diff --git a/node_modules/msw/src/core/passthrough.test.ts b/node_modules/msw/src/core/passthrough.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a7a5ee21f5c74e1945fb75e160e0a3a18b4365f --- /dev/null +++ b/node_modules/msw/src/core/passthrough.test.ts @@ -0,0 +1,11 @@ +// @vitest-environment node +import { passthrough } from './passthrough' + +it('creates a 302 response with the intention header', () => { + const response = passthrough() + + expect(response).toBeInstanceOf(Response) + expect(response.status).toBe(302) + expect(response.statusText).toBe('Passthrough') + expect(response.headers.get('x-msw-intention')).toBe('passthrough') +}) diff --git a/node_modules/msw/src/core/passthrough.ts b/node_modules/msw/src/core/passthrough.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d28f83f6b5ae8b6e4e08dd34cf8c9a37bb1f884 --- /dev/null +++ b/node_modules/msw/src/core/passthrough.ts @@ -0,0 +1,25 @@ +import type { HttpResponse } from './HttpResponse' + +/** + * Performs the intercepted request as-is. + * + * This stops request handler lookup so no other handlers + * can affect this request past this point. + * Unlike `bypass()`, this will not trigger an additional request. + * + * @example + * http.get('/resource', () => { + * return passthrough() + * }) + * + * @see {@link https://mswjs.io/docs/api/passthrough `passthrough()` API reference} + */ +export function passthrough(): HttpResponse { + return new Response(null, { + status: 302, + statusText: 'Passthrough', + headers: { + 'x-msw-intention': 'passthrough', + }, + }) as HttpResponse +} diff --git a/node_modules/msw/src/core/sharedOptions.ts b/node_modules/msw/src/core/sharedOptions.ts new file mode 100644 index 0000000000000000000000000000000000000000..1881cff2f2a8a2c744adc8ff8d423b161c1a0cb1 --- /dev/null +++ b/node_modules/msw/src/core/sharedOptions.ts @@ -0,0 +1,71 @@ +import type { Emitter, DefaultEventMap } from 'rettime' +import type { UnhandledRequestStrategy } from './utils/request/onUnhandledRequest' + +export interface SharedOptions { + /** + * Specifies how to react to a request that has no corresponding + * request handler. Warns on unhandled requests by default. + * + * @example worker.start({ onUnhandledRequest: 'bypass' }) + * @example worker.start({ onUnhandledRequest: 'warn' }) + * @example server.listen({ onUnhandledRequest: 'error' }) + */ + onUnhandledRequest?: UnhandledRequestStrategy +} + +/** + * @deprecated + * Please use `HttpNetworkFrameEventMap` or `WebSocketNetworkFrameEventMap` instead. + */ +export type LifeCycleEventsMap = { + 'request:start': [ + args: { + request: Request + requestId: string + }, + ] + 'request:match': [ + args: { + request: Request + requestId: string + }, + ] + 'request:unhandled': [ + args: { + request: Request + requestId: string + }, + ] + 'request:end': [ + args: { + request: Request + requestId: string + }, + ] + 'response:mocked': [ + args: { + response: Response + request: Request + requestId: string + }, + ] + 'response:bypass': [ + args: { + response: Response + request: Request + requestId: string + }, + ] + unhandledException: [ + args: { + error: Error + request: Request + requestId: string + }, + ] +} + +export type LifeCycleEventEmitter = Pick< + Emitter, + 'on' | 'removeListener' | 'removeAllListeners' +> diff --git a/node_modules/msw/src/core/sse.ts b/node_modules/msw/src/core/sse.ts new file mode 100644 index 0000000000000000000000000000000000000000..a07b378f25765d309869eebf50bdc554c5ad5846 --- /dev/null +++ b/node_modules/msw/src/core/sse.ts @@ -0,0 +1,1017 @@ +import { invariant } from 'outvariant' +import { DeferredPromise } from '@open-draft/deferred-promise' +import { Emitter } from 'strict-event-emitter' +import type { ResponseResolver } from './handlers/RequestHandler' +import { + HttpHandler, + type HttpRequestResolverExtras, + type HttpRequestParsedResult, +} from './handlers/HttpHandler' +import type { ResponseResolutionContext } from '#core/utils/executeHandlers' +import type { Path, PathParams } from './utils/matching/matchRequestUrl' +import { delay } from './delay' +import { getTimestamp } from './utils/logging/getTimestamp' +import { devUtils } from './utils/internal/devUtils' +import { colors } from './ws/utils/attachWebSocketLogger' +import { toPublicUrl } from './utils/request/toPublicUrl' + +type EventMapConstraint = { + message?: unknown + [key: string]: unknown + [key: symbol | number]: never +} + +export type ServerSentEventResolverExtras< + EventMap extends EventMapConstraint, + Params extends PathParams, +> = HttpRequestResolverExtras & { + client: ServerSentEventClient + server: ServerSentEventServer +} + +export type ServerSentEventResolver< + EventMap extends EventMapConstraint, + Params extends PathParams, +> = ResponseResolver, any, any> + +export type ServerSentEventRequestHandler = < + EventMap extends EventMapConstraint = { message: unknown }, + Params extends PathParams = PathParams, + RequestPath extends Path = Path, +>( + path: RequestPath, + resolver: ServerSentEventResolver, +) => HttpHandler + +export type ServerSentEventMessage< + EventMap extends EventMapConstraint = { message: unknown }, +> = + | ToEventDiscriminatedUnion + | { + id?: never + event?: never + data?: never + retry: number + } + +/** + * Intercept Server-Sent Events (SSE). + * + * @example + * sse('http://localhost:4321', ({ client }) => { + * client.send({ data: 'hello world' }) + * }) + * + * @see {@link https://mswjs.io/docs/sse/ Mocking Server-Sent Events} + * @see {@link https://mswjs.io/docs/api/sse `sse()` API reference} + */ +export const sse: ServerSentEventRequestHandler = (path, resolver) => { + return new ServerSentEventHandler(path, resolver) +} + +const SSE_RESPONSE_INIT: ResponseInit = { + headers: { + 'content-type': 'text/event-stream', + 'cache-control': 'no-cache', + connection: 'keep-alive', + }, +} + +class ServerSentEventHandler< + EventMap extends EventMapConstraint, +> extends HttpHandler { + #emitter: Emitter + + constructor(path: Path, resolver: ServerSentEventResolver) { + invariant( + typeof EventSource !== 'undefined', + 'Failed to construct a Server-Sent Event handler for path "%s": the EventSource API is not supported in this environment', + path, + ) + + super('GET', path, async (info) => { + const { client, server, response } = createEventStream( + info.request, + ) + + client[kClientEmitter] = this.#emitter + + await resolver({ + ...info, + client, + server, + }) + + return response + }) + + this.#emitter = new Emitter() + } + + async predicate(args: { + request: Request + parsedResult: HttpRequestParsedResult + resolutionContext?: ResponseResolutionContext + }) { + if (args.request.headers.get('accept') !== 'text/event-stream') { + return false + } + + const matches = await super.predicate(args) + + if (matches && !args.resolutionContext?.quiet) { + /** + * @note Log the intercepted request early. + * Normally, the `this.log()` method is called when the handler returns a response. + * For SSE, call that method earlier so the logs are in correct order. + */ + await super.log({ + request: args.request, + /** + * @note Construct a placeholder response since SSE response + * is being streamed and cannot be cloned/consumed for logging. + */ + response: new Response('[streaming]', SSE_RESPONSE_INIT), + }) + + this.#attachClientLogger(args.request, this.#emitter) + } + + return matches + } + + async log(_args: { request: Request; response: Response }): Promise { + /** + * @note Skip the default `this.log()` logic so that when this handler is logged + * upon handling the request, nothing is printed (we log SSE requests early). + */ + return + } + + #attachClientLogger( + request: Request, + emitter: Emitter, + ): void { + const publicUrl = toPublicUrl(request.url) + + /* eslint-disable no-console */ + emitter.on('message', (payload) => { + console.groupCollapsed( + devUtils.formatMessage( + `${getTimestamp()} SSE %s %c⇣%c ${payload.event}`, + ), + publicUrl, + `color:${colors.mocked}`, + 'color:inherit', + ) + console.log(payload.frames) + console.groupEnd() + }) + + emitter.on('error', () => { + console.groupCollapsed( + devUtils.formatMessage(`${getTimestamp()} SSE %s %c\u00D7%c error`), + publicUrl, + `color: ${colors.system}`, + 'color:inherit', + ) + console.log('Handler:', this) + console.groupEnd() + }) + + emitter.on('close', () => { + console.groupCollapsed( + devUtils.formatMessage(`${getTimestamp()} SSE %s %c■%c close`), + publicUrl, + `colors:${colors.system}`, + 'color:inherit', + ) + console.log('Handler:', this) + console.groupEnd() + }) + /* eslint-enable no-console */ + } +} + +type Values = T[keyof T] +type Identity = { [K in keyof T]: T[K] } & unknown +type ToEventDiscriminatedUnion = Values<{ + [K in keyof T]: Identity< + (K extends 'message' + ? { + id?: string + event?: K + data?: T[K] + retry?: never + } + : { + id?: string + event: K + data?: T[K] + retry?: never + }) & + // Make the `data` field conditionally required through an intersection. + (undefined extends T[K] ? unknown : { data: unknown }) + > +}> + +type ServerSentEventClientEventMap = { + message: [payload: EventStreamMessage] + error: [] + close: [] +} + +const kClientEmitter = Symbol.for('kClientEmitter') + +class ServerSentEventClient< + EventMap extends EventMapConstraint = { message: unknown }, +> { + private [kClientEmitter]?: Emitter + + #encoder: TextEncoder + #writer: WritableStreamDefaultWriter + + constructor(writable: WritableStream) { + this.#encoder = new TextEncoder() + this.#writer = writable.getWriter() + } + + /** + * Sends the given payload to the intercepted `EventSource`. + */ + public send(payload: ServerSentEventMessage): void { + if ('retry' in payload && payload.retry != null) { + this.#sendRetry(payload.retry) + return + } + + this.#sendMessage({ + id: payload.id, + event: payload.event, + data: + typeof payload.data === 'object' + ? JSON.stringify(payload.data) + : payload.data, + }) + } + + /** + * Dispatches the given event on the intercepted `EventSource`. + */ + public dispatchEvent(event: Event) { + if (event instanceof MessageEvent) { + /** + * @note Use the internal send mechanism to skip normalization + * of the message data (already normalized by the server). + */ + this.#sendMessage({ + id: event.lastEventId || undefined, + event: event.type === 'message' ? undefined : event.type, + data: event.data, + }) + return + } + + if (event.type === 'error') { + this.error() + return + } + + if (event.type === 'close') { + this.close() + return + } + } + + /** + * Errors the underlying `EventSource`, closing the connection with an error. + * This is equivalent to aborting the connection and will produce a `TypeError: Failed to fetch` + * error. + */ + public error(): void { + this.#writer.abort().catch((error) => { + console.error(error) + devUtils.error( + 'Failed to abort server-side EventSource. Please see the original error above.', + ) + }) + this[kClientEmitter]?.emit('error') + } + + /** + * Closes the underlying `EventSource`, closing the connection. + */ + public close(): void { + this.#writer.close().catch((error) => { + console.error(error) + devUtils.error( + 'Failed to close server-side EventSource. Please see the original error above.', + ) + }) + this[kClientEmitter]?.emit('close') + } + + #sendRetry(retry: number): void { + this.#writer + .write(this.#encoder.encode(`retry:${retry}\n\n`)) + .catch((error) => { + console.error(error) + devUtils.error( + 'Failed to send a retry packet to server-side EventSource. Please see the original error above.', + ) + }) + } + + #sendMessage(message: { + id?: string + event?: unknown + data: unknown | undefined + }): void { + const frames: Array = [] + + if (message.id) { + frames.push(`id:${message.id}`) + } + + if (message.event) { + frames.push(`event:${message.event.toString()}`) + } + + if (message.data != null) { + /** + * Split data on line terminators (LF, CR, or CRLF) and translate them to individual frames. + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream + */ + for (const line of message.data.toString().split(/\r\n|\r|\n/)) { + frames.push(`data:${line}`) + } + } + + frames.push('', '') + + this.#writer + .write(this.#encoder.encode(frames.join('\n'))) + .catch((error) => { + console.error(error) + devUtils.error( + 'Failed to send a message to server-side EventSource. Please see the original error above.', + ) + }) + + this[kClientEmitter]?.emit('message', { + id: message.id, + event: message.event?.toString() || 'message', + data: message.data, + frames, + }) + } +} + +class ServerSentEventServer { + #request: Request + #client: ServerSentEventClient + + constructor(args: { request: Request; client: ServerSentEventClient }) { + this.#request = args.request + this.#client = args.client + } + + /** + * Establishes the actual connection for this SSE request + * and returns the `EventSource` instance. + */ + public connect(): EventSource { + const source = new ObservableEventSource(this.#request.url, { + withCredentials: this.#request.credentials === 'include', + headers: { + /** + * @note Mark this request as passthrough so it doesn't trigger + * an infinite loop matching against the existing request handler. + */ + accept: 'msw/passthrough', + }, + signal: this.#request.signal, + }) + + source[kOnAnyMessage] = (event) => { + Object.defineProperties(event, { + target: { + value: this, + enumerable: true, + writable: true, + configurable: true, + }, + }) + + // Schedule the server-to-client forwarding for the next tick + // so the user can prevent the message event. + queueMicrotask(() => { + if (!event.defaultPrevented) { + this.#client.dispatchEvent(event) + } + }) + } + + // Forward stream errors from the actual server to the client. + source.addEventListener('error', (event) => { + Object.defineProperties(event, { + target: { + value: this, + enumerable: true, + writable: true, + configurable: true, + }, + }) + + queueMicrotask(() => { + // Allow the user to opt-out from this forwarding. + if (!event.defaultPrevented) { + this.#client.dispatchEvent(event) + } + }) + }) + + return source + } +} + +interface ObservableEventSourceInit extends EventSourceInit { + headers?: HeadersInit + signal?: AbortSignal +} + +type EventHandler = ( + this: EventSource, + event: EventType, +) => any + +const kRequest = Symbol('kRequest') +const kReconnectionTime = Symbol('kReconnectionTime') +const kLastEventId = Symbol('kLastEventId') +const kAbortController = Symbol('kAbortController') +const kOnOpen = Symbol('kOnOpen') +const kOnMessage = Symbol('kOnMessage') +const kOnAnyMessage = Symbol('kOnAnyMessage') +const kOnError = Symbol('kOnError') + +class ObservableEventSource extends EventTarget implements EventSource { + static readonly CONNECTING = 0 + static readonly OPEN = 1 + static readonly CLOSED = 2 + + public readonly CONNECTING = ObservableEventSource.CONNECTING + public readonly OPEN = ObservableEventSource.OPEN + public readonly CLOSED = ObservableEventSource.CLOSED + + public readyState: number + public url: string + public withCredentials: boolean + + private [kRequest]: Request + private [kReconnectionTime]: number + private [kLastEventId]: string + private [kAbortController]: AbortController + private [kOnOpen]: EventHandler | null = null + private [kOnMessage]: EventHandler | null = null + private [kOnAnyMessage]: EventHandler | null = null + private [kOnError]: EventHandler | null = null + + constructor(url: string | URL, init?: ObservableEventSourceInit) { + super() + + this.url = new URL(url).href + this.withCredentials = init?.withCredentials ?? false + + this.readyState = this.CONNECTING + + // Support custom request init. + const headers = new Headers(init?.headers || {}) + headers.append('accept', 'text/event-stream') + + this[kAbortController] = new AbortController() + this[kReconnectionTime] = 2000 + this[kLastEventId] = '' + this[kRequest] = new Request(this.url, { + method: 'GET', + headers, + credentials: this.withCredentials ? 'include' : 'omit', + signal: this[kAbortController].signal, + }) + + if (init?.signal) { + if (init.signal.aborted) { + this.close() + return + } + + init.signal.addEventListener('abort', () => this.close(), { + once: true, + signal: this[kAbortController].signal, + }) + } + + this.connect() + } + + get onopen(): EventHandler | null { + return this[kOnOpen] + } + + set onopen(handler: EventHandler) { + if (this[kOnOpen]) { + this.removeEventListener('open', this[kOnOpen]) + } + this[kOnOpen] = handler.bind(this) + this.addEventListener('open', this[kOnOpen]) + } + + get onmessage(): EventHandler | null { + return this[kOnMessage] + } + set onmessage(handler: EventHandler) { + if (this[kOnMessage]) { + this.removeEventListener('message', { handleEvent: this[kOnMessage] }) + } + this[kOnMessage] = handler.bind(this) + this.addEventListener('message', { handleEvent: this[kOnMessage] }) + } + + get onerror(): EventHandler | null { + return this[kOnError] + } + set onerror(handler: EventHandler) { + if (this[kOnError]) { + this.removeEventListener('error', { handleEvent: this[kOnError] }) + } + this[kOnError] = handler.bind(this) + this.addEventListener('error', { handleEvent: this[kOnError] }) + } + + public addEventListener( + type: K, + listener: EventHandler, + options?: boolean | AddEventListenerOptions, + ): void + public addEventListener( + type: string, + listener: EventHandler, + options?: boolean | AddEventListenerOptions, + ): void + public addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void + + public addEventListener( + type: string, + listener: EventHandler | EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void { + super.addEventListener( + type, + listener as EventListenerOrEventListenerObject, + options, + ) + } + + public removeEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | EventListenerOptions, + ): void + public removeEventListener( + type: string, + listener: (this: EventSource, event: MessageEvent) => any, + options?: boolean | EventListenerOptions, + ): void + public removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, + ): void + + public removeEventListener( + type: string, + listener: EventHandler | EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void { + super.removeEventListener( + type, + listener as EventListenerOrEventListenerObject, + options, + ) + } + + public dispatchEvent(event: Event): boolean { + return super.dispatchEvent(event) + } + + public close(): void { + this[kAbortController].abort() + this.readyState = this.CLOSED + } + + private async connect() { + await fetch(this[kRequest]) + .then((response) => { + this.processResponse(response) + }) + .catch(() => { + // Fail the connection on request errors instead of + // throwing a generic "Failed to fetch" error. + this.failConnection() + }) + } + + private processResponse(response: Response): void { + if (!response.body) { + this.failConnection() + return + } + + if (isNetworkError(response)) { + this.reestablishConnection() + return + } + + if ( + response.status !== 200 || + response.headers.get('content-type') !== 'text/event-stream' + ) { + this.failConnection() + return + } + + this.announceConnection() + this.interpretResponseBody(response) + } + + private announceConnection(): void { + queueMicrotask(() => { + if (this.readyState !== this.CLOSED) { + this.readyState = this.OPEN + this.dispatchEvent(new Event('open')) + } + }) + } + + private interpretResponseBody(response: Response): void { + const parsingStream = new EventSourceParsingStream({ + message: (message) => { + if (message.id) { + this[kLastEventId] = message.id + } + + const messageEvent = new MessageEvent( + message.event ? message.event : 'message', + { + data: message.data, + origin: this[kRequest].url, + lastEventId: this[kLastEventId], + cancelable: true, + }, + ) + + this[kOnAnyMessage]?.(messageEvent) + this.dispatchEvent(messageEvent) + }, + retry: (reconnectionTime) => { + this[kReconnectionTime] = reconnectionTime + }, + abort: () => { + throw new Error('Stream abort is not implemented') + }, + close: () => { + this.failConnection() + }, + }) + + response + .body!.pipeTo(parsingStream) + .then(() => { + this.processResponseEndOfBody(response) + }) + .catch(() => { + this.failConnection() + }) + } + + private processResponseEndOfBody(response: Response): void { + if (!isNetworkError(response)) { + this.reestablishConnection() + } + } + + private async reestablishConnection(): Promise { + queueMicrotask(() => { + if (this.readyState === this.CLOSED) { + return + } + + this.readyState = this.CONNECTING + this.dispatchEvent(new Event('error')) + }) + + const signal = this[kAbortController].signal + + if (signal.aborted) { + return + } + + const aborted = new DeferredPromise() + const onAbort = () => aborted.resolve() + signal.addEventListener('abort', onAbort, { once: true }) + + await Promise.race([delay(this[kReconnectionTime]), aborted]).finally( + () => { + signal.removeEventListener('abort', onAbort) + }, + ) + + if (signal.aborted) { + return + } + + queueMicrotask(async () => { + if (this.readyState !== this.CONNECTING) { + return + } + + if (this[kLastEventId] !== '') { + this[kRequest].headers.set('last-event-id', this[kLastEventId]) + } + + await this.connect() + }) + } + + private failConnection(): void { + queueMicrotask(() => { + if (this.readyState !== this.CLOSED) { + this.readyState = this.CLOSED + this.dispatchEvent(new Event('error')) + } + }) + } +} + +/** + * Checks if the given `Response` instance is a network error. + * @see https://fetch.spec.whatwg.org/#concept-network-error + */ +function isNetworkError(response: Response): boolean { + return ( + response.type === 'error' && + response.status === 0 && + response.statusText === '' && + Array.from(response.headers.entries()).length === 0 && + response.body === null + ) +} + +const enum ControlCharacters { + NewLine = 10, + CarriageReturn = 13, + Space = 32, + Colon = 58, +} + +interface EventSourceMessage { + id?: string + event?: string + data?: string +} + +class EventSourceParsingStream extends WritableStream { + private decoder: TextDecoder + + private buffer?: Uint8Array + private position: number + private fieldLength?: number + private discardTrailingNewline = false + + private message: EventSourceMessage = { + id: undefined, + event: undefined, + data: undefined, + } + + constructor( + private underlyingSink: { + message: (message: EventSourceMessage) => void + retry?: (reconnectionTime: number) => void + abort?: (reason: any) => void + close?: () => void + }, + ) { + super({ + write: (chunk) => { + this.processResponseBodyChunk(chunk) + }, + abort: (reason) => { + this.underlyingSink.abort?.(reason) + }, + close: () => { + this.underlyingSink.close?.() + }, + }) + + this.decoder = new TextDecoder() + this.position = 0 + } + + private resetMessage(): void { + this.message = { + id: undefined, + event: undefined, + data: undefined, + } + } + + private processResponseBodyChunk(chunk: Uint8Array): void { + if (this.buffer == null) { + this.buffer = chunk + this.position = 0 + this.fieldLength = -1 + } else { + const nextBuffer = new Uint8Array(this.buffer.length + chunk.length) + nextBuffer.set(this.buffer) + nextBuffer.set(chunk, this.buffer.length) + this.buffer = nextBuffer + } + + const bufferLength = this.buffer.length + let lineStart = 0 + + while (this.position < bufferLength) { + if (this.discardTrailingNewline) { + if (this.buffer[this.position] === ControlCharacters.NewLine) { + lineStart = ++this.position + } + + this.discardTrailingNewline = false + } + + let lineEnd = -1 + + for (; this.position < bufferLength && lineEnd === -1; ++this.position) { + switch (this.buffer[this.position]) { + case ControlCharacters.Colon: { + if (this.fieldLength === -1) { + this.fieldLength = this.position - lineStart + } + break + } + + case ControlCharacters.CarriageReturn: { + this.discardTrailingNewline = true + break + } + + case ControlCharacters.NewLine: { + lineEnd = this.position + break + } + } + } + + if (lineEnd === -1) { + break + } + + this.processLine( + this.buffer.subarray(lineStart, lineEnd), + this.fieldLength!, + ) + + lineStart = this.position + this.fieldLength = -1 + } + + if (lineStart === bufferLength) { + this.buffer = undefined + } else if (lineStart !== 0) { + this.buffer = this.buffer.subarray(lineStart) + this.position -= lineStart + } + } + + private processLine(line: Uint8Array, fieldLength: number): void { + // New line indicates the end of the message. Dispatch it. + if (line.length === 0) { + // Prevent dispatching the message if the data is an empty string. + // That is a no-op per spec. + if (this.message.data === undefined) { + this.message.event = undefined + return + } + + this.underlyingSink.message(this.message) + this.resetMessage() + return + } + + // Otherwise, keep accumulating message fields until the new line. + if (fieldLength > 0) { + const field = this.decoder.decode(line.subarray(0, fieldLength)) + const valueOffset = + fieldLength + + (line[fieldLength + 1] === ControlCharacters.Space ? 2 : 1) + const value = this.decoder.decode(line.subarray(valueOffset)) + + switch (field) { + case 'data': { + this.message.data = this.message.data + ? this.message.data + '\n' + value + : value + break + } + + case 'event': { + this.message.event = value + break + } + + case 'id': { + this.message.id = value + break + } + + case 'retry': { + /** + * Apply the retry immediately. Don't buffer onto the current message. + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation + */ + if (/^\d+$/.test(value)) { + this.underlyingSink.retry?.(parseInt(value, 10)) + } + break + } + } + } + } +} + +interface EventStreamMessage { + id?: string + event: string + data?: unknown + frames: Array +} + +interface EventStream { + client: ServerSentEventClient + server: ServerSentEventServer + response: Response +} + +/** + * Create an event stream out of the given Fetch API `Request`. + * Returns the following properties: + * - `client`, to operate on the intercepted request; + * - `server`, to establish and manage the actual server connection; + * - `response`, a `Response` to use as the mock response's body. + * + * @example + * http.post('/resource', ({ request }) => { + * const { client, server, response } = createEventStream(request) + * client.send({ data: 'hello world' }) + * return response + * }) + */ +function createEventStream( + request: Request, +): EventStream { + invariant( + !request.signal.aborted, + 'Failed to call "createEventStream" on the "%s %s" request: request aborted', + request.method, + request.url, + ) + + const { readable, writable } = new TransformStream() + + const client = new ServerSentEventClient(writable) + const server = new ServerSentEventServer({ + request, + client, + }) + + const response = new Response(readable, SSE_RESPONSE_INIT) + + request.signal.addEventListener( + 'abort', + () => { + client.close() + }, + { once: true }, + ) + + return { + client, + server, + response, + } +} diff --git a/node_modules/msw/src/core/typeUtils.ts b/node_modules/msw/src/core/typeUtils.ts new file mode 100644 index 0000000000000000000000000000000000000000..8cf6dcead1fc29f401f4111f66be538f0d667ed3 --- /dev/null +++ b/node_modules/msw/src/core/typeUtils.ts @@ -0,0 +1,26 @@ +type Fn = (...arg: any[]) => any + +export type MaybePromise = T | Promise + +export type RequiredDeep< + Type, + U extends Record | Fn | undefined = undefined, +> = Type extends Fn + ? Type + : /** + * @note The "Fn" type satisfies the predicate below. + * It must always come first, before the Record check. + */ + Type extends Record + ? { + [Key in keyof Type]-?: NonNullable extends NonNullable + ? NonNullable + : RequiredDeep, U> + } + : Type + +/** + * @fixme Remove this once TS 5.4 is the lowest supported version. + * Because "NoInfer" is a built-in type utility there. + */ +export type NoInfer = [T][T extends any ? 0 : never] diff --git a/node_modules/msw/src/core/utils/HttpResponse/decorators.ts b/node_modules/msw/src/core/utils/HttpResponse/decorators.ts new file mode 100644 index 0000000000000000000000000000000000000000..0025ff2c150e87332e3a3e61d3da2626e9208960 --- /dev/null +++ b/node_modules/msw/src/core/utils/HttpResponse/decorators.ts @@ -0,0 +1,61 @@ +import statuses from '../../../shims/statuses' +import type { HttpResponseInit } from '../../HttpResponse' + +const { message } = statuses + +const kSetCookie = Symbol('kSetCookie') + +export interface HttpResponseDecoratedInit extends HttpResponseInit { + status: number + statusText: string + headers: Headers +} + +export function normalizeResponseInit( + init: HttpResponseInit = {}, +): HttpResponseDecoratedInit { + const status = init?.status || 200 + const statusText = init?.statusText || message[status] || '' + const headers = new Headers(init?.headers) + + return { + ...init, + headers, + status, + statusText, + } +} + +export function decorateResponse( + response: Response, + init: HttpResponseDecoratedInit, +): Response { + // Allow mocking the response type. + if (init.type) { + Object.defineProperty(response, 'type', { + value: init.type, + enumerable: true, + writable: false, + }) + } + + const responseCookies = init.headers.get('set-cookie') + + if (responseCookies) { + // Record the raw "Set-Cookie" response header provided + // in the HeadersInit. This is later used to store these cookies + // in cookie jar and return the right cookies in the "cookies" + // response resolver argument. + Object.defineProperty(response, kSetCookie, { + value: responseCookies, + enumerable: false, + writable: false, + }) + } + + return response +} + +export function getRawSetCookie(response: Response): string | undefined { + return Reflect.get(response, kSetCookie) +} diff --git a/node_modules/msw/src/core/utils/cookieStore.ts b/node_modules/msw/src/core/utils/cookieStore.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b7646ea36d4a25a3b729aa319d8bf7a58be414f --- /dev/null +++ b/node_modules/msw/src/core/utils/cookieStore.ts @@ -0,0 +1,95 @@ +import { isNodeProcess } from 'is-node-process' +import { invariant } from 'outvariant' +import { + Cookie, + CookieJar, + MemoryCookieStore, + type SerializedCookie, + type MemoryCookieStoreIndex, +} from 'tough-cookie' +import { jsonParse } from './internal/jsonParse' + +class CookieStore { + #storageKey = '__msw-cookie-store__' + #jar: CookieJar + #memoryStore: MemoryCookieStore + + constructor() { + if (!isNodeProcess()) { + invariant( + typeof localStorage !== 'undefined', + 'Failed to create a CookieStore: `localStorage` is not available in this environment. This is likely an issue with your environment, which has been detected as browser (or browser-like) environment and must implement global browser APIs correctly.', + ) + } + + this.#memoryStore = new MemoryCookieStore() + this.#memoryStore.idx = this.getCookieStoreIndex() + this.#jar = new CookieJar(this.#memoryStore) + } + + public getCookies(url: string): Array { + return this.#jar.getCookiesSync(url) + } + + public async setCookie(cookieName: string, url: string): Promise { + await this.#jar.setCookie(cookieName, url) + this.persist() + } + + private getCookieStoreIndex(): MemoryCookieStoreIndex { + if ( + typeof localStorage === 'undefined' || + typeof localStorage.getItem !== 'function' + ) { + return {} + } + + const cookiesString = localStorage.getItem(this.#storageKey) + if (cookiesString == null) { + return {} + } + + const rawCookies = jsonParse>>(cookiesString) + if (rawCookies == null) { + return {} + } + + const cookies: MemoryCookieStoreIndex = {} + + for (const rawCookie of rawCookies) { + const cookie = Cookie.fromJSON(rawCookie) + + if (cookie != null && cookie.domain != null && cookie.path != null) { + cookies[cookie.domain] ||= {} + cookies[cookie.domain][cookie.path] ||= {} + cookies[cookie.domain][cookie.path][cookie.key] = cookie + } + } + + return cookies + } + + private persist(): void { + if ( + typeof localStorage === 'undefined' || + typeof localStorage.setItem !== 'function' + ) { + return + } + + const data: Array = [] + const { idx } = this.#memoryStore + + for (const domain in idx) { + for (const path in idx[domain]) { + for (const key in idx[domain][path]) { + data.push(idx[domain][path][key].toJSON()) + } + } + } + + localStorage.setItem(this.#storageKey, JSON.stringify(data)) + } +} + +export const cookieStore = new CookieStore() diff --git a/node_modules/msw/src/core/utils/executeHandlers.ts b/node_modules/msw/src/core/utils/executeHandlers.ts new file mode 100644 index 0000000000000000000000000000000000000000..c740961c27a31401beee1a5f21e6c192a0346577 --- /dev/null +++ b/node_modules/msw/src/core/utils/executeHandlers.ts @@ -0,0 +1,67 @@ +import type { RequestHandler } from '../handlers/RequestHandler' +import { type RequestHandlerExecutionResult } from '../handlers/RequestHandler' + +export interface HandlersExecutionResult { + handler: RequestHandler + parsedResult?: any + response?: Response +} + +export interface ResponseResolutionContext { + /** + * A base url to use when resolving relative urls. + * @note This is primarily used by the `@mswjs/http-middleware` + * to resolve relative urls in the context of the running server + */ + baseUrl?: string + quiet?: boolean +} + +/** + * Executes the list of request handlers against the given request. + * Returns the execution result object containing any matching request + * handler and any mocked response it returned. + */ +export const executeHandlers = async >({ + request, + requestId, + handlers, + resolutionContext, +}: { + request: Request + requestId: string + handlers: Handlers + resolutionContext?: ResponseResolutionContext +}): Promise => { + let matchingHandler: RequestHandler | null = null + let result: RequestHandlerExecutionResult | null = null + + for (const handler of handlers) { + result = await handler.run({ request, requestId, resolutionContext }) + + // If the handler produces some result for this request, + // it automatically becomes matching. + if (result !== null) { + matchingHandler = handler + } + + // Stop the lookup if this handler returns a mocked response. + // If it doesn't, it will still be considered the last matching + // handler until any of them returns a response. This way we can + // distinguish between fallthrough handlers without responses + // and the lack of a matching handler. + if (result?.response) { + break + } + } + + if (matchingHandler) { + return { + handler: matchingHandler, + parsedResult: result?.parsedResult, + response: result?.response, + } + } + + return null +} diff --git a/node_modules/msw/src/core/utils/handleRequest.test.ts b/node_modules/msw/src/core/utils/handleRequest.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..37e2b5790ffba3688779c6b67445314db51dd8f6 --- /dev/null +++ b/node_modules/msw/src/core/utils/handleRequest.test.ts @@ -0,0 +1,574 @@ +// @vitest-environment jsdom +import { Emitter } from 'strict-event-emitter' +import { createRequestId } from '@mswjs/interceptors' +import type { LifeCycleEventsMap, SharedOptions } from '../sharedOptions' +import type { RequestHandler } from '../handlers/RequestHandler' +import { http } from '../http' +import type { HandleRequestOptions } from './handleRequest' +import { handleRequest } from './handleRequest' +import type { RequiredDeep } from '../typeUtils' +import { HttpResponse } from '../HttpResponse' +import { passthrough } from '../passthrough' + +const options: RequiredDeep = { + onUnhandledRequest: vi.fn(), +} +const handleRequestOptions: Partial> = { + onPassthroughResponse: vi.fn(), + onMockedResponse: vi.fn(), +} + +function setup() { + const emitter = new Emitter() + const listener = vi.fn() + + const createMockListener = (name: string) => { + return (...args: any) => { + listener(name, ...args) + } + } + + emitter.on('request:start', createMockListener('request:start')) + emitter.on('request:match', createMockListener('request:match')) + emitter.on('request:unhandled', createMockListener('request:unhandled')) + emitter.on('request:end', createMockListener('request:end')) + emitter.on('response:mocked', createMockListener('response:mocked')) + emitter.on('response:bypass', createMockListener('response:bypass')) + + const events = listener.mock.calls + return { emitter, events } +} + +beforeEach(() => { + vi.spyOn(global.console, 'warn').mockImplementation(() => void 0) +}) + +afterEach(() => { + vi.resetAllMocks() +}) + +test('returns undefined for a request with the "accept: msw/passthrough" header equal to "bypass"', async () => { + const { emitter, events } = setup() + + const requestId = createRequestId() + const request = new Request(new URL('http://localhost/user'), { + headers: new Headers({ + accept: 'msw/passthrough', + }), + }) + const handlers: Array = [] + + const result = await handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(result).toBeUndefined() + expect(events).toEqual([ + ['request:start', { request, requestId }], + ['request:end', { request, requestId }], + ]) + expect(options.onUnhandledRequest).not.toHaveBeenCalled() + expect(handleRequestOptions.onPassthroughResponse).toHaveBeenNthCalledWith( + 1, + request, + ) + expect(handleRequestOptions.onMockedResponse).not.toHaveBeenCalled() +}) + +test('does not bypass a request with "accept: msw/*" header set to arbitrary value', async () => { + const { emitter } = setup() + + const request = new Request(new URL('http://localhost/user'), { + headers: new Headers({ + accept: 'msw/invalid', + }), + }) + const handlers: Array = [ + http.get('/user', () => { + return HttpResponse.text('hello world') + }), + ] + + const result = await handleRequest( + request, + createRequestId(), + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(result).not.toBeUndefined() + expect(options.onUnhandledRequest).not.toHaveBeenCalled() + expect(handleRequestOptions.onMockedResponse).toHaveBeenCalledTimes(1) +}) + +test('reports request as unhandled when it has no matching request handlers', async () => { + const { emitter, events } = setup() + + const requestId = createRequestId() + const request = new Request(new URL('http://localhost/user')) + const handlers: Array = [] + + const result = await handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(result).toBeUndefined() + expect(events).toEqual([ + ['request:start', { request, requestId }], + ['request:unhandled', { request, requestId }], + ['request:end', { request, requestId }], + ]) + expect(options.onUnhandledRequest).toHaveBeenNthCalledWith(1, request, { + warning: expect.any(Function), + error: expect.any(Function), + }) + expect(handleRequestOptions.onPassthroughResponse).toHaveBeenNthCalledWith( + 1, + request, + ) + expect(handleRequestOptions.onMockedResponse).not.toHaveBeenCalled() +}) + +test('returns undefined on a request handler that returns no response', async () => { + const { emitter, events } = setup() + + const requestId = createRequestId() + const request = new Request(new URL('http://localhost/user')) + const handlers: Array = [ + http.get('/user', () => { + // Intentionally blank response resolver. + return + }), + ] + + const result = await handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(result).toBeUndefined() + expect(events).toEqual([ + ['request:start', { request, requestId }], + ['request:end', { request, requestId }], + ]) + expect(options.onUnhandledRequest).not.toHaveBeenCalled() + expect(handleRequestOptions.onPassthroughResponse).toHaveBeenNthCalledWith( + 1, + request, + ) + expect(handleRequestOptions.onMockedResponse).not.toHaveBeenCalled() + + /** + * @note Returning undefined from a resolver no longer prints a warning. + */ + expect(console.warn).toHaveBeenCalledTimes(0) +}) + +test('returns the mocked response for a request with a matching request handler', async () => { + const { emitter, events } = setup() + + const requestId = createRequestId() + const request = new Request(new URL('http://localhost/user')) + const mockedResponse = HttpResponse.json({ firstName: 'John' }) + const handlers: Array = [ + http.get('/user', () => { + return mockedResponse + }), + ] + const lookupResult = { + handler: handlers[0], + response: mockedResponse, + request, + parsedResult: { + match: { matches: true, params: {} }, + cookies: {}, + }, + } + + const result = await handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(result).toEqual(mockedResponse) + expect(events).toEqual([ + ['request:start', { request, requestId }], + ['request:match', { request, requestId }], + ['request:end', { request, requestId }], + ]) + expect(handleRequestOptions.onPassthroughResponse).not.toHaveBeenCalled() + + expect(handleRequestOptions.onMockedResponse).toHaveBeenCalledTimes(1) + const [mockedResponseParam, lookupResultParam] = + handleRequestOptions.onMockedResponse.mock.calls[0] + + expect(mockedResponseParam.status).toBe(mockedResponse.status) + expect(mockedResponseParam.statusText).toBe(mockedResponse.statusText) + expect(Object.fromEntries(mockedResponseParam.headers.entries())).toEqual( + Object.fromEntries(mockedResponse.headers.entries()), + ) + + expect(lookupResultParam).toEqual({ + handler: lookupResult.handler, + parsedResult: lookupResult.parsedResult, + response: expect.objectContaining({ + status: lookupResult.response.status, + statusText: lookupResult.response.statusText, + }), + }) +}) + +it('returns undefined without warning on a passthrough request', async () => { + const { emitter, events } = setup() + + const requestId = createRequestId() + const request = new Request(new URL('http://localhost/user')) + const handlers: Array = [ + http.get('/user', () => { + return passthrough() + }), + ] + + const result = await handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(result).toBeUndefined() + expect(events).toEqual([ + ['request:start', { request, requestId }], + ['request:end', { request, requestId }], + ]) + expect(options.onUnhandledRequest).not.toHaveBeenCalled() + expect(handleRequestOptions.onPassthroughResponse).toHaveBeenNthCalledWith( + 1, + request, + ) + expect(handleRequestOptions.onMockedResponse).not.toHaveBeenCalled() +}) + +it('calls the handler with the requestId', async () => { + const { emitter } = setup() + + const requestId = createRequestId() + const request = new Request(new URL('http://localhost/user')) + const handlerFn = vi.fn() + const handlers: Array = [http.get('/user', handlerFn)] + + await handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(handlerFn).toHaveBeenCalledWith(expect.objectContaining({ requestId })) +}) + +it('marks the first matching one-time handler as used', async () => { + const { emitter } = setup() + + const oneTimeHandler = http.get( + '/resource', + () => { + return HttpResponse.text('One-time') + }, + { once: true }, + ) + const anotherHandler = http.get('/resource', () => { + return HttpResponse.text('Another') + }) + const handlers: Array = [oneTimeHandler, anotherHandler] + + const requestId = createRequestId() + const request = new Request('http://localhost/resource') + const firstResult = await handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(await firstResult?.text()).toBe('One-time') + expect(oneTimeHandler.isUsed).toBe(true) + expect(anotherHandler.isUsed).toBe(false) + + const secondResult = await handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(await secondResult?.text()).toBe('Another') + expect(anotherHandler.isUsed).toBe(true) + expect(oneTimeHandler.isUsed).toBe(true) +}) + +it('does not mark non-matching one-time handlers as used', async () => { + const { emitter } = setup() + + const oneTimeHandler = http.get( + '/resource', + () => { + return HttpResponse.text('One-time') + }, + { once: true }, + ) + const anotherHandler = http.get( + '/another', + () => { + return HttpResponse.text('Another') + }, + { once: true }, + ) + const handlers: Array = [oneTimeHandler, anotherHandler] + + const requestId = createRequestId() + const firstResult = await handleRequest( + new Request('http://localhost/another'), + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(await firstResult?.text()).toBe('Another') + expect(oneTimeHandler.isUsed).toBe(false) + expect(anotherHandler.isUsed).toBe(true) + + const secondResult = await handleRequest( + new Request('http://localhost/resource'), + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(await secondResult?.text()).toBe('One-time') + expect(anotherHandler.isUsed).toBe(true) + expect(oneTimeHandler.isUsed).toBe(true) +}) + +it('handles parallel requests with one-time handlers', async () => { + const { emitter } = setup() + + const oneTimeHandler = http.get( + '/resource', + () => { + return HttpResponse.text('One-time') + }, + { once: true }, + ) + const anotherHandler = http.get('/resource', () => { + return HttpResponse.text('Another') + }) + const handlers: Array = [oneTimeHandler, anotherHandler] + + const requestId = createRequestId() + const request = new Request('http://localhost/resource') + const firstResultPromise = handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + const secondResultPromise = handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + const firstResult = await firstResultPromise + const secondResult = await secondResultPromise + + expect(await firstResult?.text()).toBe('One-time') + expect(await secondResult?.text()).toBe('Another') + expect(oneTimeHandler.isUsed).toBe(true) + expect(anotherHandler.isUsed).toBe(true) +}) + +describe('[Private] - resolutionContext - used for extensions', () => { + describe('#baseUrl', () => { + test('when defined, handle requests to that base url only defining pathnames in the handler', async () => { + const { emitter } = setup() + + const baseUrl = 'http://this-base-url-works.com' + const handleRequestOptionsWithBaseUrl: HandleRequestOptions = { + ...handleRequestOptions, + resolutionContext: { baseUrl }, + } + + const handler = http.get('/resource', () => { + return HttpResponse.text('Mocked response') + }) + + const handlers: Array = [handler] + + const requestId = createRequestId() + const request = new Request(new URL('/resource', baseUrl)) + const response = await handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptionsWithBaseUrl, + ) + + expect(await response?.text()).toBe('Mocked response') + }) + + test('when defined, do not handle requests to different base urls when defining pathnames in the handler', async () => { + const { emitter } = setup() + + const baseUrl = 'http://this-base-url-works.com' + const handleRequestOptionsWithBaseUrl: HandleRequestOptions = { + ...handleRequestOptions, + resolutionContext: { baseUrl }, + } + + const handler = http.get('/resource', () => { + return HttpResponse.text('Mocked response') + }) + + const handlers: Array = [handler] + + const requestId = createRequestId() + const request = new Request( + new URL('/resource', `http://not-the-base-url.com`), + ) + const response = await handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptionsWithBaseUrl, + ) + + expect(response).toBeUndefined() + }) + }) +}) + +describe('handler with custom predicate', () => { + test('matches if custom predicate returns true', async () => { + const { emitter, events } = setup() + + const requestId = createRequestId() + const request = new Request(new URL('http://localhost/login'), { + method: 'POST', + body: JSON.stringify({ username: 'test', password: 'password' }), + headers: { 'Content-Type': 'application/json' }, + }) + const handlers: Array = [ + http.post( + async ({ request }) => { + const body = await request.clone().json() + return body.username === 'test' && body.password === 'password' + }, + () => + HttpResponse.json({ + success: true, + }), + ), + ] + + const result = await handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(result).toBeDefined() + expect(await result?.json()).toStrictEqual({ success: true }) + expect(events).toEqual([ + ['request:start', { request, requestId }], + ['request:match', { request, requestId }], + ['request:end', { request, requestId }], + ]) + expect(handleRequestOptions.onMockedResponse).toHaveBeenCalledTimes(1) + }) + + test('does not match if custom predicate returns false', async () => { + const { emitter, events } = setup() + + const requestId = createRequestId() + const request = new Request(new URL('http://localhost/login'), { + method: 'POST', + body: JSON.stringify({ username: 'test', password: 'passwordd' }), + headers: { 'Content-Type': 'application/json' }, + }) + const handlers: Array = [ + http.post( + async ({ request }) => { + const body = await request.clone().json() + return body.username === 'test' && body.password === 'password' + }, + () => + HttpResponse.json({ + success: true, + }), + ), + ] + + const result = await handleRequest( + request, + requestId, + handlers, + options, + emitter, + handleRequestOptions, + ) + + expect(result).toBeUndefined() + expect(events).toEqual([ + ['request:start', { request, requestId }], + ['request:unhandled', { request, requestId }], + ['request:end', { request, requestId }], + ]) + expect(options.onUnhandledRequest).toHaveBeenCalledTimes(1) + expect(handleRequestOptions.onPassthroughResponse).toHaveBeenCalledTimes(1) + }) +}) diff --git a/node_modules/msw/src/core/utils/handleRequest.ts b/node_modules/msw/src/core/utils/handleRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..10252998e6b24f2660a8d3ffa87682c3eb4d5e71 --- /dev/null +++ b/node_modules/msw/src/core/utils/handleRequest.ts @@ -0,0 +1,117 @@ +import { until } from 'until-async' +import type { Emitter } from 'strict-event-emitter' +import type { LifeCycleEventsMap, SharedOptions } from '../sharedOptions' +import type { RequiredDeep } from '../typeUtils' +import type { RequestHandler } from '../handlers/RequestHandler' +import { + type HandlersExecutionResult, + type ResponseResolutionContext, + executeHandlers, +} from './executeHandlers' +import { onUnhandledRequest } from './request/onUnhandledRequest' +import { storeResponseCookies } from './request/storeResponseCookies' + +export interface HandleRequestOptions { + /** + * `resolutionContext` is not part of the general public api + * but is exposed to aid in creating extensions like + * `@mswjs/http-middleware`. + */ + resolutionContext?: ResponseResolutionContext + + /** + * Invoked whenever a request is performed as-is. + */ + onPassthroughResponse?(request: Request): void + + /** + * Invoked when the mocked response is ready to be sent. + */ + onMockedResponse?( + response: Response, + handler: RequiredDeep, + ): void +} + +export async function handleRequest( + request: Request, + requestId: string, + handlers: Array, + options: RequiredDeep, + emitter: Emitter, + handleRequestOptions?: HandleRequestOptions, +): Promise { + emitter.emit('request:start', { request, requestId }) + + // Perform requests wrapped in "bypass()" as-is. + if (request.headers.get('accept')?.includes('msw/passthrough')) { + emitter.emit('request:end', { request, requestId }) + handleRequestOptions?.onPassthroughResponse?.(request) + return + } + + // Resolve a mocked response from the list of request handlers. + const [lookupError, lookupResult] = await until(() => { + return executeHandlers({ + request, + requestId, + handlers, + resolutionContext: handleRequestOptions?.resolutionContext, + }) + }) + + if (lookupError) { + // Allow developers to react to unhandled exceptions in request handlers. + emitter.emit('unhandledException', { + error: lookupError, + request, + requestId, + }) + throw lookupError + } + + // If the handler lookup returned nothing, no request handler was found + // matching this request. Report the request as unhandled. + if (!lookupResult) { + await onUnhandledRequest(request, options.onUnhandledRequest) + emitter.emit('request:unhandled', { request, requestId }) + emitter.emit('request:end', { request, requestId }) + handleRequestOptions?.onPassthroughResponse?.(request) + return + } + + const { response } = lookupResult + + // When the handled request returned no mocked response, warn the developer, + // as it may be an oversight on their part. Perform the request as-is. + if (!response) { + emitter.emit('request:end', { request, requestId }) + handleRequestOptions?.onPassthroughResponse?.(request) + return + } + + // Perform the request as-is when the developer explicitly returned "req.passthrough()". + // This produces no warning as the request was handled. + if ( + response.status === 302 && + response.headers.get('x-msw-intention') === 'passthrough' + ) { + emitter.emit('request:end', { request, requestId }) + handleRequestOptions?.onPassthroughResponse?.(request) + return + } + + // Store all the received response cookies in the cookie jar. + await storeResponseCookies(request, response) + + emitter.emit('request:match', { request, requestId }) + + const requiredLookupResult = + lookupResult as RequiredDeep + + handleRequestOptions?.onMockedResponse?.(response, requiredLookupResult) + + emitter.emit('request:end', { request, requestId }) + + return response +} diff --git a/node_modules/msw/src/core/utils/internal/Disposable.ts b/node_modules/msw/src/core/utils/internal/Disposable.ts new file mode 100644 index 0000000000000000000000000000000000000000..6111960a96684526db44f6da5d28e0c12fd24835 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/Disposable.ts @@ -0,0 +1,33 @@ +import { devUtils } from './devUtils' + +export type DisposableSubscription = () => void + +export class Disposable { + protected subscriptions: Array = [] + + public dispose() { + let subscription: DisposableSubscription | undefined + const errors: Array = [] + + while ((subscription = this.subscriptions.shift())) { + try { + subscription() + } catch (error) { + if (error instanceof Error) { + errors.push(error) + } + } + } + + if (errors.length > 0) { + console.error( + new AggregateError( + errors, + devUtils.formatMessage( + 'Failed to dispose of some side effects. This is likely an issue with MSW, please report it on GitHub: https://github.com/mswjs/msw/issues', + ), + ), + ) + } + } +} diff --git a/node_modules/msw/src/core/utils/internal/attachSiblingHandlers.ts b/node_modules/msw/src/core/utils/internal/attachSiblingHandlers.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7a63e37475913a22f078b44245e09429270fd7f --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/attachSiblingHandlers.ts @@ -0,0 +1,28 @@ +import { invariant } from 'outvariant' +import type { AnyHandler } from '../../experimental/handlers-controller' + +const kSiblingHandlers = Symbol('kSiblingHandlers') + +export function attachSiblingHandlers( + owner: T, + siblings: Array, +): T { + invariant( + getSiblingHandlers(owner).length === 0, + 'Failed to merge handlers: the owner "%s" handler is already merged', + owner.kind, + ) + + Object.defineProperty(owner, kSiblingHandlers, { + value: siblings, + enumerable: false, + writable: false, + configurable: false, + }) + + return owner +} + +export function getSiblingHandlers(owner: AnyHandler): Array { + return Reflect.get(owner, kSiblingHandlers) || [] +} diff --git a/node_modules/msw/src/core/utils/internal/checkGlobals.ts b/node_modules/msw/src/core/utils/internal/checkGlobals.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad765eaa9b4f481f3fc8df4d8f2427f2f9f51c9f --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/checkGlobals.ts @@ -0,0 +1,17 @@ +import { invariant } from 'outvariant' +import { devUtils } from './devUtils' + +export function checkGlobals() { + /** + * MSW expects the "URL" constructor to be defined. + * It's not present in React Native so suggest a polyfill + * instead of failing silently. + * @see https://github.com/mswjs/msw/issues/1408 + */ + invariant( + typeof URL !== 'undefined', + devUtils.formatMessage( + `Global "URL" class is not defined. This likely means that you're running MSW in an environment that doesn't support all Node.js standard API (e.g. React Native). If that's the case, please use an appropriate polyfill for the "URL" class, like "react-native-url-polyfill".`, + ), + ) +} diff --git a/node_modules/msw/src/core/utils/internal/devUtils.test.ts b/node_modules/msw/src/core/utils/internal/devUtils.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..76dd2019232beb15b53d3d7700a07f78ecb2aed6 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/devUtils.test.ts @@ -0,0 +1,21 @@ +import { InternalError } from './devUtils' + +describe(InternalError, () => { + it('creates an InternalError instance', () => { + const error = new InternalError('Message') + + expect(error.name).toBe('InternalError') + expect(error.message).toBe('Message') + expect(error.toString()).toBe('InternalError: Message') + expect(error.stack).toMatch(/\w+/) + }) + + it('passes the identity check', () => { + const error = new InternalError('Message') + expect(error instanceof InternalError).toBe(true) + expect(error instanceof Error).toBe(true) + + const extraneousError = new Error('Message') + expect(extraneousError).not.toBeInstanceOf(InternalError) + }) +}) diff --git a/node_modules/msw/src/core/utils/internal/devUtils.ts b/node_modules/msw/src/core/utils/internal/devUtils.ts new file mode 100644 index 0000000000000000000000000000000000000000..08e5005e3ffca64e9b9288c2f0849a4168c3c3c6 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/devUtils.ts @@ -0,0 +1,44 @@ +import { format } from 'outvariant' + +const LIBRARY_PREFIX = '[MSW]' + +/** + * Formats a given message by appending the library's prefix string. + */ +function formatMessage(message: string, ...positionals: any[]): string { + const interpolatedMessage = format(message, ...positionals) + return `${LIBRARY_PREFIX} ${interpolatedMessage}` +} + +/** + * Prints a library-specific warning. + */ +function warn(message: string, ...positionals: any[]): void { + console.warn(formatMessage(message, ...positionals)) +} + +/** + * Prints a library-specific error. + */ +function error(message: string, ...positionals: any[]): void { + console.error(formatMessage(message, ...positionals)) +} + +export const devUtils = { + formatMessage, + warn, + error, +} + +/** + * Internal error instance. + * Used to differentiate the library errors that must be forwarded + * to the user from the unhandled exceptions. Use this if you don't + * wish for the error to be coerced to a 500 fallback response. + */ +export class InternalError extends Error { + constructor(message: string) { + super(message) + this.name = 'InternalError' + } +} diff --git a/node_modules/msw/src/core/utils/internal/getCallFrame.test.ts b/node_modules/msw/src/core/utils/internal/getCallFrame.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b9d3c1f8eb00ff73557b0918977beb941b8546f --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/getCallFrame.test.ts @@ -0,0 +1,154 @@ +/** + * @vitest-environment jsdom + */ +import { getCallFrame } from './getCallFrame' + +class ErrorWithStack extends Error { + constructor(stack: string[] | undefined | null) { + super('') + this.stack = stack?.join('\n') + } +} + +test('supports Node.js (Linux, MacOS) error stack', () => { + const linuxError = new ErrorWithStack([ + 'Error: ', + ' at getCallFrame (/Users/mock/github/msw/lib/node/index.js:3735:22)', + ' at Object.get (/Users/mock/github/msw/lib/node/index.js:3776:29)', + ' at Object. (/Users/mock/github/msw/test/msw-api/setup-server/listHandlers.test.ts:13:8)', // <-- this one + ' at Runtime._execModule (/Users/mock/github/msw/node_modules/jest-runtime/build/index.js:1299:24)', + ' at Runtime._loadModule (/Users/mock/github/msw/node_modules/jest-runtime/build/index.js:898:12)', + ' at Runtime.requireModule (/Users/mock/github/msw/node_modules/jest-runtime/build/index.js:746:10)', + ' at jasmine2 (/Users/mock/github/msw/node_modules/jest-jasmine2/build/index.js:230:13)', + ' at runTestInternal (/Users/mock/github/msw/node_modules/jest-runner/build/runTest.js:380:22)', + ' at runTest (/Users/mock/github/msw/node_modules/jest-runner/build/runTest.js:472:34)', + ]) + expect(getCallFrame(linuxError)).toEqual( + '/Users/mock/github/msw/test/msw-api/setup-server/listHandlers.test.ts:13:8', + ) + + const macOsError = new ErrorWithStack([ + 'Error: ', + ' at getCallFrame (/Users/mock/git/msw/lib/node/index.js:3735:22)', + ' at graphQLRequestHandler (/Users/mock/git/msw/lib/node/index.js:7071:25)', + ' at Object.query (/Users/mock/git/msw/lib/node/index.js:7182:18)', + ' at Object. (/Users/mock/git/msw/test/msw-api/setup-server/listHandlers.test.ts:14:11)', // <-- this one + ' at Runtime._execModule (/Users/mock/git/msw/node_modules/jest-runtime/build/index.js:1299:24)', + ' at Runtime._loadModule (/Users/mock/git/msw/node_modules/jest-runtime/build/index.js:898:12)', + ' at Runtime.requireModule (/Users/mock/git/msw/node_modules/jest-runtime/build/index.js:746:10)', + ' at jasmine2 (/Users/mock/git/msw/node_modules/jest-jasmine2/build/index.js:230:13)', + ' at runTestInternal (/Users/mock/git/msw/node_modules/jest-runner/build/runTest.js:380:22)', + ' at runTest (/Users/mock/git/msw/node_modules/jest-runner/build/runTest.js:472:34)', + ]) + + expect(getCallFrame(macOsError)).toEqual( + '/Users/mock/git/msw/test/msw-api/setup-server/listHandlers.test.ts:14:11', + ) +}) + +test('supports Node.js (Windows) error stack', () => { + const error = new ErrorWithStack([ + 'Error: ', + ' at getCallFrame (C:\\Users\\mock\\git\\msw\\lib\\node\\index.js:3735:22)', + ' at graphQLRequestHandler (C:\\Users\\mock\\git\\msw\\lib\\node\\index.js:7071:25)', + ' at Object.query (C:\\Users\\mock\\git\\msw\\lib\\node\\index.js:7182:18)', + ' at Object. (C:\\Users\\mock\\git\\msw\\test\\msw-api\\setup-server\\listHandlers.test.ts:75:13)', // <-- this one + ' at Object.asyncJestTest (C:\\Users\\mock\\git\\msw\\node_modules\\jest-jasmine2\\build\\jasmineAsyncInstall.js:106:37)', + ' at C:\\Users\\mock\\git\\msw\\node_modules\\jest-jasmine2\\build\\queueRunner.js:45:12', + ' at new Promise ()', + ' at mapper (C:\\Users\\mock\\git\\msw\\node_modules\\jest-jasmine2\\build\\queueRunner.js:28:19)', + ' at C:\\Users\\mock\\git\\msw\\node_modules\\jest-jasmine2\\build\\queueRunner.js:75:41', + ]) + + expect(getCallFrame(error)).toBe( + 'C:\\Users\\mock\\git\\msw\\test\\msw-api\\setup-server\\listHandlers.test.ts:75:13', + ) +}) + +test('supports Chrome and Edge error stack', () => { + const error = new ErrorWithStack([ + 'Error', + ' at getCallFrame (webpack:///./lib/browser/getCallFrame-deps.js?:272:20)', + ' at Object.eval [as get] (webpack:///./lib/browser/rest-deps.js?:1402:90)', + ' at eval (webpack:///./test/msw-api/setup-worker/listHandlers.mocks.ts?:6:113)', // <-- this one + ' at Module../test/msw-api/setup-worker/listHandlers.mocks.ts (http://localhost:59464/main.js:1376:1)', + ' at __webpack_require__ (http://localhost:59464/main.js:790:30)', + ' at fn (http://localhost:59464/main.js:101:20)', + ' at eval (webpack:///multi_(webpack)-dev-server/client?:4:18)', + ' at Object.0 (http://localhost:59464/main.js:1399:1)', + ' at __webpack_require__ (http://localhost:59464/main.js:790:30)', + ' at http://localhost:59464/main.js:857:37', + ]) + + expect(getCallFrame(error)).toBe( + 'webpack:///./test/msw-api/setup-worker/listHandlers.mocks.ts?:6:113', + ) +}) + +test('supports Firefox (MacOS, Windows) error stack', () => { + const error = new ErrorWithStack([ + 'getCallFrame@webpack:///./lib/browser/getCallFrame-deps.js?:272:20', + 'createRestHandler/<@webpack:///./lib/browser/rest-deps.js?:1402:90', + '@webpack:///./test/msw-api/setup-worker/listHandlers.mocks.ts?:6:113', // <-- this one + './test/msw-api/setup-worker/listHandlers.mocks.ts@http://localhost:59464/main.js:1376:1', + '__webpack_require__@http://localhost:59464/main.js:790:30', + 'fn@http://localhost:59464/main.js:101:20', + '@webpack:///multi_(webpack)-dev-server/client?:4:18', + '0@http://localhost:59464/main.js:1399:1', + '__webpack_require__@http://localhost:59464/main.js:790:30', + '@http://localhost:59464/main.js:857:37', + ]) + + expect(getCallFrame(error)).toBe( + 'webpack:///./test/msw-api/setup-worker/listHandlers.mocks.ts?:6:113', + ) +}) + +test('supports Safari (MacOS) error stack', () => { + const errorOne = new ErrorWithStack([ + 'getCallFrame', + '', + 'eval code', + 'eval@[native code]', + './test/msw-api/setup-worker/listHandlers.mocks.ts@http://localhost:59464/main.js:1376:5', // <-- this one + '__webpack_require__@http://localhost:59464/main.js:790:34', + 'fn@http://localhost:59464/main.js:101:39', + 'eval code', + 'eval@[native code]', + 'http://localhost:59464/main.js:1399:5', + '__webpack_require__@http://localhost:59464/main.js:790:34', + 'http://localhost:59464/main.js:857:37', + 'global code@http://localhost:59464/main.js:858:12', + ]) + + expect(getCallFrame(errorOne)).toBe( + './test/msw-api/setup-worker/listHandlers.mocks.ts@http://localhost:59464/main.js:1376:5', + ) + + const errorTwo = new ErrorWithStack([ + 'getCallFrame', + 'graphQLRequestHandler', + 'eval code', + 'eval@[native code]', + './test/msw-api/setup-worker/listHandlers.mocks.ts@http://localhost:56460/main.js:1376:5', // <-- this one + '__webpack_require__@http://localhost:56460/main.js:790:34', + 'fn@http://localhost:56460/main.js:101:39', + 'eval code', + 'eval@[native code]', + 'http://localhost:56460/main.js:1399:5', + '__webpack_require__@http://localhost:56460/main.js:790:34', + 'http://localhost:56460/main.js:857:37', + 'global code@http://localhost:56460/main.js:858:12', + ]) + + expect(getCallFrame(errorTwo)).toBe( + './test/msw-api/setup-worker/listHandlers.mocks.ts@http://localhost:56460/main.js:1376:5', + ) +}) + +test('handles the undefined stack trace', () => { + expect(() => getCallFrame(new ErrorWithStack(undefined))).not.toThrow( + TypeError, + ) + expect(() => getCallFrame(new ErrorWithStack(null))).not.toThrow(TypeError) +}) diff --git a/node_modules/msw/src/core/utils/internal/getCallFrame.ts b/node_modules/msw/src/core/utils/internal/getCallFrame.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0a372215a0bb47fbb39a295d00ba9a446ff2a84 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/getCallFrame.ts @@ -0,0 +1,35 @@ +// Ignore the source files traces for local testing. +const SOURCE_FRAME = /[/\\]msw[/\\]src[/\\](.+)/ + +const BUILD_FRAME = + /(node_modules)?[/\\]lib[/\\](core|browser|node|native|iife)[/\\]|^[^/\\]*$/ + +/** + * Return the stack trace frame of a function's invocation. + */ +export function getCallFrame(error: Error) { + // In { + return !(SOURCE_FRAME.test(frame) || BUILD_FRAME.test(frame)) + }) + + if (!declarationFrame) { + return + } + + // Extract file reference from the stack frame. + const declarationPath = declarationFrame + .replace(/\s*at [^()]*\(([^)]+)\)/, '$1') + .replace(/^@/, '') + return declarationPath +} diff --git a/node_modules/msw/src/core/utils/internal/hasRefCounted.test.ts b/node_modules/msw/src/core/utils/internal/hasRefCounted.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a6890702a6a31525b703eb96c08caa06600c879 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/hasRefCounted.test.ts @@ -0,0 +1,37 @@ +import { hasRefCounted } from './hasRefCounted' + +it('returns true for objects with ref and unref methods', () => { + expect( + hasRefCounted({ + ref() {}, + unref() {}, + }), + ).toBe(true) +}) + +it('returns false for a non-refcounted object', () => { + expect(hasRefCounted({})).toBe(false) + expect(hasRefCounted({ ref() {} })).toBe(false) + expect(hasRefCounted({ unref() {} })).toBe(false) +}) + +it('returns false for non-object values', () => { + expect( + hasRefCounted( + // @ts-expect-error Runtime value. + null, + ), + ).toBe(false) + expect( + hasRefCounted( + // @ts-expect-error Runtime value. + 123, + ), + ).toBe(false) + expect( + hasRefCounted( + // @ts-expect-error Runtime value. + 'invalid', + ), + ).toBe(false) +}) diff --git a/node_modules/msw/src/core/utils/internal/hasRefCounted.ts b/node_modules/msw/src/core/utils/internal/hasRefCounted.ts new file mode 100644 index 0000000000000000000000000000000000000000..5c61e652260ab529010dc942f989ef5f5a812b42 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/hasRefCounted.ts @@ -0,0 +1,15 @@ +import { isObject } from './isObject' + +export function hasRefCounted( + value: T, +): value is T & NodeJS.RefCounted { + return ( + /** + * @note Guard against non-object values. + * E.g. `setTimeout` returns an object in Node.js but a number in the browser. + */ + isObject(value) && + typeof Reflect.get(value, 'ref') === 'function' && + typeof Reflect.get(value, 'unref') === 'function' + ) +} diff --git a/node_modules/msw/src/core/utils/internal/isHandlerKind.test.ts b/node_modules/msw/src/core/utils/internal/isHandlerKind.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ae78f5f0a828ba98afe6559ffa3b597fac2166a2 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/isHandlerKind.test.ts @@ -0,0 +1,62 @@ +import { GraphQLHandler } from '../../handlers/GraphQLHandler' +import { HttpHandler } from '../../handlers/HttpHandler' +import { RequestHandler } from '../../handlers/RequestHandler' +import { WebSocketHandler } from '../../handlers/WebSocketHandler' +import { isHandlerKind } from './isHandlerKind' + +it('returns true if expected a request handler and given a request handler', () => { + expect(isHandlerKind('request')(new HttpHandler('*', '*', () => {}))).toBe( + true, + ) + + expect( + isHandlerKind('request')(new GraphQLHandler('all', '*', '*', () => {})), + ).toBe(true) +}) + +it('returns true if expected a request handler and given a custom request handler', () => { + class MyHandler extends RequestHandler { + constructor() { + super({ info: { header: '*' }, resolver: () => {} }) + } + predicate = () => false + log() {} + } + + expect(isHandlerKind('request')(new MyHandler())).toBe(true) +}) + +it('returns false if expected a request handler but given event handler', () => { + expect(isHandlerKind('request')(new WebSocketHandler('*'))).toBe(false) +}) + +it('returns false if expected a request handler but given arbitrary object', () => { + expect(isHandlerKind('request')(undefined)).toBe(false) + expect(isHandlerKind('request')(null)).toBe(false) + expect(isHandlerKind('request')({})).toBe(false) + expect(isHandlerKind('request')([])).toBe(false) + expect(isHandlerKind('request')(123)).toBe(false) + expect(isHandlerKind('request')('hello')).toBe(false) +}) + +it('returns true if expected an event handler and given an event handler', () => { + expect(isHandlerKind('websocket')(new WebSocketHandler('*'))).toBe(true) +}) + +it('returns true if expected an event handler and given a custom event handler', () => { + class MyEventHandler extends WebSocketHandler { + constructor() { + super('*') + } + } + expect(isHandlerKind('websocket')(new MyEventHandler())).toBe(true) +}) + +it('returns false if expected an event handler but given arbitrary object', () => { + expect(isHandlerKind('websocket')(undefined)).toBe(false) + expect(isHandlerKind('websocket')(null)).toBe(false) + expect(isHandlerKind('websocket')({})).toBe(false) + expect(isHandlerKind('websocket')([])).toBe(false) + expect(isHandlerKind('websocket')(123)).toBe(false) + expect(isHandlerKind('websocket')('hello')).toBe(false) +}) diff --git a/node_modules/msw/src/core/utils/internal/isHandlerKind.ts b/node_modules/msw/src/core/utils/internal/isHandlerKind.ts new file mode 100644 index 0000000000000000000000000000000000000000..64a9dc6c796967398afc51bceb224211bf541c08 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/isHandlerKind.ts @@ -0,0 +1,17 @@ +import type { AnyHandler } from '../../experimental/handlers-controller' +import type { RequestHandler } from '../../handlers/RequestHandler' +import type { WebSocketHandler } from '../../handlers/WebSocketHandler' +import { isObject } from './isObject' + +/** + * A filter function that ensures that the provided argument + * is a handler of the given kind. This helps differentiate + * between different kinds of handlers, e.g. request and event handlers. + */ +export function isHandlerKind(kind: K) { + return ( + input: unknown, + ): input is K extends 'websocket' ? WebSocketHandler : RequestHandler => { + return isObject(input) && 'kind' in input && input.kind === kind + } +} diff --git a/node_modules/msw/src/core/utils/internal/isIterable.test.ts b/node_modules/msw/src/core/utils/internal/isIterable.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a071f9b76d739b2ab04e888e769efa0e5d8b710 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/isIterable.test.ts @@ -0,0 +1,23 @@ +import { isIterable } from './isIterable' + +test('returns true given an iterator', () => { + expect( + isIterable( + (function* () { + yield 2 + })(), + ), + ).toEqual(true) +}) + +test('returns false given a regular function', () => { + expect( + isIterable( + (function () { + return null + })(), + ), + ).toEqual(false) + + expect(isIterable((() => null)())).toEqual(false) +}) diff --git a/node_modules/msw/src/core/utils/internal/isIterable.ts b/node_modules/msw/src/core/utils/internal/isIterable.ts new file mode 100644 index 0000000000000000000000000000000000000000..670f2b649a87314308ddc03c42c4cd6ffb4e0d77 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/isIterable.ts @@ -0,0 +1,32 @@ +/** + * This is the same as TypeScript's `Iterable`, but with all three type parameters. + * @todo Remove once TypeScript 5.6 is the minimum. + */ +export interface Iterable { + [Symbol.iterator](): Iterator +} + +/** + * This is the same as TypeScript's `AsyncIterable`, but with all three type parameters. + * @todo Remove once TypeScript 5.6 is the minimum. + */ +export interface AsyncIterable { + [Symbol.asyncIterator](): AsyncIterator +} + +/** + * Determines if the given function is an iterator. + */ +export function isIterable( + fn: any, +): fn is + | Iterable + | AsyncIterable { + if (!fn) { + return false + } + + return ( + Reflect.has(fn, Symbol.iterator) || Reflect.has(fn, Symbol.asyncIterator) + ) +} diff --git a/node_modules/msw/src/core/utils/internal/isObject.test.ts b/node_modules/msw/src/core/utils/internal/isObject.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..95f5018ba38a6f9e82574def7938d0f1a281d482 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/isObject.test.ts @@ -0,0 +1,20 @@ +import { isObject } from './isObject' + +test('returns true given an object', () => { + expect(isObject({})).toBe(true) + expect(isObject({ a: 1 })).toBe(true) +}) + +test('returns false given a non-object value', () => { + expect(isObject(1)).toBe(false) + expect(isObject('string')).toBe(false) + expect(isObject([])).toBe(false) + expect( + isObject(function () { + return 2 + }), + ).toBe(false) + expect(isObject(false)).toBe(false) + expect(isObject(undefined)).toBe(false) + expect(isObject(null)).toBe(false) +}) diff --git a/node_modules/msw/src/core/utils/internal/isObject.ts b/node_modules/msw/src/core/utils/internal/isObject.ts new file mode 100644 index 0000000000000000000000000000000000000000..29fa8fbfa58681c198ad362e82ec5cbc931b8f40 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/isObject.ts @@ -0,0 +1,6 @@ +/** + * Determines if the given value is an object. + */ +export function isObject(value: any): value is Record { + return value != null && typeof value === 'object' && !Array.isArray(value) +} diff --git a/node_modules/msw/src/core/utils/internal/isStringEqual.test.ts b/node_modules/msw/src/core/utils/internal/isStringEqual.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..968a80430934190b3d25de1a0cebbecf90a8090b --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/isStringEqual.test.ts @@ -0,0 +1,45 @@ +import { isStringEqual } from './isStringEqual' + +describe('isStringEqual', () => { + describe('given two uppercase strings', () => { + describe('and the strings are equal', () => { + it('should return true', () => { + expect(isStringEqual('GET', 'GET')).toBe(true) + }) + }) + + describe('and the strings are not equal', () => { + it('should return false', () => { + expect(isStringEqual('GET', 'POST')).toBe(false) + }) + }) + }) + + describe('given two lowercase strings', () => { + describe('and the strings are equal', () => { + it('should return true', () => { + expect(isStringEqual('get', 'get')).toBe(true) + }) + }) + + describe('and the strings are not equal', () => { + it('should return false', () => { + expect(isStringEqual('get', 'post')).toBe(false) + }) + }) + }) + + describe('given two strings cased differently', () => { + describe('and the strings are equal', () => { + it('should return true', () => { + expect(isStringEqual('get', 'GET')).toBe(true) + }) + }) + + describe('and the strings are not equal', () => { + it('should return false', () => { + expect(isStringEqual('get', 'POST')).toBe(false) + }) + }) + }) +}) diff --git a/node_modules/msw/src/core/utils/internal/isStringEqual.ts b/node_modules/msw/src/core/utils/internal/isStringEqual.ts new file mode 100644 index 0000000000000000000000000000000000000000..c03220f92e1da0a117e57eeecf6c0e8c88f771de --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/isStringEqual.ts @@ -0,0 +1,6 @@ +/** + * Performs a case-insensitive comparison of two given strings. + */ +export function isStringEqual(actual: string, expected: string): boolean { + return actual.toLowerCase() === expected.toLowerCase() +} diff --git a/node_modules/msw/src/core/utils/internal/jsonParse.test.ts b/node_modules/msw/src/core/utils/internal/jsonParse.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..584cbf2480babd49e3f05c6e7dadfce4d260594d --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/jsonParse.test.ts @@ -0,0 +1,13 @@ +import { jsonParse } from './jsonParse' + +test('parses a given valid JSON string', () => { + expect(jsonParse(`{"property":"value"}`)).toEqual({ + property: 'value', + }) +}) + +test('returns undefined without an error given an invalid JSON string', () => { + const parse = () => jsonParse(`{"property:val"ue$}`) + expect(parse).not.toThrow() + expect(parse()).toBeUndefined() +}) diff --git a/node_modules/msw/src/core/utils/internal/jsonParse.ts b/node_modules/msw/src/core/utils/internal/jsonParse.ts new file mode 100644 index 0000000000000000000000000000000000000000..a494fc93368d4fc59501cadf19298fe0ed521e0f --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/jsonParse.ts @@ -0,0 +1,13 @@ +/** + * Parses a given value into a JSON. + * Does not throw an exception on an invalid JSON string. + */ +export function jsonParse>( + value: any, +): ValueType | undefined { + try { + return JSON.parse(value) + } catch { + return undefined + } +} diff --git a/node_modules/msw/src/core/utils/internal/mergeRight.test.ts b/node_modules/msw/src/core/utils/internal/mergeRight.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d0ceb2e8656539bd01df384790e3692db12de31 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/mergeRight.test.ts @@ -0,0 +1,43 @@ +import { mergeRight } from './mergeRight' + +test('shallowly merges two given objects', () => { + expect(mergeRight({ a: 1, b: 2 }, { b: 3, c: 4 })).toEqual({ + a: 1, + b: 3, + c: 4, + }) +}) + +test('deeply merges two given objects', () => { + expect( + mergeRight( + { + a: 'string', + b: [1, 2], + c: { + d: 2, + }, + }, + { + a: 'another-string', + b: [3], + c: { + e: 'five', + f: { + g: true, + }, + }, + }, + ), + ).toEqual({ + a: 'another-string', + b: [1, 2, 3], + c: { + d: 2, + e: 'five', + f: { + g: true, + }, + }, + }) +}) diff --git a/node_modules/msw/src/core/utils/internal/mergeRight.ts b/node_modules/msw/src/core/utils/internal/mergeRight.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a8b992d622da720165c340c36f56ca3075590b8 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/mergeRight.ts @@ -0,0 +1,30 @@ +import { isObject } from './isObject' + +/** + * Deeply merges two given objects with the right one + * having a priority during property assignment. + */ +export function mergeRight( + left: Record, + right: Record, +) { + return Object.entries(right).reduce( + (result, [key, rightValue]) => { + const leftValue = result[key] + + if (Array.isArray(leftValue) && Array.isArray(rightValue)) { + result[key] = leftValue.concat(rightValue) + return result + } + + if (isObject(leftValue) && isObject(rightValue)) { + result[key] = mergeRight(leftValue, rightValue) + return result + } + + result[key] = rightValue + return result + }, + Object.assign({}, left), + ) +} diff --git a/node_modules/msw/src/core/utils/internal/parseGraphQLRequest.test.ts b/node_modules/msw/src/core/utils/internal/parseGraphQLRequest.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..dac66d2528b0565d983e0e4139b05d6d314e50d2 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/parseGraphQLRequest.test.ts @@ -0,0 +1,97 @@ +/** + * @vitest-environment jsdom + */ +import { encodeBuffer } from '@mswjs/interceptors' +import { OperationTypeNode } from 'graphql' +import type { ParsedGraphQLRequest } from './parseGraphQLRequest' +import { parseGraphQLRequest } from './parseGraphQLRequest' + +test('returns true given a GraphQL-compatible request', async () => { + const getRequest = new Request( + new URL( + 'http://localhost:8080/graphql?query=mutation Login { user { id } }', + ), + ) + expect(await parseGraphQLRequest(getRequest)).toEqual< + ParsedGraphQLRequest + >({ + operationType: OperationTypeNode.MUTATION, + operationName: 'Login', + query: `mutation Login { user { id } }`, + variables: undefined, + }) + + const postRequest = new Request(new URL('http://localhost:8080/graphql'), { + method: 'POST', + headers: new Headers({ 'Content-Type': 'application/json' }), + body: encodeBuffer( + JSON.stringify({ + query: `query GetUser { user { firstName } }`, + }), + ), + }) + + expect(await parseGraphQLRequest(postRequest)).toEqual< + ParsedGraphQLRequest + >({ + operationType: OperationTypeNode.QUERY, + operationName: 'GetUser', + query: `query GetUser { user { firstName } }`, + variables: undefined, + }) +}) + +test('throws an exception given an invalid GraphQL request', async () => { + const getRequest = new Request( + new URL('http://localhost:8080/graphql?query=mutation Login() { user { {}'), + ) + + await expect(parseGraphQLRequest(getRequest)).rejects.toThrowError( + '[MSW] Failed to intercept a GraphQL request to "GET http://localhost:8080/graphql": cannot parse query. See the error message from the parser below.', + ) + + const postRequest = new Request(new URL('http://localhost:8080/graphql'), { + method: 'POST', + headers: new Headers({ 'Content-Type': 'application/json' }), + body: encodeBuffer( + JSON.stringify({ + query: `query GetUser() { user {{}`, + }), + ), + }) + + await expect(parseGraphQLRequest(postRequest)).rejects.toThrowError( + '[MSW] Failed to intercept a GraphQL request to "POST http://localhost:8080/graphql": cannot parse query. See the error message from the parser below.\n\nSyntax Error: Expected "$", found ")".', + ) +}) + +test('returns false given a GraphQL-incompatible request', async () => { + const getRequest = new Request(new URL('http://localhost:8080/graphql'), { + headers: new Headers({ 'Content-Type': 'application/json' }), + }) + expect(await parseGraphQLRequest(getRequest)).toBeUndefined() + + const postRequest = new Request(new URL('http://localhost:8080/graphql'), { + method: 'POST', + headers: new Headers({ 'Content-Type': 'application/json' }), + body: encodeBuffer( + JSON.stringify({ + queryUser: true, + }), + ), + }) + expect(await parseGraphQLRequest(postRequest)).toBeUndefined() +}) + +test('does not read the original request body', async () => { + const request = new Request(new URL('http://localhost/api'), { + method: 'POST', + body: JSON.stringify({ payload: 'value' }), + }) + + await parseGraphQLRequest(request) + + // Must not read the original request body because GraphQL parsing + // is an internal operation that must not lock the body stream. + expect(request.bodyUsed).toBe(false) +}) diff --git a/node_modules/msw/src/core/utils/internal/parseGraphQLRequest.ts b/node_modules/msw/src/core/utils/internal/parseGraphQLRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..5c81409c674e169134edfbc0b54472811aa4de44 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/parseGraphQLRequest.ts @@ -0,0 +1,214 @@ +import type { + DocumentNode, + OperationDefinitionNode, + OperationTypeNode, +} from 'graphql' +import type { GraphQLVariables } from '../../handlers/GraphQLHandler' +import { toPublicUrl } from '../request/toPublicUrl' +import { devUtils } from './devUtils' +import { jsonParse } from './jsonParse' +import { parseMultipartData } from './parseMultipartData' + +interface GraphQLInput { + query: string | null + variables?: GraphQLVariables +} + +export interface ParsedGraphQLQuery { + operationType: OperationTypeNode + operationName?: string +} + +export type ParsedGraphQLRequest< + VariablesType extends GraphQLVariables = GraphQLVariables, +> = + | (ParsedGraphQLQuery & { + query: string + variables?: VariablesType + }) + | undefined + +export function parseDocumentNode(node: DocumentNode): ParsedGraphQLQuery { + const operationDef = node.definitions.find((definition) => { + return definition.kind === 'OperationDefinition' + }) as OperationDefinitionNode + + return { + operationType: operationDef?.operation, + operationName: operationDef?.name?.value, + } +} + +async function parseQuery(query: string): Promise { + /** + * @note Use `require` to get the "graphql" module here. + * It has to be scoped to this function because this module leaks to the + * root export. It has to be `require` because tools like Jest have trouble + * handling dynamic imports. It gets replaced with a dynamic import on build time. + */ + // eslint-disable-next-line @typescript-eslint/no-require-imports + const { parse } = require('graphql') + + try { + const ast = parse(query) + return parseDocumentNode(ast) + } catch (error) { + return error as Error + } +} + +export type GraphQLParsedOperationsMap = Record +export type GraphQLMultipartRequestBody = { + operations: string + map?: string +} & { + [fileName: string]: File +} + +function extractMultipartVariables( + variables: VariablesType, + map: GraphQLParsedOperationsMap, + files: Record, +) { + const operations = { variables } + + for (const [key, pathArray] of Object.entries(map)) { + if (!(key in files)) { + throw new Error(`Given files do not have a key '${key}' .`) + } + + for (const dotPath of pathArray) { + const [lastPath, ...reversedPaths] = dotPath.split('.').reverse() + const paths = reversedPaths.reverse() + let target: Record = operations + + for (const path of paths) { + if (!(path in target)) { + throw new Error(`Property '${path}' is not in operations.`) + } + + target = target[path] + } + + target[lastPath] = files[key] + } + } + + return operations.variables +} + +async function getGraphQLInput(request: Request): Promise { + switch (request.method) { + case 'GET': { + const url = new URL(request.url) + const query = url.searchParams.get('query') + const variables = url.searchParams.get('variables') || '' + + return { + query, + variables: jsonParse(variables), + } + } + + case 'POST': { + // Clone the request so we could read its body without locking + // the body stream to the downward consumers. + const requestClone = request.clone() + + // Handle multipart body GraphQL operations. + if ( + request.headers.get('content-type')?.includes('multipart/form-data') + ) { + const responseJson = parseMultipartData( + await requestClone.text(), + request.headers, + ) + + if (!responseJson) { + return null + } + + const { operations, map, ...files } = responseJson + const parsedOperations = + jsonParse<{ query?: string; variables?: GraphQLVariables }>( + operations, + ) || {} + + if (!parsedOperations.query) { + return null + } + + const parsedMap = jsonParse(map || '') || {} + const variables = parsedOperations.variables + ? extractMultipartVariables( + parsedOperations.variables, + parsedMap, + files, + ) + : {} + + return { + query: parsedOperations.query, + variables, + } + } + + // Handle plain POST GraphQL operations. + const requestJson: { + query: string + variables?: GraphQLVariables + operations?: any /** @todo Annotate this */ + } = await requestClone.json().catch(() => null) + + if (requestJson?.query) { + const { query, variables } = requestJson + + return { + query, + variables, + } + } + return null + } + + default: + return null + } +} + +/** + * Determines if a given request can be considered a GraphQL request. + * Does not parse the query and does not guarantee its validity. + */ +export async function parseGraphQLRequest( + request: Request, +): Promise { + const input = await getGraphQLInput(request) + + if (!input || !input.query) { + return + } + + const { query, variables } = input + const parsedResult = await parseQuery(query) + + if (parsedResult instanceof Error) { + const requestPublicUrl = toPublicUrl(request.url) + + throw new Error( + devUtils.formatMessage( + 'Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s', + request.method, + requestPublicUrl, + parsedResult.message, + ), + ) + } + + return { + query: input.query, + operationType: parsedResult.operationType, + operationName: parsedResult.operationName, + variables, + } +} diff --git a/node_modules/msw/src/core/utils/internal/parseMultipartData.test.ts b/node_modules/msw/src/core/utils/internal/parseMultipartData.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..958133f0a434416f86aedfa468555ac6f359548b --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/parseMultipartData.test.ts @@ -0,0 +1,76 @@ +/** + * @vitest-environment jsdom + */ +import { parseMultipartData } from './parseMultipartData' + +test('parses a given valid multipart string', async () => { + expect.assertions(3) + await testMultipartDataWithContentType( + 'multipart/form-data; boundary=WebKitFormBoundaryvZ1cVXWyK0ilQdab', + ) +}) + +test('parses a given valid multipart string given non-pretty content-type', async () => { + expect.assertions(3) + // node-fetch will serialize content-type in this format, which is valid according to HTTP + // https://github.com/node-fetch/node-fetch/blob/d8fc32d6b29bd43d1ad377e80b3e439fe37f2904/test/main.js#L1438 + await testMultipartDataWithContentType( + 'multipart/form-data;boundary=WebKitFormBoundaryvZ1cVXWyK0ilQdab', + ) +}) + +test('parses a given valid multipart string given content-type with extra spaces', async () => { + expect.assertions(3) + await testMultipartDataWithContentType( + 'multipart/form-data; boundary=WebKitFormBoundaryvZ1cVXWyK0ilQdab', + ) +}) + +async function testMultipartDataWithContentType( + contentType: string, +): Promise { + const body = `\ +------WebKitFormBoundaryvZ1cVXWyK0ilQdab\r +Content-Disposition: form-data; name="file"; filename="file1.txt"\r +Content-Type: application/octet-stream\r +\r +file content\r +------WebKitFormBoundaryvZ1cVXWyK0ilQdab\r +Content-Disposition: form-data; name="text"\r +\r +text content\r +------WebKitFormBoundaryvZ1cVXWyK0ilQdab\r +Content-Disposition: form-data; name="text2"\r +\r +another text content\r +------WebKitFormBoundaryvZ1cVXWyK0ilQdab\r +Content-Disposition: form-data; name="text2"\r +\r +\r +another text content 2\r +\r +------WebKitFormBoundaryvZ1cVXWyK0ilQdab--` + const headers = new Headers({ + 'content-type': contentType, + }) + const parsed = parseMultipartData(body, headers) + + // Workaround: JSDOM does not have `Blob.text` implementation. + // see https://github.com/jsdom/jsdom/issues/2555 + expect(parsed).toHaveProperty('file.name', 'file1.txt') + + expect(parsed).toHaveProperty('text', 'text content') + expect(parsed).toHaveProperty('text2', [ + 'another text content', + '\r\nanother text content 2\r\n', + ]) +} + +test('returns undefined without an error given an invalid multipart string', () => { + const headers = new Headers({ + 'content-type': 'multipart/form-data; boundary=dummyBoundary', + }) + const parse = () => parseMultipartData(`{"invalid": ["multipart"]}`, headers) + expect(parse).not.toThrow() + expect(parse()).toBeUndefined() +}) diff --git a/node_modules/msw/src/core/utils/internal/parseMultipartData.ts b/node_modules/msw/src/core/utils/internal/parseMultipartData.ts new file mode 100644 index 0000000000000000000000000000000000000000..d38d6d342bbe6b4b14f3d5dd74298b1c4a05e61f --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/parseMultipartData.ts @@ -0,0 +1,106 @@ +import { stringToHeaders } from 'headers-polyfill' +import { type DefaultRequestMultipartBody } from '../../handlers/RequestHandler' + +interface ParsedContentHeaders { + name: string + filename?: string + contentType: string +} + +interface ContentDispositionDirective { + [key: string]: string | undefined + name: string + filename?: string + 'form-data': string +} + +function parseContentHeaders(headersString: string): ParsedContentHeaders { + const headers = stringToHeaders(headersString) + const contentType = headers.get('content-type') || 'text/plain' + const disposition = headers.get('content-disposition') + + if (!disposition) { + throw new Error('"Content-Disposition" header is required.') + } + + const directives = disposition.split(';').reduce((acc, chunk) => { + const [name, ...rest] = chunk.trim().split('=') + acc[name] = rest.join('=') + return acc + }, {} as ContentDispositionDirective) + + const name = directives.name?.slice(1, -1) + const filename = directives.filename?.slice(1, -1) + + return { + name, + filename, + contentType, + } +} + +/** + * Parses a given string as a multipart/form-data. + * Does not throw an exception on an invalid multipart string. + */ +export function parseMultipartData( + data: string, + headers?: Headers, +): T | undefined { + const contentType = headers?.get('content-type') + + if (!contentType) { + return undefined + } + + const [, ...directives] = contentType.split(/; */) + const boundary = directives + .filter((d) => d.startsWith('boundary=')) + .map((s) => s.replace(/^boundary=/, ''))[0] + + if (!boundary) { + return undefined + } + + const boundaryRegExp = new RegExp( + `--+${boundary.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`, + ) + const fields = data + .split(boundaryRegExp) + .filter((chunk) => chunk.startsWith('\r\n') && chunk.endsWith('\r\n')) + .map((chunk) => chunk.trimStart().replace(/\r\n$/, '')) + + if (!fields.length) { + return undefined + } + + const parsedBody: DefaultRequestMultipartBody = {} + + try { + for (const field of fields) { + const [contentHeaders, ...rest] = field.split('\r\n\r\n') + const contentBody = rest.join('\r\n\r\n') + const { contentType, filename, name } = + parseContentHeaders(contentHeaders) + + const value = + filename === undefined + ? contentBody + : new File([contentBody], filename, { type: contentType }) + + const parsedValue = parsedBody[name] + + if (parsedValue === undefined) { + parsedBody[name] = value + } else if (Array.isArray(parsedValue)) { + parsedBody[name] = [...parsedValue, value] + } else { + parsedBody[name] = [parsedValue, value] + } + } + + return parsedBody as T + } catch { + return undefined + } +} diff --git a/node_modules/msw/src/core/utils/internal/pipeEvents.test.ts b/node_modules/msw/src/core/utils/internal/pipeEvents.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..77dff7f4fb14a5d3f353560bc2e695d79c7c107c --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/pipeEvents.test.ts @@ -0,0 +1,14 @@ +import { Emitter } from 'strict-event-emitter' +import { pipeEvents } from './pipeEvents' + +it('pipes events from the source emitter to the destination emitter', () => { + const source = new Emitter() + const destination = new Emitter() + pipeEvents(source, destination) + + const callback = vi.fn() + destination.on('hello', callback) + + source.emit('hello', 'world', { data: true }) + expect(callback).toHaveBeenNthCalledWith(1, 'world', { data: true }) +}) diff --git a/node_modules/msw/src/core/utils/internal/pipeEvents.ts b/node_modules/msw/src/core/utils/internal/pipeEvents.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ccede71309eb2f21668e8ead9c2f4c0652b9509 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/pipeEvents.ts @@ -0,0 +1,26 @@ +import type { Emitter } from 'strict-event-emitter' +import { type EventMap } from 'strict-event-emitter' + +/** + * Pipes all emitted events from one emitter to another. + */ +export function pipeEvents( + source: Emitter, + destination: Emitter, +): void { + const rawEmit: typeof source.emit & { _isPiped?: boolean } = source.emit + + if (rawEmit._isPiped) { + return + } + + const sourceEmit: typeof source.emit & { _isPiped?: boolean } = + function sourceEmit(this: typeof source, event, ...data) { + destination.emit(event, ...data) + return rawEmit.call(this, event, ...data) + } + + sourceEmit._isPiped = true + + source.emit = sourceEmit +} diff --git a/node_modules/msw/src/core/utils/internal/toReadonlyArray.test.ts b/node_modules/msw/src/core/utils/internal/toReadonlyArray.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1314aebb44685002e768d994636625b101718bfc --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/toReadonlyArray.test.ts @@ -0,0 +1,30 @@ +import { toReadonlyArray } from './toReadonlyArray' + +it('creates a copy of an array', () => { + expect(toReadonlyArray([1, 2, 3])).toEqual([1, 2, 3]) +}) + +it('does not affect the source array', () => { + const source = ['a', 'b', 'c'] + toReadonlyArray(source) + + expect(source.push('d')).toBe(4) + expect(source).toEqual(['a', 'b', 'c', 'd']) +}) + +it('forbids modifying the array copy', () => { + const source = [1, 2, 3] + const copy = toReadonlyArray(source) + + expect(() => { + // @ts-expect-error Intentional runtime misusage. + copy[2] = 1 + }).toThrow(/Cannot assign to read only property '\d+' of object/) + + expect(() => { + // @ts-expect-error Intentional runtime misusage. + copy.push(4) + }).toThrow(/Cannot add property \d+, object is not extensible/) + + expect(source).toEqual([1, 2, 3]) +}) diff --git a/node_modules/msw/src/core/utils/internal/toReadonlyArray.ts b/node_modules/msw/src/core/utils/internal/toReadonlyArray.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3d99cd9b6495d324f1d005bdeb5cda0cc060dbe --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/toReadonlyArray.ts @@ -0,0 +1,8 @@ +/** + * Creates an immutable copy of the given array. + */ +export function toReadonlyArray(source: Array): ReadonlyArray { + const clone = [...source] as Array + Object.freeze(clone) + return clone +} diff --git a/node_modules/msw/src/core/utils/internal/tryCatch.test.ts b/node_modules/msw/src/core/utils/internal/tryCatch.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b48896d10892a2cc1e41691a3bc6365ee65f5aa3 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/tryCatch.test.ts @@ -0,0 +1,29 @@ +import { tryCatch } from './tryCatch' + +test('returns the function payload', () => { + const result = tryCatch(() => 'hello') + expect(result).toEqual('hello') +}) + +test('silences exceptions by default', () => { + const result = tryCatch(() => { + throw new Error('Exception') + }) + + expect(result).toBeUndefined() +}) + +test('executes a custom callback function when an exception occurs', async () => { + await new Promise((resolve) => { + tryCatch( + () => { + throw new Error('Exception') + }, + (error) => { + expect(error).toBeInstanceOf(Error) + expect(error.message).toEqual('Exception') + resolve() + }, + ) + }) +}) diff --git a/node_modules/msw/src/core/utils/internal/tryCatch.ts b/node_modules/msw/src/core/utils/internal/tryCatch.ts new file mode 100644 index 0000000000000000000000000000000000000000..bcfdde135fbea55ceccd6a65de0f3cb5e7613d31 --- /dev/null +++ b/node_modules/msw/src/core/utils/internal/tryCatch.ts @@ -0,0 +1,11 @@ +export function tryCatch any>( + fn: Fn, + onException?: (error: Error) => void, +): ReturnType | undefined { + try { + const result = fn() + return result + } catch (error) { + onException?.(error as Error) + } +} diff --git a/node_modules/msw/src/core/utils/logging/getStatusCodeColor.test.ts b/node_modules/msw/src/core/utils/logging/getStatusCodeColor.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9050d7988e4c7193e57ae330fccc548292f1d75 --- /dev/null +++ b/node_modules/msw/src/core/utils/logging/getStatusCodeColor.test.ts @@ -0,0 +1,22 @@ +import { getStatusCodeColor } from './getStatusCodeColor' + +test('returns a green color for status codes lower than 300', () => { + expect(getStatusCodeColor(100)).toBe('#69AB32') + expect(getStatusCodeColor(200)).toBe('#69AB32') + expect(getStatusCodeColor(204)).toBe('#69AB32') +}) + +test('returns a yellow color for status codes between 201 and 400', () => { + expect(getStatusCodeColor(300)).toBe('#F0BB4B') + expect(getStatusCodeColor(304)).toBe('#F0BB4B') +}) + +test('returns a red color for status codes higher than 400', () => { + expect(getStatusCodeColor(400)).toBe('#E95F5D') + expect(getStatusCodeColor(404)).toBe('#E95F5D') + expect(getStatusCodeColor(500)).toBe('#E95F5D') +}) + +test('returns a red color for unknown status code', () => { + expect(getStatusCodeColor(700)).toBe('#E95F5D') +}) diff --git a/node_modules/msw/src/core/utils/logging/getStatusCodeColor.ts b/node_modules/msw/src/core/utils/logging/getStatusCodeColor.ts new file mode 100644 index 0000000000000000000000000000000000000000..39a45e864d8e6126385b6871b269c9e85ae9c3a0 --- /dev/null +++ b/node_modules/msw/src/core/utils/logging/getStatusCodeColor.ts @@ -0,0 +1,20 @@ +export enum StatusCodeColor { + Success = '#69AB32', + Warning = '#F0BB4B', + Danger = '#E95F5D', +} + +/** + * Returns a HEX color for a given response status code number. + */ +export function getStatusCodeColor(status: number): StatusCodeColor { + if (status < 300) { + return StatusCodeColor.Success + } + + if (status < 400) { + return StatusCodeColor.Warning + } + + return StatusCodeColor.Danger +} diff --git a/node_modules/msw/src/core/utils/logging/getTimestamp.test.ts b/node_modules/msw/src/core/utils/logging/getTimestamp.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..04b488686e7b5eccb6c7b18c09de7dc41be39678 --- /dev/null +++ b/node_modules/msw/src/core/utils/logging/getTimestamp.test.ts @@ -0,0 +1,32 @@ +import { getTimestamp } from './getTimestamp' + +beforeAll(() => { + vi.useFakeTimers() +}) + +afterAll(() => { + vi.useRealTimers() +}) + +test('returns a timestamp string of the invocation time', () => { + vi.setSystemTime(new Date('2024-01-01 12:4:8')) + const timestamp = getTimestamp() + expect(timestamp).toBe('12:04:08') +}) + +test('returns a timestamp with milliseconds', () => { + vi.setSystemTime(new Date('2024-01-01 12:4:8')) + expect(getTimestamp({ milliseconds: true })).toBe('12:04:08.000') + + vi.setSystemTime(new Date('2024-01-01 12:4:8.000')) + expect(getTimestamp({ milliseconds: true })).toBe('12:04:08.000') + + vi.setSystemTime(new Date('2024-01-01 12:4:8.4')) + expect(getTimestamp({ milliseconds: true })).toBe('12:04:08.400') + + vi.setSystemTime(new Date('2024-01-01 12:4:8.123')) + expect(getTimestamp({ milliseconds: true })).toBe('12:04:08.123') + + vi.setSystemTime(new Date('2024-01-01 12:00:00')) + expect(getTimestamp({ milliseconds: true })).toBe('12:00:00.000') +}) diff --git a/node_modules/msw/src/core/utils/logging/getTimestamp.ts b/node_modules/msw/src/core/utils/logging/getTimestamp.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5360535518fa5dc56a6f92198c07ee1ea9798e9 --- /dev/null +++ b/node_modules/msw/src/core/utils/logging/getTimestamp.ts @@ -0,0 +1,17 @@ +interface GetTimestampOptions { + milliseconds?: boolean +} + +/** + * Returns a timestamp string in a "HH:MM:SS" format. + */ +export function getTimestamp(options?: GetTimestampOptions): string { + const now = new Date() + const timestamp = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}` + + if (options?.milliseconds) { + return `${timestamp}.${now.getMilliseconds().toString().padStart(3, '0')}` + } + + return timestamp +} diff --git a/node_modules/msw/src/core/utils/logging/serializeRequest.test.ts b/node_modules/msw/src/core/utils/logging/serializeRequest.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..aac41d891b24e7765bef591eaf6bfa3e3dd114e7 --- /dev/null +++ b/node_modules/msw/src/core/utils/logging/serializeRequest.test.ts @@ -0,0 +1,23 @@ +import { encodeBuffer } from '@mswjs/interceptors' +import { serializeRequest } from './serializeRequest' + +test('serializes given Request instance into a plain object', async () => { + const request = await serializeRequest( + new Request(new URL('http://test.mswjs.io/user'), { + method: 'POST', + headers: new Headers({ + 'Content-Type': 'text/plain', + 'X-Header': 'secret', + }), + body: encodeBuffer('text-body'), + }), + ) + + expect(request.method).toBe('POST') + expect(request.url.href).toBe('http://test.mswjs.io/user') + expect(request.headers).toEqual({ + 'content-type': 'text/plain', + 'x-header': 'secret', + }) + expect(request.body).toBe('text-body') +}) diff --git a/node_modules/msw/src/core/utils/logging/serializeRequest.ts b/node_modules/msw/src/core/utils/logging/serializeRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2c2afd01e0a6ed14eb896aaf3d8a609ae0cf26b --- /dev/null +++ b/node_modules/msw/src/core/utils/logging/serializeRequest.ts @@ -0,0 +1,23 @@ +export interface LoggedRequest { + url: URL + method: string + headers: Record + body: string +} + +/** + * Formats a mocked request for introspection in browser's console. + */ +export async function serializeRequest( + request: Request, +): Promise { + const requestClone = request.clone() + const requestText = await requestClone.text() + + return { + url: new URL(request.url), + method: request.method, + headers: Object.fromEntries(request.headers.entries()), + body: requestText, + } +} diff --git a/node_modules/msw/src/core/utils/logging/serializeResponse.test.ts b/node_modules/msw/src/core/utils/logging/serializeResponse.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c1e22e2806db11340eb7ba589b27d2f341cdc188 --- /dev/null +++ b/node_modules/msw/src/core/utils/logging/serializeResponse.test.ts @@ -0,0 +1,77 @@ +/** + * @vitest-environment node + */ +import { encodeBuffer } from '@mswjs/interceptors' +import { serializeResponse } from './serializeResponse' + +it('serializes response without body', async () => { + const result = await serializeResponse(new Response(null)) + + expect(result.status).toBe(200) + expect(result.statusText).toBe('OK') + expect(result.headers).toEqual({}) + expect(result.body).toBe('') +}) + +it('serializes a plain text response', async () => { + const result = await serializeResponse( + new Response('hello world', { + status: 201, + statusText: 'Created', + headers: { + 'Content-Type': 'text/plain', + }, + }), + ) + + expect(result.status).toBe(201) + expect(result.statusText).toBe('Created') + expect(result.headers).toEqual({ + 'content-type': 'text/plain', + }) + expect(result.body).toBe('hello world') +}) + +it('serializes a JSON response', async () => { + const response = new Response(JSON.stringify({ users: ['John'] }), { + headers: { + 'Content-Type': 'application/json', + }, + }) + const result = await serializeResponse(response) + + expect(result.headers).toEqual({ + 'content-type': 'application/json', + }) + expect(result.body).toBe(JSON.stringify({ users: ['John'] })) +}) + +it('serializes a ArrayBuffer response', async () => { + const data = encodeBuffer('hello world') + const response = new Response(data) + const result = await serializeResponse(response) + + expect(result.body).toBe('hello world') +}) + +it('serializes a Blob response', async () => { + const response = new Response(new Blob(['hello world'])) + const result = await serializeResponse(response) + + expect(result.body).toBe('hello world') +}) + +it('serializes a FormData response', async () => { + const data = new FormData() + data.set('firstName', 'Alice') + data.set('age', '32') + const response = new Response(data) + const result = await serializeResponse(response) + + expect(result.body).toContain( + `Content-Disposition: form-data; name="firstName"\r\n\r\nAlice`, + ) + expect(result.body).toContain( + `Content-Disposition: form-data; name="age"\r\n\r\n32`, + ) +}) diff --git a/node_modules/msw/src/core/utils/logging/serializeResponse.ts b/node_modules/msw/src/core/utils/logging/serializeResponse.ts new file mode 100644 index 0000000000000000000000000000000000000000..52417e0098224e690762961303f072afb67d4882 --- /dev/null +++ b/node_modules/msw/src/core/utils/logging/serializeResponse.ts @@ -0,0 +1,31 @@ +import statuses from '../../../shims/statuses' + +const { message } = statuses + +export interface SerializedResponse { + status: number + statusText: string + headers: Record + body: string +} + +export async function serializeResponse( + response: Response, +): Promise { + const responseClone = response.clone() + const responseText = await responseClone.text() + + // Normalize the response status and status text when logging + // since the default Response instance doesn't infer status texts + // from status codes. This has no effect on the actual response instance. + const responseStatus = responseClone.status || 200 + const responseStatusText = + responseClone.statusText || message[responseStatus] || 'OK' + + return { + status: responseStatus, + statusText: responseStatusText, + headers: Object.fromEntries(responseClone.headers.entries()), + body: responseText, + } +} diff --git a/node_modules/msw/src/core/utils/matching/matchRequestUrl.test.ts b/node_modules/msw/src/core/utils/matching/matchRequestUrl.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e2ca5824243c34310c25b3bece5fbd6699e582aa --- /dev/null +++ b/node_modules/msw/src/core/utils/matching/matchRequestUrl.test.ts @@ -0,0 +1,267 @@ +// @vitest-environment jsdom +import { coercePath, matchRequestUrl } from './matchRequestUrl' + +describe('matchRequestUrl', () => { + test('returns true when matches against an exact URL', () => { + expect( + matchRequestUrl( + new URL('https://test.mswjs.io'), + 'https://test.mswjs.io', + ), + ).toEqual({ + matches: true, + params: {}, + }) + }) + + test('returns true when matched against a wildcard', () => { + expect(matchRequestUrl(new URL('https://test.mswjs.io'), '*')).toEqual({ + matches: true, + params: { + '0': 'https://test.mswjs.io/', + }, + }) + }) + + test('returns true when matched against a RegExp', () => { + expect( + matchRequestUrl(new URL('https://test.mswjs.io'), /test\.mswjs\.io/), + ).toEqual({ + matches: true, + params: {}, + }) + }) + + test('returns path parameters when matched', () => { + expect( + matchRequestUrl( + new URL('https://test.mswjs.io/user/abc-123'), + 'https://test.mswjs.io/user/:userId', + ), + ).toEqual({ + matches: true, + params: { + userId: 'abc-123', + }, + }) + }) + + test('decodes path parameters', () => { + const url = 'http://example.com:5001/example' + + expect( + matchRequestUrl( + new URL(`https://test.mswjs.io/reflect-url/${encodeURIComponent(url)}`), + 'https://test.mswjs.io/reflect-url/:url', + ), + ).toEqual({ + matches: true, + params: { + url, + }, + }) + }) + + test('returns false when does not match against the request URL', () => { + expect( + matchRequestUrl(new URL('https://test.mswjs.io'), 'https://google.com'), + ).toEqual({ + matches: false, + params: {}, + }) + }) + + test('returns true when matching optional path parameters', () => { + expect( + matchRequestUrl( + new URL('https://test.mswjs.io/user/123'), + 'https://test.mswjs.io/user/:userId?', + ), + ).toEqual({ + matches: true, + params: { + userId: '123', + }, + }) + }) + + test('returns true when matching URLs with wildcard ports', () => { + expect + .soft( + matchRequestUrl(new URL('http://localhost:3000'), 'http://localhost:*'), + ) + .toEqual({ + matches: true, + params: { + '0': '3000/', + }, + }) + + expect + .soft( + matchRequestUrl( + new URL('http://localhost:3000'), + 'http://localhost:*/', + ), + ) + .toEqual({ + matches: true, + params: { + '0': '3000', + }, + }) + }) + + test('returns true when matching URLs with wildcard ports and pathnames', () => { + expect( + matchRequestUrl( + new URL('http://localhost:3000/resource'), + 'http://localhost:*/resource', + ), + ).toEqual({ + matches: true, + params: { + '0': '3000', + }, + }) + }) + + test('matches wildcard ports with other wildcard parameters', () => { + expect( + matchRequestUrl( + new URL('http://subdomain.localhost:3000/user/settings'), + 'http://*.localhost:*/user/*', + ), + ).toEqual({ + matches: true, + params: { + '0': 'subdomain', + '1': '3000', + '2': 'settings', + }, + }) + }) + + test('matches wildcard ports that also match a part of the pathname', () => { + expect( + matchRequestUrl( + new URL('http://localhost:3000/user/settings'), + 'http://localhost:*/settings', + ), + ).toEqual({ + matches: true, + params: { + '0': '3000/user', + }, + }) + }) + + test('returns true for matching WebSocket URL', () => { + expect( + matchRequestUrl(new URL('ws://test.mswjs.io'), 'ws://test.mswjs.io'), + ).toEqual({ + matches: true, + params: {}, + }) + expect( + matchRequestUrl(new URL('wss://test.mswjs.io'), 'wss://test.mswjs.io'), + ).toEqual({ + matches: true, + params: {}, + }) + }) + + test('returns false for non-matching WebSocket URL', () => { + expect( + matchRequestUrl(new URL('ws://test.mswjs.io'), 'ws://foo.mswjs.io'), + ).toEqual({ + matches: false, + params: {}, + }) + expect( + matchRequestUrl(new URL('wss://test.mswjs.io'), 'wss://completely.diff'), + ).toEqual({ + matches: false, + params: {}, + }) + }) + + test('returns path parameters when matched a WebSocket URL', () => { + expect( + matchRequestUrl( + new URL('wss://test.mswjs.io'), + 'wss://:service.mswjs.io', + ), + ).toEqual({ + matches: true, + params: { + service: 'test', + }, + }) + }) + + test('returns true for matching WebSocket URLs with wildcard ports', () => { + expect( + matchRequestUrl(new URL('ws://localhost:3000'), 'ws://localhost:*'), + ).toEqual({ + matches: true, + params: { + '0': '3000/', + }, + }) + }) +}) + +describe('coercePath', () => { + test('escapes the colon in protocol', () => { + expect(coercePath('https://example.com')).toEqual('https\\://example.com') + expect(coercePath('https://example.com/:userId')).toEqual( + 'https\\://example.com/:userId', + ) + expect(coercePath('http://localhost:3000')).toEqual( + 'http\\://localhost\\:3000', + ) + }) + + test('escapes the colon before the port number', () => { + expect(coercePath('localhost:8080')).toEqual('localhost\\:8080') + expect(coercePath('http://127.0.0.1:8080')).toEqual( + 'http\\://127.0.0.1\\:8080', + ) + expect(coercePath('https://example.com:1234')).toEqual( + 'https\\://example.com\\:1234', + ) + + expect(coercePath('localhost:8080/:5678')).toEqual('localhost\\:8080/:5678') + expect(coercePath('https://example.com:8080/:5678')).toEqual( + 'https\\://example.com\\:8080/:5678', + ) + expect(coercePath('http://localhost:*')).toEqual( + 'http\\://localhost\\:(.*)', + ) + expect(coercePath('ws://localhost:*')).toEqual('ws\\://localhost\\:(.*)') + }) + + test('replaces wildcard with an unnnamed capturing group', () => { + expect(coercePath('*')).toEqual('(.*)') + expect(coercePath('**')).toEqual('(.*)') + expect(coercePath('/us*')).toEqual('/us(.*)') + expect(coercePath('/user/*')).toEqual('/user/(.*)') + expect(coercePath('https://example.com/user/*')).toEqual( + 'https\\://example.com/user/(.*)', + ) + expect(coercePath('https://example.com/us*')).toEqual( + 'https\\://example.com/us(.*)', + ) + }) + + test('preserves path parameter modifiers', () => { + expect(coercePath(':name*')).toEqual(':name*') + expect(coercePath('/foo/:name*')).toEqual('/foo/:name*') + expect(coercePath('/foo/**:name*')).toEqual('/foo/(.*):name*') + expect(coercePath('**/foo/*/:name*')).toEqual('(.*)/foo/(.*)/:name*') + expect(coercePath('/foo/:first/bar/:second*/*')).toEqual( + '/foo/:first/bar/:second*/(.*)', + ) + }) +}) diff --git a/node_modules/msw/src/core/utils/matching/matchRequestUrl.ts b/node_modules/msw/src/core/utils/matching/matchRequestUrl.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5d2e18b82f741e16fd2bf4507ce464d4b8e0bd9 --- /dev/null +++ b/node_modules/msw/src/core/utils/matching/matchRequestUrl.ts @@ -0,0 +1,77 @@ +import { match } from 'path-to-regexp' +import { getCleanUrl } from '@mswjs/interceptors' +import { normalizePath } from './normalizePath' + +export type Path = string | RegExp +export type PathParams = { + [ParamName in KeyType]?: string | ReadonlyArray +} + +export interface Match { + matches: boolean + params?: PathParams +} + +/** + * Coerce a path supported by MSW into a path + * supported by "path-to-regexp". + */ +export function coercePath(path: string): string { + return ( + path + /** + * Replace wildcards ("*") with unnamed capturing groups + * because "path-to-regexp" doesn't support wildcards. + * Ignore path parameter' modifiers (i.e. ":name*"). + */ + .replace( + /([:a-zA-Z_-]*)(\*{1,2})+/g, + (_, parameterName: string | undefined, wildcard: string) => { + const expression = '(.*)' + + if (!parameterName) { + return expression + } + + return parameterName.startsWith(':') + ? `${parameterName}${wildcard}` + : `${parameterName}${expression}` + }, + ) + /** + * Escape the port so that "path-to-regexp" can match + * absolute URLs with numeric or wildcard ports. + */ + .replace(/([^/])(:)(?=(?:\d+|\(\.\*\))(?=\/|$))/, '$1\\$2') + /** + * Escape the protocol so that "path-to-regexp" could match + * absolute URL. + * @see https://github.com/pillarjs/path-to-regexp/issues/259 + */ + .replace(/^([^/]+)(:)(?=\/\/)/, '$1\\$2') + ) +} + +/** + * Returns the result of matching given request URL against a mask. + */ +export function matchRequestUrl(url: URL, path: Path, baseUrl?: string): Match { + const normalizedPath = normalizePath(path, baseUrl) + const cleanPath = + typeof normalizedPath === 'string' + ? coercePath(normalizedPath) + : normalizedPath + + const cleanUrl = getCleanUrl(url) + const result = match(cleanPath, { decode: decodeURIComponent })(cleanUrl) + const params = (result && (result.params as PathParams)) || {} + + return { + matches: result !== false, + params, + } +} + +export function isPath(value: unknown): value is Path { + return typeof value === 'string' || value instanceof RegExp +} diff --git a/node_modules/msw/src/core/utils/matching/normalizePath.node.test.ts b/node_modules/msw/src/core/utils/matching/normalizePath.node.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..61b3871e6c8f23dde22c8c19325c01d8186f3b6d --- /dev/null +++ b/node_modules/msw/src/core/utils/matching/normalizePath.node.test.ts @@ -0,0 +1,44 @@ +/** + * @vitest-environment node + */ +import { normalizePath } from './normalizePath' + +test('returns RegExp as-is', () => { + const path = /s/ + expect(normalizePath(path)).toEqual(path) +}) + +test('returns a clean absolute URL as-is', () => { + const path = 'https://test.mswjs.io/path' + expect(normalizePath(path)).toEqual(path) +}) + +test('returns a relative URL as-is given a string path', () => { + const path = '/relative/url' + expect(normalizePath(path)).toEqual(path) +}) + +test('rebases a relative URL against a custom base URL', () => { + const path = '/relative/url' + expect(normalizePath(path, 'https://test.mswjs.io')).toEqual( + 'https://test.mswjs.io/relative/url', + ) +}) + +test('removes query parameters and hashes from an absolute URL', () => { + expect(normalizePath('https://test.mswjs.io/user?query=123')).toEqual( + 'https://test.mswjs.io/user', + ) + expect(normalizePath('https://test.mswjs.io/user#some')).toEqual( + 'https://test.mswjs.io/user', + ) + expect(normalizePath('https://test.mswjs.io/user?query=123#some')).toEqual( + 'https://test.mswjs.io/user', + ) +}) + +test('removes query parameters and hashes from a relative URL', () => { + expect(normalizePath('/user?query=123')).toEqual('/user') + expect(normalizePath('/user#some')).toEqual('/user') + expect(normalizePath('/user?query=123#some')).toEqual('/user') +}) diff --git a/node_modules/msw/src/core/utils/matching/normalizePath.test.ts b/node_modules/msw/src/core/utils/matching/normalizePath.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..06702f584d684d2a76d4a536fd8f2b9ac7481c94 --- /dev/null +++ b/node_modules/msw/src/core/utils/matching/normalizePath.test.ts @@ -0,0 +1,56 @@ +/** + * @vitest-environment jsdom + */ +import { normalizePath } from './normalizePath' + +test('returns RegExp as-is', () => { + const path = /\/user\/(.+?)\// + expect(normalizePath(path)).toEqual(path) +}) + +test('returns a clean absolute URL as-is', () => { + const path = 'https://test.mswjs.io/user' + expect(normalizePath(path)).toEqual(path) +}) + +test('rebases a relative URL against the current location', () => { + const path = '/relative/url' + expect(normalizePath(path)).toBe(`${location.origin}/relative/url`) +}) + +test('rebases a relative URL against a custom base URL', () => { + const path = '/relative/url' + expect(normalizePath(path, 'https://test.mswjs.io')).toEqual( + 'https://test.mswjs.io/relative/url', + ) +}) + +test('removes query parameters and hashes from an absolute URL', () => { + const path = 'https://test.mswjs.io/user?query=123#some' + expect(normalizePath(path)).toEqual('https://test.mswjs.io/user') +}) + +test('removes query parameters and hashes from a relative URL', () => { + expect(normalizePath('/user?query=123')).toEqual(`${location.origin}/user`) + expect(normalizePath('/user#some')).toEqual(`${location.origin}/user`) + expect(normalizePath('/user?query=123#some')).toEqual( + `${location.origin}/user`, + ) +}) + +test('returns a path pattern string as-is', () => { + expect(normalizePath(':api/user')).toEqual('http://localhost/:api/user') + expect(normalizePath('*/resource/*')).toEqual('*/resource/*') +}) + +test('removes query parameters and hashes from a path pattern string', () => { + expect(normalizePath(':api/user?query=123#some')).toEqual( + 'http://localhost/:api/user', + ) +}) + +test('preserves optional path parameters', () => { + expect(normalizePath('/user/:userId?')).toEqual( + 'http://localhost/user/:userId?', + ) +}) diff --git a/node_modules/msw/src/core/utils/matching/normalizePath.ts b/node_modules/msw/src/core/utils/matching/normalizePath.ts new file mode 100644 index 0000000000000000000000000000000000000000..bb8a237c09c32038902e922947d9e19f012370a7 --- /dev/null +++ b/node_modules/msw/src/core/utils/matching/normalizePath.ts @@ -0,0 +1,22 @@ +import type { Path } from './matchRequestUrl' +import { cleanUrl } from '../url/cleanUrl' +import { getAbsoluteUrl } from '../url/getAbsoluteUrl' + +/** + * Normalizes a given request handler path: + * - Preserves RegExp. + * - Removes query parameters and hashes. + * - Rebases relative URLs against the "baseUrl" or the current location. + * - Preserves relative URLs in Node.js, unless specified otherwise. + * - Preserves optional path parameters. + */ +export function normalizePath(path: Path, baseUrl?: string): Path { + // RegExp paths do not need normalization. + if (path instanceof RegExp) { + return path + } + + const maybeAbsoluteUrl = getAbsoluteUrl(path, baseUrl) + + return cleanUrl(maybeAbsoluteUrl) +} diff --git a/node_modules/msw/src/core/utils/request/getAllAcceptedMimeTypes.test.ts b/node_modules/msw/src/core/utils/request/getAllAcceptedMimeTypes.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4645df93e79226e545264d3aaa739cc5460ba507 --- /dev/null +++ b/node_modules/msw/src/core/utils/request/getAllAcceptedMimeTypes.test.ts @@ -0,0 +1,86 @@ +import { getAllAcceptedMimeTypes } from './getAllAcceptedMimeTypes' + +it('returns an empty array for null accept header', () => { + expect(getAllAcceptedMimeTypes(null)).toEqual([]) +}) + +it('returns a single mime type as-is', () => { + expect(getAllAcceptedMimeTypes('application/json')).toEqual([ + 'application/json', + ]) +}) + +it('returns multiple mime types in order', () => { + expect(getAllAcceptedMimeTypes('text/html, application/json')).toEqual([ + 'text/html', + 'application/json', + ]) +}) + +it('sorts by quality value (q parameter)', () => { + expect( + getAllAcceptedMimeTypes('text/plain;q=0.5, application/json;q=0.9'), + ).toEqual(['application/json', 'text/plain']) +}) + +it('excludes types with q=0', () => { + expect(getAllAcceptedMimeTypes('text/html, text/plain;q=0')).toEqual([ + 'text/html', + ]) +}) + +it('returns an empty array when all types have q=0', () => { + expect(getAllAcceptedMimeTypes('text/html;q=0, text/plain;q=0')).toEqual([]) +}) + +it('treats missing q as q=1 (default)', () => { + expect(getAllAcceptedMimeTypes('text/plain;q=0.5, application/json')).toEqual( + ['application/json', 'text/plain'], + ) +}) + +it('sorts by specificity when quality is equal (type/subtype > type/* > */*)', () => { + expect(getAllAcceptedMimeTypes('*/*, text/*, text/html')).toEqual([ + 'text/html', + 'text/*', + '*/*', + ]) +}) + +it('sorts by parameter count when quality and specificity are equal', () => { + expect( + getAllAcceptedMimeTypes( + 'text/plain;format=fixed;charset=utf-8, text/plain;charset=utf-8', + ), + ).toEqual(['text/plain', 'text/plain']) +}) + +it('applies full precedence: quality > specificity > parameter count', () => { + expect( + getAllAcceptedMimeTypes( + 'text/*;q=0.8, application/json, text/html;q=0.8, */*;q=0.1', + ), + ).toEqual(['application/json', 'text/html', 'text/*', '*/*']) +}) + +it('handles whitespace around values', () => { + expect( + getAllAcceptedMimeTypes(' text/html , application/json ; q=0.9 '), + ).toEqual(['text/html', 'application/json']) +}) + +it('handles a realistic browser accept header', () => { + expect( + getAllAcceptedMimeTypes( + 'text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8', + ), + ).toEqual(['text/html', 'application/xhtml+xml', 'application/xml', '*/*']) +}) + +it('handles the graphql-over-http accept header', () => { + expect( + getAllAcceptedMimeTypes( + 'application/graphql-response+json, application/json', + ), + ).toEqual(['application/graphql-response+json', 'application/json']) +}) diff --git a/node_modules/msw/src/core/utils/request/getAllAcceptedMimeTypes.ts b/node_modules/msw/src/core/utils/request/getAllAcceptedMimeTypes.ts new file mode 100644 index 0000000000000000000000000000000000000000..dbc0b1298ff9882497c7a8d7c43beece5fd2eed0 --- /dev/null +++ b/node_modules/msw/src/core/utils/request/getAllAcceptedMimeTypes.ts @@ -0,0 +1,70 @@ +/** + * Returns all accepted mime types, ordered by precedence as defined + * in [RFC 7231 Section 5.3.2](https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2). + * + * Precedence rules (highest to lowest): + * 1. Quality value (`q` parameter, default 1). + * 2. Specificity: `type/subtype` > `type/*` > `*\/*`. + * 3. Number of media type parameters (more = more specific). + * + * Types with `q=0` are excluded (explicitly not acceptable). + */ +export function getAllAcceptedMimeTypes( + acceptHeader: string | null, +): Array { + if (acceptHeader == null) { + return [] + } + + const accepted: Array<{ + type: string + quality: number + specificity: number + parameterCount: number + }> = [] + + for (const part of acceptHeader.split(',')) { + const [type, ...params] = part.split(';').map((v) => v.trim()) + + let quality = 1 + let parameterCount = 0 + + for (const param of params) { + const [key, value] = param.split('=').map((v) => v.trim()) + + if (key === 'q') { + quality = Number(value) + } else { + parameterCount++ + } + } + + // RFC 7231: a quality value of 0 indicates "not acceptable". + if (quality === 0) { + continue + } + + const [mediaType, mediaSubtype] = type.split('/') + const specificity = mediaType === '*' ? 0 : mediaSubtype === '*' ? 1 : 2 + + accepted.push({ type, quality, specificity, parameterCount }) + } + + if (!accepted.length) { + return [] + } + + return accepted + .sort((left, right) => { + if (right.quality !== left.quality) { + return right.quality - left.quality + } + + if (right.specificity !== left.specificity) { + return right.specificity - left.specificity + } + + return right.parameterCount - left.parameterCount + }) + .map((entry) => entry.type) +} diff --git a/node_modules/msw/src/core/utils/request/getRequestCookies.ts b/node_modules/msw/src/core/utils/request/getRequestCookies.ts new file mode 100644 index 0000000000000000000000000000000000000000..f80124cffb20b8f36aa707fa44856162f2ef5a47 --- /dev/null +++ b/node_modules/msw/src/core/utils/request/getRequestCookies.ts @@ -0,0 +1,88 @@ +import { + parse as parseCookie, + serialize as serializeCookie, +} from '../../../shims/cookie' +import { cookieStore } from '../cookieStore' + +function parseCookies(input: string): Record { + const parsedCookies = parseCookie(input) + const cookies: Record = {} + + for (const cookieName in parsedCookies) { + if (typeof parsedCookies[cookieName] !== 'undefined') { + cookies[cookieName] = parsedCookies[cookieName] + } + } + + return cookies +} + +function getAllDocumentCookies() { + return parseCookies(document.cookie) +} + +function getDocumentCookies(request: Request): Record { + if (typeof document === 'undefined' || typeof location === 'undefined') { + return {} + } + + switch (request.credentials) { + case 'same-origin': { + const requestUrl = new URL(request.url) + + // Return document cookies only when requested a resource + // from the same origin as the current document. + return location.origin === requestUrl.origin + ? getAllDocumentCookies() + : {} + } + + case 'include': { + // Return all document cookies. + return getAllDocumentCookies() + } + + default: { + return {} + } + } +} + +export function getAllRequestCookies(request: Request): Record { + /** + * @note While the "cookie" header is a forbidden header field + * in the browser, you can read it in Node.js. We need to respect + * it for mocking in Node.js. + */ + const requestCookieHeader = request.headers.get('cookie') + const cookiesFromHeaders = requestCookieHeader + ? parseCookies(requestCookieHeader) + : {} + + const cookiesFromDocument = getDocumentCookies(request) + + // Forward the document cookies to the request headers. + for (const name in cookiesFromDocument) { + request.headers.append( + 'cookie', + serializeCookie(name, cookiesFromDocument[name]), + ) + } + + const cookiesFromStore = cookieStore.getCookies(request.url) + const storedCookiesObject = Object.fromEntries( + cookiesFromStore.map((cookie) => [cookie.key, cookie.value]), + ) + + // Forward the raw stored cookies to request headers + // so they contain metadata like "expires", "secure", etc. + for (const cookie of cookiesFromStore) { + request.headers.append('cookie', cookie.toString()) + } + + return { + ...cookiesFromDocument, + ...storedCookiesObject, + ...cookiesFromHeaders, + } +} diff --git a/node_modules/msw/src/core/utils/request/onUnhandledRequest.node.test.ts b/node_modules/msw/src/core/utils/request/onUnhandledRequest.node.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..aca44fca3773b52afe69bce269a6a74d0fd416e4 --- /dev/null +++ b/node_modules/msw/src/core/utils/request/onUnhandledRequest.node.test.ts @@ -0,0 +1,62 @@ +// @vitest-environment node +import { onUnhandledRequest } from './onUnhandledRequest' + +const fixtures = { + warningWithoutSuggestions: (url = `/api`) => `\ +[MSW] Warning: intercepted a request without a matching request handler: + + • GET ${url} + +If you still wish to intercept this unhandled request, please create a request handler for it. +Read more: https://mswjs.io/docs/http/intercepting-requests`, + warningWithResponseBody: (url = `/api`) => `\ +[MSW] Warning: intercepted a request without a matching request handler: + + • POST ${url} + + • Request body: {"variables":{"id":"abc-123"},"query":"query UserName($id: String!) { user(id: $id) { name } }"} + +If you still wish to intercept this unhandled request, please create a request handler for it. +Read more: https://mswjs.io/docs/http/intercepting-requests`, + + errorWithoutSuggestions: `\ +[MSW] Error: intercepted a request without a matching request handler: + + • GET /api + +If you still wish to intercept this unhandled request, please create a request handler for it. +Read more: https://mswjs.io/docs/http/intercepting-requests`, +} + +beforeAll(() => { + vi.spyOn(console, 'warn').mockImplementation(() => void 0) + vi.spyOn(console, 'error').mockImplementation(() => void 0) +}) + +afterEach(() => { + vi.clearAllMocks() +}) + +afterAll(() => { + vi.restoreAllMocks() +}) + +test('prints with an absolute URL and search params', async () => { + await onUnhandledRequest( + new Request(new URL('https://mswjs.io/api?foo=boo')), + 'warn', + ) + + expect(console.warn).toHaveBeenCalledWith( + fixtures.warningWithoutSuggestions(`https://mswjs.io/api?foo=boo`), + ) + + await onUnhandledRequest( + new Request(new URL('http://localhost/api?foo=boo')), + 'warn', + ) + + expect(console.warn).toHaveBeenCalledWith( + fixtures.warningWithoutSuggestions(`http://localhost/api?foo=boo`), + ) +}) diff --git a/node_modules/msw/src/core/utils/request/onUnhandledRequest.test.ts b/node_modules/msw/src/core/utils/request/onUnhandledRequest.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d570a857a81ec791034fa6bfed821c4f5330eb7f --- /dev/null +++ b/node_modules/msw/src/core/utils/request/onUnhandledRequest.test.ts @@ -0,0 +1,226 @@ +// @vitest-environment jsdom +import type { UnhandledRequestCallback } from './onUnhandledRequest' +import { onUnhandledRequest } from './onUnhandledRequest' + +const fixtures = { + warningWithoutSuggestions: (url = `/api`) => `\ +[MSW] Warning: intercepted a request without a matching request handler: + + • GET ${url} + +If you still wish to intercept this unhandled request, please create a request handler for it. +Read more: https://mswjs.io/docs/http/intercepting-requests`, + warningWithResponseBody: (url = `/api`) => `\ +[MSW] Warning: intercepted a request without a matching request handler: + + • POST ${url} + + • Request body: {"variables":{"id":"abc-123"},"query":"query UserName($id: String!) { user(id: $id) { name } }"} + +If you still wish to intercept this unhandled request, please create a request handler for it. +Read more: https://mswjs.io/docs/http/intercepting-requests`, + + errorWithoutSuggestions: `\ +[MSW] Error: intercepted a request without a matching request handler: + + • GET /api + +If you still wish to intercept this unhandled request, please create a request handler for it. +Read more: https://mswjs.io/docs/http/intercepting-requests`, +} + +beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => void 0) + vi.spyOn(console, 'error').mockImplementation(() => void 0) +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + +test('supports the "bypass" request strategy', async () => { + await onUnhandledRequest( + new Request(new URL('http://localhost/api')), + 'bypass', + ) + + expect(console.warn).not.toHaveBeenCalled() + expect(console.error).not.toHaveBeenCalled() +}) + +test('supports the "warn" request strategy', async () => { + await onUnhandledRequest(new Request(new URL('http://localhost/api')), 'warn') + + expect(console.warn).toHaveBeenCalledWith( + fixtures.warningWithoutSuggestions(), + ) +}) + +test('supports the "warn" request strategy with request body', async () => { + await onUnhandledRequest( + new Request(new URL('http://localhost/api'), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + variables: { + id: 'abc-123', + }, + query: 'query UserName($id: String!) { user(id: $id) { name } }', + }), + }), + ) + + expect(console.warn).toHaveBeenCalledWith(fixtures.warningWithResponseBody()) +}) + +test('supports the "error" request strategy', async () => { + await expect( + onUnhandledRequest(new Request(new URL('http://localhost/api')), 'error'), + ).rejects.toThrow( + '[MSW] Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.', + ) + + expect(console.error).toHaveBeenCalledWith(fixtures.errorWithoutSuggestions) +}) + +test('supports a custom callback function', async () => { + const callback = vi.fn((request) => { + console.warn(`callback: ${request.method} ${request.url}`) + }) + const request = new Request(new URL('/user', 'http://localhost:3000')) + await onUnhandledRequest(request, callback) + + expect(callback).toHaveBeenCalledTimes(1) + expect(callback).toHaveBeenCalledWith(request, { + warning: expect.any(Function), + error: expect.any(Function), + }) + + // Check that the custom logic in the callback was called. + expect(console.warn).toHaveBeenCalledWith( + `callback: GET http://localhost:3000/user`, + ) +}) + +test('supports calling default strategies from the custom callback function', async () => { + const callback = vi.fn((request, print) => { + // Call the default "error" strategy. + print.error() + }) + const request = new Request(new URL('http://localhost/api')) + await expect(onUnhandledRequest(request, callback)).rejects.toThrow( + `[MSW] Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.`, + ) + + expect(callback).toHaveBeenCalledTimes(1) + expect(callback).toHaveBeenCalledWith(request, { + warning: expect.any(Function), + error: expect.any(Function), + }) + + // Check that the default strategy was called. + expect(console.error).toHaveBeenCalledWith(fixtures.errorWithoutSuggestions) +}) + +test('does not print any suggestions given no handlers to suggest', async () => { + await onUnhandledRequest(new Request(new URL('http://localhost/api')), 'warn') + + expect(console.warn).toHaveBeenCalledWith( + fixtures.warningWithoutSuggestions(), + ) +}) + +test('throws an exception given unknown request strategy', async () => { + await expect( + onUnhandledRequest( + new Request(new URL('http://localhost/api')), + // @ts-expect-error Intentional unknown strategy. + 'invalid-strategy', + ), + ).rejects.toThrow( + '[MSW] Failed to react to an unhandled request: unknown strategy "invalid-strategy". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.', + ) +}) + +test('prints with a relative URL and search params', async () => { + await onUnhandledRequest( + new Request(new URL('http://localhost/api?foo=boo')), + 'warn', + ) + + expect(console.warn).toHaveBeenCalledWith( + fixtures.warningWithoutSuggestions(`/api?foo=boo`), + ) +}) + +test('prints with an absolute URL and search params', async () => { + await onUnhandledRequest( + new Request(new URL('https://mswjs.io/api?foo=boo')), + 'warn', + ) + + expect(console.warn).toHaveBeenCalledWith( + fixtures.warningWithoutSuggestions(`https://mswjs.io/api?foo=boo`), + ) +}) + +test('ignores common static assets when using the "warn" strategy', async () => { + await Promise.allSettled([ + onUnhandledRequest( + new Request(new URL('https://example.com/main.css')), + 'warn', + ), + onUnhandledRequest( + new Request(new URL('https://example.com/index.mjs')), + 'warn', + ), + onUnhandledRequest( + new Request(new URL('https://example.com/node_modules/abc-123')), + 'warn', + ), + onUnhandledRequest( + new Request(new URL('https://fonts.googleapis.com/some-font')), + 'warn', + ), + ]) + + expect(console.warn).not.toHaveBeenCalled() +}) + +test('ignores common static assets when using the "error" strategy', async () => { + await Promise.allSettled([ + onUnhandledRequest( + new Request(new URL('https://example.com/main.css')), + 'error', + ), + onUnhandledRequest( + new Request(new URL('https://example.com/index.mjs')), + 'error', + ), + onUnhandledRequest( + new Request(new URL('https://example.com/node_modules/abc-123')), + 'error', + ), + onUnhandledRequest( + new Request(new URL('https://fonts.googleapis.com/some-font')), + 'error', + ), + ]) + + expect(console.error).not.toHaveBeenCalled() +}) + +test('exposes common static assets to the explicit callback', async () => { + let callbackRequest!: Request + await onUnhandledRequest( + new Request(new URL('https://example.com/main.css')), + (request) => { + callbackRequest = request + }, + ) + + expect(callbackRequest).toBeInstanceOf(Request) + expect(callbackRequest.url).toBe('https://example.com/main.css') +}) diff --git a/node_modules/msw/src/core/utils/request/onUnhandledRequest.ts b/node_modules/msw/src/core/utils/request/onUnhandledRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..e15987bc558a78c9b6a92bd8b62431a03d73c5cd --- /dev/null +++ b/node_modules/msw/src/core/utils/request/onUnhandledRequest.ts @@ -0,0 +1,81 @@ +import { toPublicUrl } from './toPublicUrl' +import { InternalError, devUtils } from '../internal/devUtils' +import { isCommonAssetRequest } from '../../isCommonAssetRequest' + +export interface UnhandledRequestPrint { + warning: () => void + error: () => void +} + +export type UnhandledRequestCallback = ( + request: Request, + print: UnhandledRequestPrint, +) => void + +export type UnhandledRequestStrategy = + | 'bypass' + | 'warn' + | 'error' + | UnhandledRequestCallback + +export async function onUnhandledRequest( + request: Request, + strategy: UnhandledRequestStrategy = 'warn', +): Promise { + const url = new URL(request.url) + const publicUrl = toPublicUrl(url) + url.search + + const requestBody = + request.method === 'HEAD' || request.method === 'GET' + ? null + : await request.clone().text() + const messageDetails = `\n\n \u2022 ${request.method} ${publicUrl}\n\n${requestBody ? ` \u2022 Request body: ${requestBody}\n\n` : ''}` + const unhandledRequestMessage = `intercepted a request without a matching request handler:${messageDetails}If you still wish to intercept this unhandled request, please create a request handler for it.\nRead more: https://mswjs.io/docs/http/intercepting-requests` + + function applyStrategy(strategy: UnhandledRequestStrategy) { + switch (strategy) { + case 'error': { + // Print a developer-friendly error. + devUtils.error('Error: %s', unhandledRequestMessage) + + // Throw an exception to halt request processing and not perform the original request. + throw new InternalError( + devUtils.formatMessage( + 'Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.', + ), + ) + } + + case 'warn': { + devUtils.warn('Warning: %s', unhandledRequestMessage) + break + } + + case 'bypass': + break + + default: + throw new InternalError( + devUtils.formatMessage( + 'Failed to react to an unhandled request: unknown strategy "%s". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.', + strategy, + ), + ) + } + } + + if (typeof strategy === 'function') { + strategy(request, { + warning: applyStrategy.bind(null, 'warn'), + error: applyStrategy.bind(null, 'error'), + }) + return + } + + // Ignore common static asset requests when using a built-in strategy. + // There's a slight overhead here because this utility will create a request URL + // instance again despite us having done so previously in this function. + if (!isCommonAssetRequest(request)) { + applyStrategy(strategy) + } +} diff --git a/node_modules/msw/src/core/utils/request/storeResponseCookies.ts b/node_modules/msw/src/core/utils/request/storeResponseCookies.ts new file mode 100644 index 0000000000000000000000000000000000000000..3eacdcf89ab48c45873808048c63b482ac8a7fb3 --- /dev/null +++ b/node_modules/msw/src/core/utils/request/storeResponseCookies.ts @@ -0,0 +1,15 @@ +import { cookieStore } from '../cookieStore' +import { getRawSetCookie } from '../HttpResponse/decorators' + +export async function storeResponseCookies( + request: Request, + response: Response, +): Promise { + // Grab the raw "Set-Cookie" response header provided + // in the HeadersInit for this mocked response. + const responseCookies = getRawSetCookie(response) + + if (responseCookies) { + await cookieStore.setCookie(responseCookies, request.url) + } +} diff --git a/node_modules/msw/src/core/utils/request/toPublicUrl.node.test.ts b/node_modules/msw/src/core/utils/request/toPublicUrl.node.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0338df6a8f1ea34d956031796e40d2099f82083d --- /dev/null +++ b/node_modules/msw/src/core/utils/request/toPublicUrl.node.test.ts @@ -0,0 +1,17 @@ +// @vitest-environment node +import { toPublicUrl } from './toPublicUrl' + +test('returns an absolute request URL without search params', () => { + expect(toPublicUrl(new URL('https://test.mswjs.io/path'))).toBe( + 'https://test.mswjs.io/path', + ) + + expect(toPublicUrl(new URL('http://192.168.0.10/path'))).toBe( + 'http://192.168.0.10/path', + ) + + expect( + toPublicUrl(new URL('http://localhost/path?foo=bar')), + 'Must not return relative URL in Node.js', + ).toBe('http://localhost/path') +}) diff --git a/node_modules/msw/src/core/utils/request/toPublicUrl.test.ts b/node_modules/msw/src/core/utils/request/toPublicUrl.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6622d36254c12dbdef5208d96b4ef6555e9b5362 --- /dev/null +++ b/node_modules/msw/src/core/utils/request/toPublicUrl.test.ts @@ -0,0 +1,16 @@ +// @vitest-environment jsdom +import { toPublicUrl } from './toPublicUrl' + +test('returns an absolute request URL without search params', () => { + expect(toPublicUrl(new URL('https://test.mswjs.io/path'))).toBe( + 'https://test.mswjs.io/path', + ) + + expect(toPublicUrl(new URL('http://localhost/path'))).toBe('/path') + + expect(toPublicUrl(new URL('http://localhost/path?foo=bar'))).toBe('/path') +}) + +it('returns a relative URL given the request to the same origin', () => { + expect(toPublicUrl('http://localhost/user')).toBe('/user') +}) diff --git a/node_modules/msw/src/core/utils/request/toPublicUrl.ts b/node_modules/msw/src/core/utils/request/toPublicUrl.ts new file mode 100644 index 0000000000000000000000000000000000000000..3930f40be57d0a5f4c75bdca71b1b517f8c063b1 --- /dev/null +++ b/node_modules/msw/src/core/utils/request/toPublicUrl.ts @@ -0,0 +1,16 @@ +/** + * Returns a relative URL if the given request URL is relative + * to the current origin. Otherwise returns an absolute URL. + */ +export function toPublicUrl(url: string | URL): string { + const urlInstance = url instanceof URL ? url : new URL(url) + + if ( + typeof location !== 'undefined' && + urlInstance.origin === location.origin + ) { + return urlInstance.pathname + } + + return urlInstance.origin + urlInstance.pathname +} diff --git a/node_modules/msw/src/core/utils/toResponseInit.ts b/node_modules/msw/src/core/utils/toResponseInit.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7e6f9a7ae200fc610d07180c284a4e80880fc5f --- /dev/null +++ b/node_modules/msw/src/core/utils/toResponseInit.ts @@ -0,0 +1,7 @@ +export function toResponseInit(response: Response): ResponseInit { + return { + status: response.status, + statusText: response.statusText, + headers: Object.fromEntries(response.headers.entries()), + } +} diff --git a/node_modules/msw/src/core/utils/url/cleanUrl.test.ts b/node_modules/msw/src/core/utils/url/cleanUrl.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a04560d3a1ab807e30c878e1486c3e6e0c70289 --- /dev/null +++ b/node_modules/msw/src/core/utils/url/cleanUrl.test.ts @@ -0,0 +1,22 @@ +import { cleanUrl } from './cleanUrl' + +it('removes query parameters from a URL string', () => { + expect(cleanUrl('/user?id=123')).toEqual('/user') + expect(cleanUrl('/user?id=123&id=456')).toEqual('/user') + expect(cleanUrl('/user?id=123&role=admin')).toEqual('/user') +}) + +it('removes hashes from a URL string', () => { + expect(cleanUrl('/user#hash')).toEqual('/user') + expect(cleanUrl('/user#hash-with-dashes')).toEqual('/user') +}) + +it('removes both query parameters and hashes from a URL string', () => { + expect(cleanUrl('/user?id=123#some')).toEqual('/user') + expect(cleanUrl('/user?id=123&role=admin#some')).toEqual('/user') +}) + +it('preserves optional path parameters', () => { + expect(cleanUrl('/user/:id?')).toEqual('/user/:id?') + expect(cleanUrl('/user/:id?/:messageId?')).toEqual('/user/:id?/:messageId?') +}) diff --git a/node_modules/msw/src/core/utils/url/cleanUrl.ts b/node_modules/msw/src/core/utils/url/cleanUrl.ts new file mode 100644 index 0000000000000000000000000000000000000000..4eae2b593a9017dbf90b3a1577cff571fec70101 --- /dev/null +++ b/node_modules/msw/src/core/utils/url/cleanUrl.ts @@ -0,0 +1,16 @@ +const REDUNDANT_CHARACTERS_EXP = /[?|#].*$/g + +/** + * Removes search parameters and the fragment + * from a given URL string. + */ +export function cleanUrl(path: string): string { + // If the path ends with an optional path parameter, + // return it as-is. + if (path.endsWith('?')) { + return path + } + + // Otherwise, remove the search and fragment from it. + return path.replace(REDUNDANT_CHARACTERS_EXP, '') +} diff --git a/node_modules/msw/src/core/utils/url/getAbsoluteUrl.node.test.ts b/node_modules/msw/src/core/utils/url/getAbsoluteUrl.node.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..918ed215d44a82dfe8ac5274787f36bb11f0f74f --- /dev/null +++ b/node_modules/msw/src/core/utils/url/getAbsoluteUrl.node.test.ts @@ -0,0 +1,19 @@ +/** + * @vitest-environment node + */ +import { getAbsoluteUrl } from './getAbsoluteUrl' + +it('returns a given relative URL as-is', () => { + expect(getAbsoluteUrl('/reviews')).toBe('/reviews') +}) + +it('rebases a relative URL against a custom base URL', () => { + expect(getAbsoluteUrl('/user', 'https://api.github.com')).toEqual( + 'https://api.github.com/user', + ) +}) +it('returns a given absolute URL as-is', () => { + expect(getAbsoluteUrl('https://api.mswjs.io/users')).toBe( + 'https://api.mswjs.io/users', + ) +}) diff --git a/node_modules/msw/src/core/utils/url/getAbsoluteUrl.test.ts b/node_modules/msw/src/core/utils/url/getAbsoluteUrl.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e085a153f6393778cd5df7e8160616e381d1ed9 --- /dev/null +++ b/node_modules/msw/src/core/utils/url/getAbsoluteUrl.test.ts @@ -0,0 +1,47 @@ +// @vitest-environment jsdom +import { getAbsoluteUrl } from './getAbsoluteUrl' + +const rawLocation = window.location + +afterAll(() => { + Object.defineProperty(window, 'location', { + value: rawLocation, + }) +}) + +it('resolves a relative URL against the current location (default)', () => { + expect(getAbsoluteUrl('/reviews')).toBe('http://localhost/reviews') +}) + +it('supports relative URLs starting with search parameters', () => { + Object.defineProperty(window, 'location', { + value: { + href: 'http://localhost/nested', + }, + }) + + expect(getAbsoluteUrl('?resourceId=abc-123')).toBe( + 'http://localhost/nested?resourceId=abc-123', + ) +}) + +it('resolves a relative URL against a custom base URL', () => { + expect(getAbsoluteUrl('/user', 'https://api.github.com')).toBe( + 'https://api.github.com/user', + ) +}) + +it('returns a given absolute URL as-is', () => { + expect(getAbsoluteUrl('https://api.mswjs.io/users')).toBe( + 'https://api.mswjs.io/users', + ) +}) + +it('returns an absolute URL given a relative path without a leading slash', () => { + expect(getAbsoluteUrl('users')).toBe('http://localhost/users') +}) + +it('returns a path with a pattern as-is', () => { + expect(getAbsoluteUrl(':api/user')).toBe('http://localhost/:api/user') + expect(getAbsoluteUrl('*/resource/*')).toBe('*/resource/*') +}) diff --git a/node_modules/msw/src/core/utils/url/getAbsoluteUrl.ts b/node_modules/msw/src/core/utils/url/getAbsoluteUrl.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb46a4afc62e11ab8e76610e8b7b4bd35f522940 --- /dev/null +++ b/node_modules/msw/src/core/utils/url/getAbsoluteUrl.ts @@ -0,0 +1,25 @@ +import { isAbsoluteUrl } from './isAbsoluteUrl' + +/** + * Returns an absolute URL based on the given path. + */ +export function getAbsoluteUrl(path: string, baseUrl?: string): string { + // already absolute URL + if (isAbsoluteUrl(path)) { + return path + } + + // Ignore path with pattern start with * + if (path.startsWith('*')) { + return path + } + + // Resolve a relative request URL against a given custom "baseUrl" + // or the document baseURI (in the case of browser/browser-like environments). + const origin = baseUrl || (typeof location !== 'undefined' && location.href) + + return origin + ? // Encode and decode the path to preserve escaped characters. + decodeURI(new URL(encodeURI(path), origin).href) + : path +} diff --git a/node_modules/msw/src/core/utils/url/isAbsoluteUrl.test.ts b/node_modules/msw/src/core/utils/url/isAbsoluteUrl.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c213fde87743df6d58f0d36dc36957d678fe202 --- /dev/null +++ b/node_modules/msw/src/core/utils/url/isAbsoluteUrl.test.ts @@ -0,0 +1,32 @@ +/** + * @vitest-environment node + */ +import { isAbsoluteUrl } from './isAbsoluteUrl' + +it('returns true for the "http" scheme', () => { + expect(isAbsoluteUrl('http://www.domain.com')).toEqual(true) +}) + +it('returns true for the "https" scheme', () => { + expect(isAbsoluteUrl('https://www.domain.com')).toEqual(true) +}) + +it('returns true for the "ws" scheme', () => { + expect(isAbsoluteUrl('ws://www.domain.com')).toEqual(true) +}) + +it('returns true for the "ftp" scheme', () => { + expect(isAbsoluteUrl('ftp://www.domain.com')).toEqual(true) +}) + +it('returns true for the custom scheme', () => { + expect(isAbsoluteUrl('web+my://www.example.com')).toEqual(true) +}) + +it('returns false for the relative URL', () => { + expect(isAbsoluteUrl('/test')).toEqual(false) +}) + +it('returns false for the relative URL without a leading slash', () => { + expect(isAbsoluteUrl('test')).toEqual(false) +}) diff --git a/node_modules/msw/src/core/utils/url/isAbsoluteUrl.ts b/node_modules/msw/src/core/utils/url/isAbsoluteUrl.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4fd9d054f1ad7b4400327a1dea34cd6f90a2d1a --- /dev/null +++ b/node_modules/msw/src/core/utils/url/isAbsoluteUrl.ts @@ -0,0 +1,6 @@ +/** + * Determines if the given URL string is an absolute URL. + */ +export function isAbsoluteUrl(url: string): boolean { + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url) +} diff --git a/node_modules/msw/src/core/ws.test.ts b/node_modules/msw/src/core/ws.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0f4eff7597a5cc1ec8e596c4efac4d0e80b63623 --- /dev/null +++ b/node_modules/msw/src/core/ws.test.ts @@ -0,0 +1,21 @@ +// @vitest-environment node-websocket +import { ws } from './ws' + +it('exports the "link()" method', () => { + expect(ws).toHaveProperty('link') + expect(ws.link).toBeInstanceOf(Function) +}) + +it('throws an error when calling "ws.link()" without a URL argument', () => { + expect(() => + // @ts-expect-error Intentionally invalid call. + ws.link(), + ).toThrow('Expected a WebSocket server URL but got undefined') +}) + +it('throws an error when given a non-path argument to "ws.link()"', () => { + expect(() => + // @ts-expect-error Intentionally invalid argument. + ws.link(2), + ).toThrow('Expected a WebSocket server URL to be a valid path but got number') +}) diff --git a/node_modules/msw/src/core/ws.ts b/node_modules/msw/src/core/ws.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c99ee8230445f2a333da5a516793e5930517028 --- /dev/null +++ b/node_modules/msw/src/core/ws.ts @@ -0,0 +1,220 @@ +import { invariant } from 'outvariant' +import { FetchResponse, resolveWebSocketUrl } from '@mswjs/interceptors' +import type { + WebSocketData, + WebSocketClientConnectionProtocol, +} from '@mswjs/interceptors/WebSocket' +import { + WebSocketHandler, + kEmitter, + type WebSocketHandlerEventMap, +} from './handlers/WebSocketHandler' +import { hasRefCounted } from './utils/internal/hasRefCounted' +import { + type Path, + type PathParams, + isPath, + matchRequestUrl, +} from './utils/matching/matchRequestUrl' +import { WebSocketClientManager } from './ws/WebSocketClientManager' +import { http } from './http' +import { attachSiblingHandlers } from './utils/internal/attachSiblingHandlers' + +const webSocketChannel = new BroadcastChannel('msw:websocket-client-manager') + +if (hasRefCounted(webSocketChannel)) { + // Allows the Node.js thread to exit if it is the only active handle in the event system. + // https://nodejs.org/api/worker_threads.html#broadcastchannelunref + webSocketChannel.unref() +} + +export type WebSocketEventListener< + EventType extends keyof WebSocketHandlerEventMap, +> = (...args: WebSocketHandlerEventMap[EventType]) => void + +export type WebSocketLink = { + /** + * A set of all WebSocket clients connected + * to this link. + * + * @see {@link https://mswjs.io/docs/api/ws#clients `clients` API reference} + */ + clients: Set + + /** + * Adds an event listener to this WebSocket link. + * + * @example + * const chat = ws.link('wss://chat.example.com') + * chat.addEventListener('connection', listener) + * + * @see {@link https://mswjs.io/docs/api/ws#onevent-listener `on()` API reference} + */ + addEventListener: ( + event: EventType, + listener: WebSocketEventListener, + ) => WebSocketHandler + + /** + * Broadcasts the given data to all WebSocket clients. + * + * @example + * const service = ws.link('wss://example.com') + * service.addEventListener('connection', () => { + * service.broadcast('hello, everyone!') + * }) + * + * @see {@link https://mswjs.io/docs/api/ws#broadcastdata `broadcast()` API reference} + */ + broadcast: (data: WebSocketData) => void + + /** + * Broadcasts the given data to all WebSocket clients + * except the ones provided in the `clients` argument. + * + * @example + * const service = ws.link('wss://example.com') + * service.addEventListener('connection', ({ client }) => { + * service.broadcastExcept(client, 'hi, the rest of you!') + * }) + * + * @see {@link https://mswjs.io/docs/api/ws#broadcastexceptclients-data `broadcast()` API reference} + */ + broadcastExcept: ( + clients: + | WebSocketClientConnectionProtocol + | Array, + data: WebSocketData, + ) => void +} + +/** + * Intercepts outgoing WebSocket connections to the given URL. + * + * @example + * const chat = ws.link('wss://chat.example.com') + * chat.addEventListener('connection', ({ client }) => { + * client.send('hello from server!') + * }) + */ +function createWebSocketLinkHandler(url: Path): WebSocketLink { + invariant(url, 'Expected a WebSocket server URL but got undefined') + + invariant( + isPath(url), + 'Expected a WebSocket server URL to be a valid path but got %s', + typeof url, + ) + + const clientManager = new WebSocketClientManager(webSocketChannel) + + // The same upgrade handler instance is attached as a sibling to every + // WebSocketHandler returned by this link. `groupHandlersByKind` dedupes + // by reference, so it lands in the `request` bucket exactly once regardless + // of which subset of WS handlers the user ends up registering. + const upgradeHandler = http.get(({ request }) => { + return ( + request.headers.get('upgrade')?.toLowerCase() === 'websocket' && + matchRequestUrl(new URL(resolveWebSocketUrl(request.url)), url).matches + ) + }, ws.onUpgrade) + + return { + get clients() { + return clientManager.clients + }, + addEventListener(event, listener) { + const webSocketHandler = new WebSocketHandler(url) + + // Add the connection event listener for when the + // handler matches and emits a connection event. + // When that happens, store that connection in the + // set of all connections for reference. + webSocketHandler[kEmitter].on('connection', async ({ client }) => { + await clientManager.addConnection(client) + }) + + // The "handleWebSocketEvent" function will invoke + // the "run()" method on the WebSocketHandler. + // If the handler matches, it will emit the "connection" + // event. Attach the user-defined listener to that event. + webSocketHandler[kEmitter].on(event, listener) + + return attachSiblingHandlers(webSocketHandler, [upgradeHandler]) + }, + + broadcast(data) { + // This will invoke "send()" on the immediate clients + // in this runtime and post a message to the broadcast channel + // to trigger send for the clients in other runtimes. + this.broadcastExcept([], data) + }, + + broadcastExcept(clients, data) { + const ignoreClients = Array.prototype + .concat(clients) + .map((client) => client.id) + + clientManager.clients.forEach((otherClient) => { + if (!ignoreClients.includes(otherClient.id)) { + otherClient.send(data) + } + }) + }, + } +} + +const WEBSOCKET_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' + +interface WebSocketNamespace { + link: typeof createWebSocketLinkHandler + /** + * Request handler for the `upgrade` requests to the WebSocket protocol. + * This requires a WebSocket handler to be present to fire. + * @note This only affects Node.js as the `upgrade` request header is + * forbidden and cannot be read in the browser. Consider using the + * `WebSocket` API for establishing WebSocket connections in the browser. + */ + onUpgrade: (info: { + requestId: string + request: Request + params: PathParams + }) => Promise | Response | undefined +} + +/** + * A namespace to intercept and mock WebSocket connections. + * + * @example + * const chat = ws.link('wss://chat.example.com') + * + * @see {@link https://mswjs.io/docs/api/ws `ws` API reference} + * @see {@link https://mswjs.io/docs/basics/handling-websocket-events Handling WebSocket events} + */ +export const ws: WebSocketNamespace = { + link: createWebSocketLinkHandler, + async onUpgrade({ request }) { + const key = request.headers.get('sec-websocket-key') + + if (!key) { + return + } + + const keyBytes = new TextEncoder().encode(key + WEBSOCKET_GUID) + const digest = await crypto.subtle.digest('SHA-1', keyBytes) + const acceptValue = btoa(String.fromCharCode(...new Uint8Array(digest))) + + new WebSocket(resolveWebSocketUrl(request.url)) + + return new FetchResponse(null, { + status: 101, + headers: { + upgrade: 'websocket', + connection: 'upgrade', + 'sec-websocket-accept': acceptValue, + }, + }) + }, +} + +export { type WebSocketData } diff --git a/node_modules/msw/src/core/ws/WebSocketClientManager.test.ts b/node_modules/msw/src/core/ws/WebSocketClientManager.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc1b2d30f183ac93d176a4627fbaed4e0f64ab80 --- /dev/null +++ b/node_modules/msw/src/core/ws/WebSocketClientManager.test.ts @@ -0,0 +1,154 @@ +// @vitest-environment node-websocket +import { setMaxListeners } from 'node:events' +import { WebSocketClientConnection } from '@mswjs/interceptors/WebSocket' +import type { WebSocketBroadcastChannelMessage } from './WebSocketClientManager' +import { WebSocketClientManager } from './WebSocketClientManager' +import { TestWebSocketTransport } from '../../../test/support/ws-test-utils' + +const channel = new BroadcastChannel('test:channel') + +/** + * @note Increase the number of maximum event listeners + * because the same channel is shared between different + * manager instances in different tests. + */ +setMaxListeners(Number.MAX_SAFE_INTEGER, channel) + +vi.spyOn(channel, 'postMessage') + +const socket = new WebSocket('ws://localhost') + +afterEach(() => { + vi.resetAllMocks() +}) + +it('adds a client from this runtime to the list of clients', async () => { + const manager = new WebSocketClientManager(channel) + const connection = new WebSocketClientConnection( + socket, + new TestWebSocketTransport(), + ) + + await manager.addConnection(connection) + + // Must add the client to the list of clients. + expect(Array.from(manager.clients.values())).toEqual([connection]) +}) + +it('adds multiple clients from this runtime to the list of clients', async () => { + const manager = new WebSocketClientManager(channel) + const connectionOne = new WebSocketClientConnection( + socket, + new TestWebSocketTransport(), + ) + await manager.addConnection(connectionOne) + + // Must add the client to the list of clients. + expect(Array.from(manager.clients.values())).toEqual([connectionOne]) + + const connectionTwo = new WebSocketClientConnection( + socket, + new TestWebSocketTransport(), + ) + await manager.addConnection(connectionTwo) + + // Must add the new client to the list as well. + expect(Array.from(manager.clients.values())).toEqual([ + connectionOne, + connectionTwo, + ]) +}) + +it('replays a "send" event coming from another runtime', async () => { + const manager = new WebSocketClientManager(channel) + const connection = new WebSocketClientConnection( + socket, + new TestWebSocketTransport(), + ) + await manager.addConnection(connection) + vi.spyOn(connection, 'send') + + // Emulate another runtime signaling this connection to receive data. + channel.dispatchEvent( + new MessageEvent('message', { + data: { + type: 'extraneous:send', + payload: { + clientId: connection.id, + data: 'hello', + }, + }, + }), + ) + + await vi.waitFor(() => { + // Must execute the requested operation on the connection. + expect(connection.send).toHaveBeenCalledWith('hello') + expect(connection.send).toHaveBeenCalledTimes(1) + }) +}) + +it('replays a "close" event coming from another runtime', async () => { + const manager = new WebSocketClientManager(channel) + const connection = new WebSocketClientConnection( + socket, + new TestWebSocketTransport(), + ) + await manager.addConnection(connection) + vi.spyOn(connection, 'close') + + // Emulate another runtime signaling this connection to close. + channel.dispatchEvent( + new MessageEvent('message', { + data: { + type: 'extraneous:close', + payload: { + clientId: connection.id, + code: 1000, + reason: 'Normal closure', + }, + }, + }), + ) + + await vi.waitFor(() => { + // Must execute the requested operation on the connection. + expect(connection.close).toHaveBeenCalledWith(1000, 'Normal closure') + expect(connection.close).toHaveBeenCalledTimes(1) + }) +}) + +it('removes the extraneous message listener when the connection closes', async () => { + const manager = new WebSocketClientManager(channel) + const transport = new TestWebSocketTransport() + const connection = new WebSocketClientConnection(socket, transport) + vi.spyOn(connection, 'close').mockImplementationOnce(() => { + /** + * @note This is a nasty hack so we don't have to uncouple + * the connection from transport. Creating a mock transport + * is difficult because it relies on the `WebSocketOverride` class. + * All we care here is that closing the connection triggers + * the transport closure, which it always does. + */ + transport.dispatchEvent(new Event('close')) + }) + vi.spyOn(connection, 'send') + + await manager.addConnection(connection) + connection.close() + + // Signals from other runtimes have no effect on the closed connection. + channel.dispatchEvent( + new MessageEvent('message', { + data: { + type: 'extraneous:send', + payload: { + clientId: connection.id, + data: 'hello', + }, + }, + }), + ) + + expect(connection.send).not.toHaveBeenCalled() +}) diff --git a/node_modules/msw/src/core/ws/WebSocketClientManager.ts b/node_modules/msw/src/core/ws/WebSocketClientManager.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ffdff4bd2d4cd3a05004e841e38a7ecc02e26ef --- /dev/null +++ b/node_modules/msw/src/core/ws/WebSocketClientManager.ts @@ -0,0 +1,241 @@ +import type { + WebSocketData, + WebSocketClientConnectionProtocol, + WebSocketClientEventMap, +} from '@mswjs/interceptors/WebSocket' +import type { WebSocketClientStore } from './WebSocketClientStore' +import { WebSocketMemoryClientStore } from './WebSocketMemoryClientStore' +import { WebSocketIndexedDBClientStore } from './WebSocketIndexedDBClientStore' + +export type WebSocketBroadcastChannelMessage = + | { + type: 'extraneous:send' + payload: { + clientId: string + data: WebSocketData + } + } + | { + type: 'extraneous:close' + payload: { + clientId: string + code?: number + reason?: string + } + } + +/** + * A manager responsible for accumulating WebSocket client + * connections across different browser runtimes. + */ +export class WebSocketClientManager { + private store: WebSocketClientStore + private runtimeClients: Map + private allClients: Set + + constructor(private channel: BroadcastChannel) { + // Store the clients in the IndexedDB in the browser, + // otherwise, store the clients in memory. + this.store = + typeof indexedDB !== 'undefined' + ? new WebSocketIndexedDBClientStore() + : new WebSocketMemoryClientStore() + + this.runtimeClients = new Map() + this.allClients = new Set() + + this.channel.addEventListener('message', (message) => { + if (message.data?.type === 'db:update') { + this.flushDatabaseToMemory() + } + }) + + if (typeof window !== 'undefined') { + window.addEventListener('message', async (message) => { + if (message.data?.type === 'msw/worker:stop') { + await this.removeRuntimeClients() + } + }) + } + } + + private async flushDatabaseToMemory() { + const storedClients = await this.store.getAll() + + this.allClients = new Set( + storedClients.map((client) => { + const runtimeClient = this.runtimeClients.get(client.id) + + /** + * @note For clients originating in this runtime, use their + * direct references. No need to wrap them in a remote connection. + */ + if (runtimeClient) { + return runtimeClient + } + + return new WebSocketRemoteClientConnection( + client.id, + new URL(client.url), + this.channel, + ) + }), + ) + } + + private async removeRuntimeClients(): Promise { + await this.store.deleteMany(Array.from(this.runtimeClients.keys())) + this.runtimeClients.clear() + await this.flushDatabaseToMemory() + this.notifyOthersAboutDatabaseUpdate() + } + + /** + * All active WebSocket client connections. + */ + get clients(): Set { + return this.allClients + } + + /** + * Notify other runtimes about the database update + * using the shared `BroadcastChannel` instance. + */ + private notifyOthersAboutDatabaseUpdate(): void { + this.channel.postMessage({ type: 'db:update' }) + } + + private async addClient( + client: WebSocketClientConnectionProtocol, + ): Promise { + await this.store.add(client) + // Sync the in-memory clients in this runtime with the + // updated database. This pulls in all the stored clients. + await this.flushDatabaseToMemory() + this.notifyOthersAboutDatabaseUpdate() + } + + /** + * Adds the given `WebSocket` client connection to the set + * of all connections. The given connection is always the complete + * connection object because `addConnection()` is called only + * for the opened connections in the same runtime. + */ + public async addConnection( + client: WebSocketClientConnectionProtocol, + ): Promise { + // Store this client in the map of clients created in this runtime. + // This way, the manager can distinguish between this runtime clients + // and extraneous runtime clients when synchronizing clients storage. + this.runtimeClients.set(client.id, client) + + // Add the new client to the storage. + await this.addClient(client) + + // Handle the incoming BroadcastChannel messages from other runtimes + // that attempt to control this runtime (via a remote connection wrapper). + // E.g. another runtime calling `client.send()` for the client in this runtime. + const handleExtraneousMessage = ( + message: MessageEvent, + ) => { + const { type, payload } = message.data + + // Ignore broadcasted messages for other clients. + if ( + typeof payload === 'object' && + 'clientId' in payload && + payload.clientId !== client.id + ) { + return + } + + switch (type) { + case 'extraneous:send': { + client.send(payload.data) + break + } + + case 'extraneous:close': { + client.close(payload.code, payload.reason) + break + } + } + } + + const abortController = new AbortController() + + this.channel.addEventListener('message', handleExtraneousMessage, { + signal: abortController.signal, + }) + + // Once closed, this connection cannot be operated on. + // This must include the extraneous runtimes as well. + client.addEventListener('close', () => abortController.abort(), { + once: true, + }) + } +} + +/** + * A wrapper class to operate with WebSocket client connections + * from other runtimes. This class maintains 1-1 public API + * compatibility to the `WebSocketClientConnection` but relies + * on the given `BroadcastChannel` to communicate instructions + * with the client connections from other runtimes. + */ +export class WebSocketRemoteClientConnection + implements WebSocketClientConnectionProtocol +{ + constructor( + public readonly id: string, + public readonly url: URL, + private channel: BroadcastChannel, + ) {} + + send(data: WebSocketData): void { + this.channel.postMessage({ + type: 'extraneous:send', + payload: { + clientId: this.id, + data, + }, + } as WebSocketBroadcastChannelMessage) + } + + close(code?: number | undefined, reason?: string | undefined): void { + this.channel.postMessage({ + type: 'extraneous:close', + payload: { + clientId: this.id, + code, + reason, + }, + } as WebSocketBroadcastChannelMessage) + } + + addEventListener( + _type: EventType, + _listener: ( + this: WebSocket, + event: WebSocketClientEventMap[EventType], + ) => void, + _options?: AddEventListenerOptions | boolean, + ): void { + throw new Error( + 'WebSocketRemoteClientConnection.addEventListener is not supported', + ) + } + + removeEventListener( + _event: EventType, + _listener: ( + this: WebSocket, + event: WebSocketClientEventMap[EventType], + ) => void, + _options?: EventListenerOptions | boolean, + ): void { + throw new Error( + 'WebSocketRemoteClientConnection.removeEventListener is not supported', + ) + } +} diff --git a/node_modules/msw/src/core/ws/WebSocketClientStore.ts b/node_modules/msw/src/core/ws/WebSocketClientStore.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e4c302b6c748295802bbdda1f2ef220f1878111 --- /dev/null +++ b/node_modules/msw/src/core/ws/WebSocketClientStore.ts @@ -0,0 +1,14 @@ +import type { WebSocketClientConnectionProtocol } from '@mswjs/interceptors/WebSocket' + +export interface SerializedWebSocketClient { + id: string + url: string +} + +export abstract class WebSocketClientStore { + public abstract add(client: WebSocketClientConnectionProtocol): Promise + + public abstract getAll(): Promise> + + public abstract deleteMany(clientIds: Array): Promise +} diff --git a/node_modules/msw/src/core/ws/WebSocketIndexedDBClientStore.ts b/node_modules/msw/src/core/ws/WebSocketIndexedDBClientStore.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f09ebbbf9050aec3767b6c73dca2c4fcbe5c8b1 --- /dev/null +++ b/node_modules/msw/src/core/ws/WebSocketIndexedDBClientStore.ts @@ -0,0 +1,138 @@ +import { DeferredPromise } from '@open-draft/deferred-promise' +import type { WebSocketClientConnectionProtocol } from '@mswjs/interceptors/WebSocket' +import type { WebSocketClientStore } from './WebSocketClientStore' +import { type SerializedWebSocketClient } from './WebSocketClientStore' + +const DB_NAME = 'msw-websocket-clients' +const DB_STORE_NAME = 'clients' + +export class WebSocketIndexedDBClientStore implements WebSocketClientStore { + private db: Promise + + constructor() { + this.db = this.createDatabase() + } + + public async add(client: WebSocketClientConnectionProtocol): Promise { + const promise = new DeferredPromise() + const store = await this.getStore() + + /** + * @note Use `.put()` instead of `.add()` to allow setting clients + * that already exist in the database. This can happen if a single page + * has multiple event handlers. Each handler will receive the "connection" + * event in parallel, and try to set that WebSocket client in the database. + */ + const request = store.put({ + id: client.id, + url: client.url.href, + } satisfies SerializedWebSocketClient) + + request.onsuccess = () => { + promise.resolve() + } + request.onerror = () => { + console.error(request.error) + promise.reject( + new Error( + `Failed to add WebSocket client "${client.id}". There is likely an additional output above.`, + ), + ) + } + + return promise + } + + public async getAll(): Promise> { + const promise = new DeferredPromise>() + const store = await this.getStore() + const request = store.getAll() as IDBRequest< + Array + > + + request.onsuccess = () => { + promise.resolve(request.result) + } + request.onerror = () => { + console.error(request.error) + promise.reject( + new Error( + `Failed to get all WebSocket clients. There is likely an additional output above.`, + ), + ) + } + + return promise + } + + public async deleteMany(clientIds: Array): Promise { + const promise = new DeferredPromise() + const store = await this.getStore() + + for (const clientId of clientIds) { + store.delete(clientId) + } + + store.transaction.oncomplete = () => { + promise.resolve() + } + store.transaction.onerror = () => { + console.error(store.transaction.error) + promise.reject( + new Error( + `Failed to delete WebSocket clients [${clientIds.join(', ')}]. There is likely an additional output above.`, + ), + ) + } + + return promise + } + + private async createDatabase(): Promise { + const promise = new DeferredPromise() + const request = indexedDB.open(DB_NAME, 1) + + request.onsuccess = ({ currentTarget }) => { + const db = Reflect.get(currentTarget!, 'result') as IDBDatabase + + if (db.objectStoreNames.contains(DB_STORE_NAME)) { + return promise.resolve(db) + } + } + + request.onupgradeneeded = async ({ currentTarget }) => { + const db = Reflect.get(currentTarget!, 'result') as IDBDatabase + if (db.objectStoreNames.contains(DB_STORE_NAME)) { + return + } + + const store = db.createObjectStore(DB_STORE_NAME, { keyPath: 'id' }) + store.transaction.oncomplete = () => { + promise.resolve(db) + } + store.transaction.onerror = () => { + console.error(store.transaction.error) + promise.reject( + new Error( + 'Failed to create WebSocket client store. There is likely an additional output above.', + ), + ) + } + } + request.onerror = () => { + console.error(request.error) + promise.reject( + new Error( + 'Failed to open an IndexedDB database. There is likely an additional output above.', + ), + ) + } + + return promise + } + + private async getStore(): Promise { + const db = await this.db + return db.transaction(DB_STORE_NAME, 'readwrite').objectStore(DB_STORE_NAME) + } +} diff --git a/node_modules/msw/src/core/ws/WebSocketMemoryClientStore.ts b/node_modules/msw/src/core/ws/WebSocketMemoryClientStore.ts new file mode 100644 index 0000000000000000000000000000000000000000..722fc790f6b1eebf65fa4f900acbc8e96e7b53d2 --- /dev/null +++ b/node_modules/msw/src/core/ws/WebSocketMemoryClientStore.ts @@ -0,0 +1,25 @@ +import type { WebSocketClientConnectionProtocol } from '@mswjs/interceptors/WebSocket' +import type { WebSocketClientStore } from './WebSocketClientStore' +import { type SerializedWebSocketClient } from './WebSocketClientStore' + +export class WebSocketMemoryClientStore implements WebSocketClientStore { + private store: Map + + constructor() { + this.store = new Map() + } + + public async add(client: WebSocketClientConnectionProtocol): Promise { + this.store.set(client.id, { id: client.id, url: client.url.href }) + } + + public getAll(): Promise> { + return Promise.resolve(Array.from(this.store.values())) + } + + public async deleteMany(clientIds: Array): Promise { + for (const clientId of clientIds) { + this.store.delete(clientId) + } + } +} diff --git a/node_modules/msw/src/core/ws/handleWebSocketEvent.ts b/node_modules/msw/src/core/ws/handleWebSocketEvent.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b4e62b1543a86ee716fd9dbe49e153cd91de616 --- /dev/null +++ b/node_modules/msw/src/core/ws/handleWebSocketEvent.ts @@ -0,0 +1,68 @@ +import type { WebSocketConnectionData } from '@mswjs/interceptors/WebSocket' +import type { RequestHandler } from '../handlers/RequestHandler' +import type { WebSocketHandler } from '../handlers/WebSocketHandler' +import { webSocketInterceptor } from './webSocketInterceptor' +import { + onUnhandledRequest, + type UnhandledRequestStrategy, +} from '../utils/request/onUnhandledRequest' +import { isHandlerKind } from '../utils/internal/isHandlerKind' + +interface HandleWebSocketEventOptions { + getUnhandledRequestStrategy: () => UnhandledRequestStrategy + getHandlers: () => Array + onMockedConnection: (connection: WebSocketConnectionData) => void + onPassthroughConnection: (onnection: WebSocketConnectionData) => void +} + +export function handleWebSocketEvent(options: HandleWebSocketEventOptions) { + webSocketInterceptor.on('connection', async (connection) => { + /** + * @todo @fixme Reference the handlers controller here and use `.getHandlersByKind`. + * That one relies on the pre-grouped handlers map and will be more performant. + */ + const handlers = options.getHandlers().filter(isHandlerKind('websocket')) + + // Ignore this connection if the user hasn't defined any handlers. + if (handlers.length > 0) { + options?.onMockedConnection(connection) + + await Promise.all( + handlers.map((handler) => { + // Iterate over the handlers and forward the connection + // event to WebSocket event handlers. This is equivalent + // to dispatching that event onto multiple listeners. + return handler.run(connection) + }), + ) + + return + } + + // Construct a request representing this WebSocket connection. + const request = new Request(connection.client.url, { + headers: { + upgrade: 'websocket', + connection: 'upgrade', + }, + }) + await onUnhandledRequest( + request, + options.getUnhandledRequestStrategy(), + ).catch((error) => { + const errorEvent = new Event('error') + Object.defineProperty(errorEvent, 'cause', { + enumerable: true, + configurable: false, + value: error, + }) + connection.client.socket.dispatchEvent(errorEvent) + }) + + options?.onPassthroughConnection(connection) + + // If none of the "ws" handlers matched, + // establish the WebSocket connection as-is. + connection.server.connect() + }) +} diff --git a/node_modules/msw/src/core/ws/utils/attachWebSocketLogger.ts b/node_modules/msw/src/core/ws/utils/attachWebSocketLogger.ts new file mode 100644 index 0000000000000000000000000000000000000000..0afba329841a0b740d703abf7432d6348d77319e --- /dev/null +++ b/node_modules/msw/src/core/ws/utils/attachWebSocketLogger.ts @@ -0,0 +1,277 @@ +import type { + WebSocketClientConnection, + WebSocketConnectionData, + WebSocketData, +} from '@mswjs/interceptors/WebSocket' +import { devUtils } from '../../utils/internal/devUtils' +import { getTimestamp } from '../../utils/logging/getTimestamp' +import { toPublicUrl } from '../../utils/request/toPublicUrl' +import { getMessageLength } from './getMessageLength' +import { getPublicData } from './getPublicData' + +export const colors = { + system: '#3b82f6', + outgoing: '#22c55e', + incoming: '#ef4444', + mocked: '#ff6a33', +} + +export function attachWebSocketLogger( + connection: WebSocketConnectionData, +): () => void { + const { client, server } = connection + const controller = new AbortController() + + logConnectionOpen(client) + + // Log the events sent from the WebSocket client. + // WebSocket client connection object is written from the + // server's perspective so these message events are outgoing. + /** + * @todo Provide the reference to the exact event handler + * that called this `client.send()`. + */ + client.addEventListener( + 'message', + (event) => { + logOutgoingClientMessage(event) + }, + { signal: controller.signal }, + ) + + client.addEventListener( + 'close', + (event) => { + logConnectionClose(event) + }, + { signal: controller.signal }, + ) + + // Log client errors (connection closures due to errors). + client.socket.addEventListener( + 'error', + (event) => { + logClientError(event) + }, + { signal: controller.signal }, + ) + + const { send: originalClientSend } = client + client.send = new Proxy(client.send, { + apply(target, thisArg, args) { + const [data] = args + const messageEvent = new MessageEvent('message', { data }) + Object.defineProperties(messageEvent, { + currentTarget: { + enumerable: true, + writable: false, + value: client.socket, + }, + target: { + enumerable: true, + writable: false, + value: client.socket, + }, + }) + + queueMicrotask(() => { + logIncomingMockedClientMessage(messageEvent) + }) + + return Reflect.apply(target, thisArg, args) + }, + }) + + server.addEventListener( + 'open', + () => { + server.addEventListener('message', (event) => { + logIncomingServerMessage(event) + }) + }, + { + once: true, + signal: controller.signal, + }, + ) + + // Log outgoing client events initiated by the event handler. + // The actual client never sent these but the handler did. + const { send: originalServerSend } = server + server.send = new Proxy(server.send, { + apply(target, thisArg, args) { + const [data] = args + const messageEvent = new MessageEvent('message', { data }) + Object.defineProperties(messageEvent, { + currentTarget: { + enumerable: true, + writable: false, + value: server.socket, + }, + target: { + enumerable: true, + writable: false, + value: server.socket, + }, + }) + + logOutgoingMockedClientMessage(messageEvent) + + return Reflect.apply(target, thisArg, args) + }, + }) + + // Undo method proxies. + controller.signal.addEventListener( + 'abort', + () => { + client.send = originalClientSend + server.send = originalServerSend + }, + { once: true }, + ) + + return () => { + controller.abort() + } +} + +/** + * Prints the WebSocket connection. + * This is meant to be logged by every WebSocket handler + * that intercepted this connection. This helps you see + * what handlers observe this connection. + */ +export function logConnectionOpen(client: WebSocketClientConnection) { + const publicUrl = toPublicUrl(client.url) + + console.groupCollapsed( + devUtils.formatMessage(`${getTimestamp()} %c▶%c ${publicUrl}`), + `color:${colors.system}`, + 'color:inherit', + ) + // eslint-disable-next-line no-console + console.log('Client:', client.socket) + console.groupEnd() +} + +function logConnectionClose(event: CloseEvent) { + const target = event.target as WebSocket + const publicUrl = toPublicUrl(target.url) + + console.groupCollapsed( + devUtils.formatMessage( + `${getTimestamp({ milliseconds: true })} %c■%c ${publicUrl}`, + ), + `color:${colors.system}`, + 'color:inherit', + ) + // eslint-disable-next-line no-console + console.log(event) + console.groupEnd() +} + +function logClientError(event: Event) { + const socket = event.target as WebSocket + const publicUrl = toPublicUrl(socket.url) + + console.groupCollapsed( + devUtils.formatMessage( + `${getTimestamp({ milliseconds: true })} %c\u00D7%c ${publicUrl}`, + ), + `color:${colors.system}`, + 'color:inherit', + ) + // eslint-disable-next-line no-console + console.log(event) + console.groupEnd() +} + +/** + * Prints the outgoing client message. + */ +async function logOutgoingClientMessage(event: MessageEvent) { + const byteLength = getMessageLength(event.data) + const publicData = await getPublicData(event.data) + const arrow = event.defaultPrevented ? '⇡' : '⬆' + + console.groupCollapsed( + devUtils.formatMessage( + `${getTimestamp({ milliseconds: true })} %c${arrow}%c ${publicData} %c${byteLength}%c`, + ), + `color:${colors.outgoing}`, + 'color:inherit', + 'color:gray;font-weight:normal', + 'color:inherit;font-weight:inherit', + ) + // eslint-disable-next-line no-console + console.log(event) + console.groupEnd() +} + +/** + * Prints the outgoing client message initiated + * by `server.send()` in the event handler. + */ +async function logOutgoingMockedClientMessage( + event: MessageEvent, +) { + const byteLength = getMessageLength(event.data) + const publicData = await getPublicData(event.data) + + console.groupCollapsed( + devUtils.formatMessage( + `${getTimestamp({ milliseconds: true })} %c⬆%c ${publicData} %c${byteLength}%c`, + ), + `color:${colors.mocked}`, + 'color:inherit', + 'color:gray;font-weight:normal', + 'color:inherit;font-weight:inherit', + ) + // eslint-disable-next-line no-console + console.log(event) + console.groupEnd() +} + +/** + * Prints the outgoing client message initiated + * by `client.send()` in the event handler. + */ +async function logIncomingMockedClientMessage( + event: MessageEvent, +) { + const byteLength = getMessageLength(event.data) + const publicData = await getPublicData(event.data) + + console.groupCollapsed( + devUtils.formatMessage( + `${getTimestamp({ milliseconds: true })} %c⬇%c ${publicData} %c${byteLength}%c`, + ), + `color:${colors.mocked}`, + 'color:inherit', + 'color:gray;font-weight:normal', + 'color:inherit;font-weight:inherit', + ) + // eslint-disable-next-line no-console + console.log(event) + console.groupEnd() +} + +async function logIncomingServerMessage(event: MessageEvent) { + const byteLength = getMessageLength(event.data) + const publicData = await getPublicData(event.data) + const arrow = event.defaultPrevented ? '⇣' : '⬇' + + console.groupCollapsed( + devUtils.formatMessage( + `${getTimestamp({ milliseconds: true })} %c${arrow}%c ${publicData} %c${byteLength}%c`, + ), + `color:${colors.incoming}`, + 'color:inherit', + 'color:gray;font-weight:normal', + 'color:inherit;font-weight:inherit', + ) + // eslint-disable-next-line no-console + console.log(event) + console.groupEnd() +} diff --git a/node_modules/msw/src/core/ws/utils/getMessageLength.test.ts b/node_modules/msw/src/core/ws/utils/getMessageLength.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..af45718ee15e2cecbbc1e65513932b09409b2eec --- /dev/null +++ b/node_modules/msw/src/core/ws/utils/getMessageLength.test.ts @@ -0,0 +1,16 @@ +import { getMessageLength } from './getMessageLength' + +it('returns the length of the string', () => { + expect(getMessageLength('')).toBe(0) + expect(getMessageLength('hello')).toBe(5) +}) + +it('returns the size of the Blob', () => { + expect(getMessageLength(new Blob())).toBe(0) + expect(getMessageLength(new Blob(['hello']))).toBe(5) +}) + +it('returns the byte length of ArrayBuffer', () => { + expect(getMessageLength(new ArrayBuffer(0))).toBe(0) + expect(getMessageLength(new ArrayBuffer(5))).toBe(5) +}) diff --git a/node_modules/msw/src/core/ws/utils/getMessageLength.ts b/node_modules/msw/src/core/ws/utils/getMessageLength.ts new file mode 100644 index 0000000000000000000000000000000000000000..931d497b91f6c22d169e8f7f42f351fb33f703ff --- /dev/null +++ b/node_modules/msw/src/core/ws/utils/getMessageLength.ts @@ -0,0 +1,20 @@ +import type { WebSocketData } from '@mswjs/interceptors/WebSocket' +import { isObject } from '../../utils/internal/isObject' + +/** + * Returns the byte length of the given WebSocket message. + * @example + * getMessageLength('hello') // 5 + * getMessageLength(new Blob(['hello'])) // 5 + */ +export function getMessageLength(data: WebSocketData): number { + if (data instanceof Blob) { + return data.size + } + + if (isObject(data) && 'byteLength' in data) { + return data.byteLength + } + + return new Blob([data as any]).size +} diff --git a/node_modules/msw/src/core/ws/utils/getPublicData.test.ts b/node_modules/msw/src/core/ws/utils/getPublicData.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2820301f7f16351c90b9705a6d1df431a6f3fe41 --- /dev/null +++ b/node_modules/msw/src/core/ws/utils/getPublicData.test.ts @@ -0,0 +1,38 @@ +import { getPublicData } from './getPublicData' + +it('returns a short string as-is', async () => { + expect(await getPublicData('')).toBe('') + expect(await getPublicData('hello')).toBe('hello') +}) + +it('returns a truncated long string', async () => { + expect(await getPublicData('this is a very long string')).toBe( + 'this is a very long stri…', + ) +}) + +it('returns a short Blob text as-is', async () => { + expect(await getPublicData(new Blob(['']))).toBe('Blob()') + expect(await getPublicData(new Blob(['hello']))).toBe('Blob(hello)') +}) + +it('returns a truncated long Blob text', async () => { + expect(await getPublicData(new Blob(['this is a very long string']))).toBe( + 'Blob(this is a very long stri…)', + ) +}) + +it('returns a short ArrayBuffer text as-is', async () => { + expect(await getPublicData(new TextEncoder().encode(''))).toBe( + 'ArrayBuffer()', + ) + expect(await getPublicData(new TextEncoder().encode('hello'))).toBe( + 'ArrayBuffer(hello)', + ) +}) + +it('returns a truncated ArrayBuffer text', async () => { + expect( + await getPublicData(new TextEncoder().encode('this is a very long string')), + ).toBe('ArrayBuffer(this is a very long stri…)') +}) diff --git a/node_modules/msw/src/core/ws/utils/getPublicData.ts b/node_modules/msw/src/core/ws/utils/getPublicData.ts new file mode 100644 index 0000000000000000000000000000000000000000..6f4f97a964ca1ad2c006710c6cbb92a3cf27a9e7 --- /dev/null +++ b/node_modules/msw/src/core/ws/utils/getPublicData.ts @@ -0,0 +1,18 @@ +import type { WebSocketData } from '@mswjs/interceptors/WebSocket' +import { isObject } from '../../utils/internal/isObject' +import { truncateMessage } from './truncateMessage' + +export async function getPublicData(data: WebSocketData): Promise { + if (data instanceof Blob) { + const text = await data.text() + return `Blob(${truncateMessage(text)})` + } + + // Handle all ArrayBuffer-like objects. + if (isObject(data)) { + const text = new TextDecoder().decode(data as ArrayBuffer) + return `ArrayBuffer(${truncateMessage(text)})` + } + + return truncateMessage(data) +} diff --git a/node_modules/msw/src/core/ws/utils/truncateMessage.test.ts b/node_modules/msw/src/core/ws/utils/truncateMessage.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e247a0e3e6772e3df9ab8e210ea38a8d0777f83 --- /dev/null +++ b/node_modules/msw/src/core/ws/utils/truncateMessage.test.ts @@ -0,0 +1,12 @@ +import { truncateMessage } from './truncateMessage' + +it('returns a short string as-is', () => { + expect(truncateMessage('')).toBe('') + expect(truncateMessage('hello')).toBe('hello') +}) + +it('truncates a long string', () => { + expect(truncateMessage('this is a very long string')).toBe( + 'this is a very long stri…', + ) +}) diff --git a/node_modules/msw/src/core/ws/utils/truncateMessage.ts b/node_modules/msw/src/core/ws/utils/truncateMessage.ts new file mode 100644 index 0000000000000000000000000000000000000000..eae145e91abce69397bfdbc108490407406ce319 --- /dev/null +++ b/node_modules/msw/src/core/ws/utils/truncateMessage.ts @@ -0,0 +1,9 @@ +const MAX_LENGTH = 24 + +export function truncateMessage(message: string): string { + if (message.length <= MAX_LENGTH) { + return message + } + + return `${message.slice(0, MAX_LENGTH)}…` +} diff --git a/node_modules/msw/src/core/ws/webSocketInterceptor.ts b/node_modules/msw/src/core/ws/webSocketInterceptor.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a8b21f2d58fa70d1fa3bee643a6994fda1f3a16 --- /dev/null +++ b/node_modules/msw/src/core/ws/webSocketInterceptor.ts @@ -0,0 +1,3 @@ +import { WebSocketInterceptor } from '@mswjs/interceptors/WebSocket' + +export const webSocketInterceptor = new WebSocketInterceptor() diff --git a/node_modules/msw/src/iife/index.ts b/node_modules/msw/src/iife/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..829e2c97968628f12be05344e64c301fa2aeea5e --- /dev/null +++ b/node_modules/msw/src/iife/index.ts @@ -0,0 +1,2 @@ +export * from '#core' +export * from '../browser' diff --git a/node_modules/msw/src/mockServiceWorker.js b/node_modules/msw/src/mockServiceWorker.js new file mode 100644 index 0000000000000000000000000000000000000000..d02b80689f69c49ce2568e50a600c53f73609f61 --- /dev/null +++ b/node_modules/msw/src/mockServiceWorker.js @@ -0,0 +1,349 @@ +/* eslint-disable */ +/* tslint:disable */ + +/** + * Mock Service Worker. + * @see https://github.com/mswjs/msw + * - Please do NOT modify this file. + */ + +const PACKAGE_VERSION = '' +const INTEGRITY_CHECKSUM = '' +const IS_MOCKED_RESPONSE = Symbol('isMockedResponse') +const activeClientIds = new Set() + +addEventListener('install', function () { + self.skipWaiting() +}) + +addEventListener('activate', function (event) { + event.waitUntil(self.clients.claim()) +}) + +addEventListener('message', async function (event) { + const clientId = Reflect.get(event.source || {}, 'id') + + if (!clientId || !self.clients) { + return + } + + const client = await self.clients.get(clientId) + + if (!client) { + return + } + + const allClients = await self.clients.matchAll({ + type: 'window', + }) + + switch (event.data) { + case 'KEEPALIVE_REQUEST': { + sendToClient(client, { + type: 'KEEPALIVE_RESPONSE', + }) + break + } + + case 'INTEGRITY_CHECK_REQUEST': { + sendToClient(client, { + type: 'INTEGRITY_CHECK_RESPONSE', + payload: { + packageVersion: PACKAGE_VERSION, + checksum: INTEGRITY_CHECKSUM, + }, + }) + break + } + + case 'MOCK_ACTIVATE': { + activeClientIds.add(clientId) + + sendToClient(client, { + type: 'MOCKING_ENABLED', + payload: { + client: { + id: client.id, + frameType: client.frameType, + }, + }, + }) + break + } + + case 'CLIENT_CLOSED': { + activeClientIds.delete(clientId) + + const remainingClients = allClients.filter((client) => { + return client.id !== clientId + }) + + // Unregister itself when there are no more clients + if (remainingClients.length === 0) { + self.registration.unregister() + } + + break + } + } +}) + +addEventListener('fetch', function (event) { + const requestInterceptedAt = Date.now() + + // Bypass navigation requests. + if (event.request.mode === 'navigate') { + return + } + + // Opening the DevTools triggers the "only-if-cached" request + // that cannot be handled by the worker. Bypass such requests. + if ( + event.request.cache === 'only-if-cached' && + event.request.mode !== 'same-origin' + ) { + return + } + + // Bypass all requests when there are no active clients. + // Prevents the self-unregistered worked from handling requests + // after it's been terminated (still remains active until the next reload). + if (activeClientIds.size === 0) { + return + } + + const requestId = crypto.randomUUID() + event.respondWith(handleRequest(event, requestId, requestInterceptedAt)) +}) + +/** + * @param {FetchEvent} event + * @param {string} requestId + * @param {number} requestInterceptedAt + */ +async function handleRequest(event, requestId, requestInterceptedAt) { + const client = await resolveMainClient(event) + const requestCloneForEvents = event.request.clone() + const response = await getResponse( + event, + client, + requestId, + requestInterceptedAt, + ) + + // Send back the response clone for the "response:*" life-cycle events. + // Ensure MSW is active and ready to handle the message, otherwise + // this message will pend indefinitely. + if (client && activeClientIds.has(client.id)) { + const serializedRequest = await serializeRequest(requestCloneForEvents) + + // Clone the response so both the client and the library could consume it. + const responseClone = response.clone() + + sendToClient( + client, + { + type: 'RESPONSE', + payload: { + isMockedResponse: IS_MOCKED_RESPONSE in response, + request: { + id: requestId, + ...serializedRequest, + }, + response: { + type: responseClone.type, + status: responseClone.status, + statusText: responseClone.statusText, + headers: Object.fromEntries(responseClone.headers.entries()), + body: responseClone.body, + }, + }, + }, + responseClone.body ? [serializedRequest.body, responseClone.body] : [], + ) + } + + return response +} + +/** + * Resolve the main client for the given event. + * Client that issues a request doesn't necessarily equal the client + * that registered the worker. It's with the latter the worker should + * communicate with during the response resolving phase. + * @param {FetchEvent} event + * @returns {Promise} + */ +async function resolveMainClient(event) { + const client = await self.clients.get(event.clientId) + + if (activeClientIds.has(event.clientId)) { + return client + } + + if (client?.frameType === 'top-level') { + return client + } + + const allClients = await self.clients.matchAll({ + type: 'window', + }) + + return allClients + .filter((client) => { + // Get only those clients that are currently visible. + return client.visibilityState === 'visible' + }) + .find((client) => { + // Find the client ID that's recorded in the + // set of clients that have registered the worker. + return activeClientIds.has(client.id) + }) +} + +/** + * @param {FetchEvent} event + * @param {Client | undefined} client + * @param {string} requestId + * @param {number} requestInterceptedAt + * @returns {Promise} + */ +async function getResponse(event, client, requestId, requestInterceptedAt) { + // Clone the request because it might've been already used + // (i.e. its body has been read and sent to the client). + const requestClone = event.request.clone() + + function passthrough() { + // Cast the request headers to a new Headers instance + // so the headers can be manipulated with. + const headers = new Headers(requestClone.headers) + + // Remove the "accept" header value that marked this request as passthrough. + // This prevents request alteration and also keeps it compliant with the + // user-defined CORS policies. + const acceptHeader = headers.get('accept') + if (acceptHeader) { + const values = acceptHeader.split(',').map((value) => value.trim()) + const filteredValues = values.filter( + (value) => value !== 'msw/passthrough', + ) + + if (filteredValues.length > 0) { + headers.set('accept', filteredValues.join(', ')) + } else { + headers.delete('accept') + } + } + + return fetch(requestClone, { headers }) + } + + // Bypass mocking when the client is not active. + if (!client) { + return passthrough() + } + + // Bypass initial page load requests (i.e. static assets). + // The absence of the immediate/parent client in the map of the active clients + // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet + // and is not ready to handle requests. + if (!activeClientIds.has(client.id)) { + return passthrough() + } + + // Notify the client that a request has been intercepted. + const serializedRequest = await serializeRequest(event.request) + const clientMessage = await sendToClient( + client, + { + type: 'REQUEST', + payload: { + id: requestId, + interceptedAt: requestInterceptedAt, + ...serializedRequest, + }, + }, + [serializedRequest.body], + ) + + switch (clientMessage.type) { + case 'MOCK_RESPONSE': { + return respondWithMock(clientMessage.data) + } + + case 'PASSTHROUGH': { + return passthrough() + } + } + + return passthrough() +} + +/** + * @param {Client} client + * @param {any} message + * @param {Array} transferrables + * @returns {Promise} + */ +function sendToClient(client, message, transferrables = []) { + return new Promise((resolve, reject) => { + const channel = new MessageChannel() + + channel.port1.onmessage = (event) => { + if (event.data && event.data.error) { + return reject(event.data.error) + } + + resolve(event.data) + } + + client.postMessage(message, [ + channel.port2, + ...transferrables.filter(Boolean), + ]) + }) +} + +/** + * @param {Response} response + * @returns {Response} + */ +function respondWithMock(response) { + // Setting response status code to 0 is a no-op. + // However, when responding with a "Response.error()", the produced Response + // instance will have status code set to 0. Since it's not possible to create + // a Response instance with status code 0, handle that use-case separately. + if (response.status === 0) { + return Response.error() + } + + const mockedResponse = new Response(response.body, response) + + Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, { + value: true, + enumerable: true, + }) + + return mockedResponse +} + +/** + * @param {Request} request + */ +async function serializeRequest(request) { + return { + url: request.url, + mode: request.mode, + method: request.method, + headers: Object.fromEntries(request.headers.entries()), + cache: request.cache, + credentials: request.credentials, + destination: request.destination, + integrity: request.integrity, + redirect: request.redirect, + referrer: request.referrer, + referrerPolicy: request.referrerPolicy, + body: await request.arrayBuffer(), + keepalive: request.keepalive, + } +} diff --git a/node_modules/msw/src/native/index.ts b/node_modules/msw/src/native/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..376bbb8c7a1ee0c3501443de99ff04dc3e340a6c --- /dev/null +++ b/node_modules/msw/src/native/index.ts @@ -0,0 +1,44 @@ +import type { Interceptor } from '@mswjs/interceptors' +import { FetchInterceptor } from '@mswjs/interceptors/fetch' +import { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest' +import type { AnyHandler } from '#core/experimental/handlers-controller' +import { + defineNetwork, + type DefineNetworkOptions, +} from '#core/experimental/define-network' +import { InterceptorSource } from '#core/experimental/sources/interceptor-source' +import { type SetupServerCommon } from '../node/glossary' +import { defineSetupServerApi } from '../node/setup-server-common' + +const defaultInterceptors: Array> = [ + new FetchInterceptor(), + new XMLHttpRequestInterceptor(), +] + +export const defaultNetworkOptions: DefineNetworkOptions<[InterceptorSource]> = + { + sources: [ + new InterceptorSource({ + interceptors: defaultInterceptors, + }), + ], + onUnhandledFrame: 'warn', + context: { + quiet: true, + }, + } + +/** + * Sets up a requests interception in React Native with the given request handlers. + * @param {Array} handlers List of request handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-server `setupServer()` API reference} + */ +export function setupServer(...handlers: Array): SetupServerCommon { + const network = defineNetwork({ + ...defaultNetworkOptions, + handlers, + }) + + return defineSetupServerApi(network) +} diff --git a/node_modules/msw/src/node/async-handlers-controller.test.ts b/node_modules/msw/src/node/async-handlers-controller.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..47ae5435235bfe1809e39368671cfb21c785a0e3 --- /dev/null +++ b/node_modules/msw/src/node/async-handlers-controller.test.ts @@ -0,0 +1,50 @@ +import { http } from '../core/http' +import { AsyncHandlersController } from './async-handlers-controller' + +it('respects initial handlers in the boundary', () => { + { + const controller = new AsyncHandlersController([]) + controller.boundary(() => { + expect(controller.currentHandlers()).toEqual([]) + })() + } + + { + const initialHandlers = [http.get('/', () => {})] + const controller = new AsyncHandlersController(initialHandlers) + controller.boundary(() => { + expect(controller.currentHandlers()).toEqual(initialHandlers) + })() + } +}) + +it('provides boundary-specific overrides', () => { + const initialHandlers = [http.get('/one', () => {})] + const controller = new AsyncHandlersController(initialHandlers) + + controller.boundary(() => { + const runtimeHandlers = [http.get('/two', () => {})] + controller.use(runtimeHandlers) + expect(controller.currentHandlers()).toEqual([ + ...runtimeHandlers, + ...initialHandlers, + ]) + })() + + expect(controller.currentHandlers()).toEqual(initialHandlers) +}) + +it('resets the handlers in the boundary', () => { + const initialHandlers = [http.get('/one', () => {})] + const controller = new AsyncHandlersController(initialHandlers) + + controller.boundary(() => { + const runtimeHandlers = [http.get('/two', () => {})] + controller.use(runtimeHandlers) + controller.reset([]) + + expect(controller.currentHandlers()).toEqual(initialHandlers) + })() + + expect(controller.currentHandlers()).toEqual(initialHandlers) +}) diff --git a/node_modules/msw/src/node/async-handlers-controller.ts b/node_modules/msw/src/node/async-handlers-controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..0376ff9ca98f68b89bc6732301579593aaea6099 --- /dev/null +++ b/node_modules/msw/src/node/async-handlers-controller.ts @@ -0,0 +1,69 @@ +import { AsyncLocalStorage } from 'node:async_hooks' +import { + HandlersController, + type AnyHandler, + type HandlersMap, + type HandlersControllerState, +} from '#core/experimental/handlers-controller' + +export interface AsyncHandlersControllerContext { + initialHandlers: HandlersMap + handlers: HandlersMap +} + +export class AsyncHandlersController extends HandlersController { + #asyncContext: AsyncLocalStorage + #fallbackContext: AsyncHandlersControllerContext + + constructor(initialHandlers: Array) { + super() + + const initialState = this.getInitialState(initialHandlers) + + this.#asyncContext = new AsyncLocalStorage() + this.#fallbackContext = { + initialHandlers: initialState.initialHandlers, + handlers: initialState.handlers, + } + } + + protected getState() { + const { initialHandlers, handlers } = this.#getContext() + + return { + initialHandlers, + handlers, + } + } + + protected setState(nextState: HandlersControllerState): void { + const context = this.#getContext() + + if (nextState.initialHandlers) { + context.initialHandlers = nextState.initialHandlers + } + + if (nextState.handlers) { + context.handlers = nextState.handlers + } + } + + public boundary, R>(callback: (...args: Args) => R) { + return (...args: Args) => { + const initialHandlers = { ...this.getState().handlers } + + return this.#asyncContext.run( + { + initialHandlers, + handlers: { ...initialHandlers }, + }, + callback, + ...args, + ) + } + } + + #getContext() { + return this.#asyncContext.getStore() || this.#fallbackContext + } +} diff --git a/node_modules/msw/src/node/glossary.ts b/node_modules/msw/src/node/glossary.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ed51e7ccf0f8e7066dcbe1935b91389f594352a --- /dev/null +++ b/node_modules/msw/src/node/glossary.ts @@ -0,0 +1,75 @@ +import type { PartialDeep } from 'type-fest' +import type { HttpNetworkFrameEventMap } from '#core/experimental/frames/http-frame' +import type { WebSocketNetworkFrameEventMap } from '#core/experimental/frames/websocket-frame' +import type { AnyHandler } from '#core/experimental/handlers-controller' +import type { LifeCycleEventEmitter, SharedOptions } from '#core/sharedOptions' + +export interface ListenOptions extends SharedOptions {} + +export interface SetupServerCommon { + /** + * Starts the request interception based on the previously provided request handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-server/listen `server.listen()` API reference} + */ + listen: (options?: PartialDeep) => void + + /** + * Stops the request interception by restoring all augmented modules. + * + * @see {@link https://mswjs.io/docs/api/setup-server/close `server.close()` API reference} + */ + close: () => void + + /** + * Prepends given request handlers to the list of existing handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-server/use `server.use()` API reference} + */ + use: (...handlers: Array) => void + + /** + * Marks all request handlers that respond using `res.once()` as unused. + * + * @see {@link https://mswjs.io/docs/api/setup-server/restore-handlers `server.restore-handlers()` API reference} + */ + restoreHandlers: () => void + + /** + * Resets request handlers to the initial list given to the `setupServer` call, or to the explicit next request handlers list, if given. + * + * @see {@link https://mswjs.io/docs/api/setup-server/reset-handlers `server.reset-handlers()` API reference} + */ + resetHandlers: (...nextHandlers: Array) => void + + /** + * Returns a readonly list of currently active request handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-server/list-handlers `server.listHandlers()` API reference} + */ + listHandlers: () => ReadonlyArray + + /** + * Life-cycle events. + * Life-cycle events allow you to subscribe to the internal library events occurring during the request/response handling. + * + * @see {@link https://mswjs.io/docs/api/life-cycle-events Life-cycle Events API reference} + */ + events: LifeCycleEventEmitter< + HttpNetworkFrameEventMap & WebSocketNetworkFrameEventMap + > +} + +export interface SetupServer extends SetupServerCommon { + /** + * Wraps the given function in a boundary. Any changes to the + * network behavior (e.g. adding runtime request handlers via + * `server.use()`) will be scoped to this boundary only. + * @param callback A function to run (e.g. a test) + * + * @see {@link https://mswjs.io/docs/api/setup-server/boundary `server.boundary()` API reference} + */ + boundary: , R>( + callback: (...args: Args) => R, + ) => (...args: Args) => R +} diff --git a/node_modules/msw/src/node/index.ts b/node_modules/msw/src/node/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..6afd80d1c2bd3aa51d0af4f7157d16a4a9c87668 --- /dev/null +++ b/node_modules/msw/src/node/index.ts @@ -0,0 +1,8 @@ +export type { SetupServer } from './glossary' +export { + setupServer, + SetupServerApi, + defaultNetworkOptions, +} from './setup-server' +export { SetupServerCommonApi } from './setup-server-common' +export { AsyncHandlersController } from './async-handlers-controller' diff --git a/node_modules/msw/src/node/setup-server-common.ts b/node_modules/msw/src/node/setup-server-common.ts new file mode 100644 index 0000000000000000000000000000000000000000..b02723d0586acaa1bb8b78755fd2f830f470e9e3 --- /dev/null +++ b/node_modules/msw/src/node/setup-server-common.ts @@ -0,0 +1,100 @@ +import type { PartialDeep } from 'type-fest' +import type { Interceptor } from '@mswjs/interceptors' +import { + NetworkReadyState, + defineNetwork, + type NetworkApi, +} from '#core/experimental/define-network' +import type { AnyHandler } from '#core/experimental/handlers-controller' +import type { HandlersController } from '#core/experimental/handlers-controller' +import { InterceptorSource } from '#core/experimental/sources/interceptor-source' +import { fromLegacyOnUnhandledRequest } from '#core/experimental/compat' +import type { ListenOptions, SetupServerCommon } from './glossary' + +/** + * Define the common `setupServer` API around the given network. + * This is used by both `msw/node` and `msw/native` to implement the same + * baseline setup methods, like `.use()`, `.resetHandlers()`, `.close()`, etc. + */ +export function defineSetupServerApi( + network: NetworkApi, +): SetupServerCommon { + return { + events: network.events, + listen(options) { + network.configure({ + onUnhandledFrame: fromLegacyOnUnhandledRequest(() => { + return options?.onUnhandledRequest || 'warn' + }), + }) + + network.enable() + }, + use: network.use.bind(network), + resetHandlers: network.resetHandlers.bind(network), + restoreHandlers: network.restoreHandlers.bind(network), + listHandlers: network.listHandlers.bind(network), + close() { + /** + * @note Ignore closing after closed for backwards compatibility. + */ + if (network.readyState === NetworkReadyState.DISABLED) { + return + } + + network.disable() + }, + } +} + +/** + * @deprecated + * Please use the `defineNetwork` API instead. + */ +export class SetupServerCommonApi implements SetupServerCommon { + protected network: NetworkApi<[InterceptorSource]> + + constructor( + interceptors: Array>, + handlers: Array | HandlersController, + ) { + this.network = defineNetwork({ + sources: [new InterceptorSource({ interceptors })], + handlers, + }) + } + + get events() { + return this.network.events + } + + public listen(options?: PartialDeep): void { + this.network.configure({ + onUnhandledFrame: fromLegacyOnUnhandledRequest(() => { + return options?.onUnhandledRequest || 'warn' + }), + }) + + this.network.enable() + } + + public use(...handlers: Array): void { + this.network.use(...handlers) + } + + public resetHandlers(...nextHandlers: Array): void { + return this.network.resetHandlers(...nextHandlers) + } + + public restoreHandlers(): void { + return this.network.restoreHandlers() + } + + public listHandlers(): ReadonlyArray { + return this.network.listHandlers() + } + + public close(): void { + this.network.disable() + } +} diff --git a/node_modules/msw/src/node/setup-server.ts b/node_modules/msw/src/node/setup-server.ts new file mode 100644 index 0000000000000000000000000000000000000000..35fe8a41f0abaf0b41e1bb5a9bb248d8a84d6c07 --- /dev/null +++ b/node_modules/msw/src/node/setup-server.ts @@ -0,0 +1,91 @@ +import type { Interceptor } from '@mswjs/interceptors' +import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest' +import { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest' +import { FetchInterceptor } from '@mswjs/interceptors/fetch' +import { WebSocketInterceptor } from '@mswjs/interceptors/WebSocket' +import { + defineNetwork, + type DefineNetworkOptions, +} from '#core/experimental/define-network' +import type { AnyHandler } from '#core/experimental/handlers-controller' +import { InterceptorSource } from '#core/experimental/sources/interceptor-source' +import type { SetupServer } from './glossary' +import { AsyncHandlersController } from './async-handlers-controller' +import { + defineSetupServerApi, + SetupServerCommonApi, +} from './setup-server-common' + +const defaultInterceptors: Array> = [ + new ClientRequestInterceptor(), + new XMLHttpRequestInterceptor(), + new FetchInterceptor(), + /** + * @fixme WebSocketInterceptor is in a browser-only export of Interceptors + * while the Interceptor class imported from the root module points to `lib/node`. + * An absolute madness to solve as it requires to duplicate the build config we have + * in MSW: shared core, CJS/ESM patching, .d.ts patching... + */ + new WebSocketInterceptor() as any, +] + +export const defaultNetworkOptions: DefineNetworkOptions<[InterceptorSource]> = + { + sources: [ + new InterceptorSource({ + interceptors: defaultInterceptors, + }), + ], + onUnhandledFrame: 'warn', + context: { + quiet: true, + }, + } + +/** + * Enables request interception in Node.js with the given request handlers. + * @see {@link https://mswjs.io/docs/api/setup-server `setupServer()` API reference} + */ +export function setupServer(...handlers: Array): SetupServer { + const handlersController = new AsyncHandlersController(handlers) + const network = defineNetwork({ + ...defaultNetworkOptions, + handlers: handlersController, + }) + + const commonApi = defineSetupServerApi(network) + + return { + ...commonApi, + boundary: handlersController.boundary.bind(handlersController), + } +} + +/** + * @deprecated + * Please use the `defineNetwork` API instead. + */ +export class SetupServerApi + extends SetupServerCommonApi + implements SetupServer +{ + #handlersController: AsyncHandlersController + + public boundary: AsyncHandlersController['boundary'] + + constructor( + handlers: Array, + interceptors: Array>, + ) { + const controller = new AsyncHandlersController(handlers) + super(interceptors, controller) + + const { sources: _, ...networkOptions } = defaultNetworkOptions + this.network.configure(networkOptions) + + this.#handlersController = controller + this.boundary = this.#handlersController.boundary.bind( + this.#handlersController, + ) + } +} diff --git a/node_modules/msw/src/package.json b/node_modules/msw/src/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/node_modules/msw/src/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/msw/src/shims/cookie.ts b/node_modules/msw/src/shims/cookie.ts new file mode 100644 index 0000000000000000000000000000000000000000..edff4bcfafecd11e4cd87fa5b5cc6f232314c5ff --- /dev/null +++ b/node_modules/msw/src/shims/cookie.ts @@ -0,0 +1,7 @@ +import * as allCookie from 'cookie' +const cookie = (allCookie as any).default || allCookie + +export const parse = cookie.parse as typeof import('cookie').parse +export const serialize = cookie.serialize as typeof import('cookie').serialize + +export default cookie diff --git a/node_modules/msw/src/shims/statuses.ts b/node_modules/msw/src/shims/statuses.ts new file mode 100644 index 0000000000000000000000000000000000000000..7bb32acb81e96dbc85d80d2627e8addf05dbbc38 --- /dev/null +++ b/node_modules/msw/src/shims/statuses.ts @@ -0,0 +1,6 @@ +import * as allStatuses from 'statuses' +const statuses = (allStatuses as any).default || allStatuses + +export const message = statuses.message as typeof import('statuses').message + +export default statuses diff --git a/node_modules/msw/src/tsconfig.core.build.json b/node_modules/msw/src/tsconfig.core.build.json new file mode 100644 index 0000000000000000000000000000000000000000..0852a1d0103e0f1139300a448710bab9123c1753 --- /dev/null +++ b/node_modules/msw/src/tsconfig.core.build.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.src.json", + "compilerOptions": { + "composite": false + } +} diff --git a/node_modules/msw/src/tsconfig.core.json b/node_modules/msw/src/tsconfig.core.json new file mode 100644 index 0000000000000000000000000000000000000000..dfc88cb0fc076e034c59ddbc90d70db5d7b51573 --- /dev/null +++ b/node_modules/msw/src/tsconfig.core.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.src.json", + "include": ["./core/**/*.ts"], + "files": [], + "compilerOptions": { + "composite": true + } +} diff --git a/node_modules/msw/src/tsconfig.node.build.json b/node_modules/msw/src/tsconfig.node.build.json new file mode 100644 index 0000000000000000000000000000000000000000..db4cc04cde5f9b859b97114d8231b4501b377862 --- /dev/null +++ b/node_modules/msw/src/tsconfig.node.build.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.node.json", + "compilerOptions": { + "composite": false + } +} diff --git a/node_modules/msw/src/tsconfig.node.json b/node_modules/msw/src/tsconfig.node.json new file mode 100644 index 0000000000000000000000000000000000000000..c71d2c27c7c333e5fadfe55e01c3149c0cd3bb68 --- /dev/null +++ b/node_modules/msw/src/tsconfig.node.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.src.json", + "include": ["./node", "./native"], + "exclude": ["**/*.test.ts"], + "references": [ + { + "path": "./tsconfig.src.json" + } + ], + "compilerOptions": { + "types": ["node"] + } +} diff --git a/node_modules/msw/src/tsconfig.src.json b/node_modules/msw/src/tsconfig.src.json new file mode 100644 index 0000000000000000000000000000000000000000..58f2e89916868b724f77c45e6e76673c16941867 --- /dev/null +++ b/node_modules/msw/src/tsconfig.src.json @@ -0,0 +1,8 @@ +{ + "extends": "../tsconfig.base.json", + "compilerOptions": { + "composite": true + }, + "include": ["../global.d.ts", "./**/*.ts"], + "exclude": ["./**/*.test.ts"] +} diff --git a/node_modules/msw/src/tsconfig.worker.json b/node_modules/msw/src/tsconfig.worker.json new file mode 100644 index 0000000000000000000000000000000000000000..d0f218d5cf88c856da99b219eeb56afb942d440b --- /dev/null +++ b/node_modules/msw/src/tsconfig.worker.json @@ -0,0 +1,14 @@ +{ + "include": ["./mockServiceWorker.js"], + "files": [], + "compilerOptions": { + "composite": true, + "strict": true, + "allowJs": true, + "checkJs": true, + "target": "esnext", + "module": "esnext", + "lib": ["esnext"], + "types": ["@types/serviceworker"] + } +} diff --git a/node_modules/multer/LICENSE b/node_modules/multer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6c011b18fa16e456f63b662d75047e376306874b --- /dev/null +++ b/node_modules/multer/LICENSE @@ -0,0 +1,17 @@ +Copyright (c) 2014 Hage Yaapa <[http://www.hacksparrow.com](http://www.hacksparrow.com)> + +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. diff --git a/node_modules/multer/README.md b/node_modules/multer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ed2a4e6d817ac328a976fca24b62f32c3064956b --- /dev/null +++ b/node_modules/multer/README.md @@ -0,0 +1,361 @@ +# Multer [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Test Coverage][test-image]][test-url] [![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] + +Multer is a node.js middleware for handling `multipart/form-data`, which is primarily used for uploading files. It is written +on top of [busboy](https://github.com/mscdex/busboy) for maximum efficiency. + +**NOTE**: Multer will not process any form which is not multipart (`multipart/form-data`). + +## Translations + +This README is also available in other languages: + +| | | +| ------------------------------------------------------------------------------ | --------------- | +| [العربية](https://github.com/expressjs/multer/blob/main/doc/README-ar.md) | Arabic | +| [简体中文](https://github.com/expressjs/multer/blob/main/doc/README-zh-cn.md) | Chinese | +| [Français](https://github.com/expressjs/multer/blob/main/doc/README-fr.md) | French | +| [한국어](https://github.com/expressjs/multer/blob/main/doc/README-ko.md) | Korean | +| [Português](https://github.com/expressjs/multer/blob/main/doc/README-pt-br.md) | Portuguese (BR) | +| [Русский язык](https://github.com/expressjs/multer/blob/main/doc/README-ru.md) | Russian | +| [Español](https://github.com/expressjs/multer/blob/main/doc/README-es.md) | Spanish | +| [O'zbek tili](https://github.com/expressjs/multer/blob/main/doc/README-uz.md) | Uzbek | +| [Việt Nam](https://github.com/expressjs/multer/blob/main/doc/README-vi.md) | Vietnamese | +| [Türkçe](https://github.com/expressjs/multer/blob/main/doc/README-tr.md) | Turkish | + + +## Installation + +```sh +$ npm install multer +``` + +## Usage + +Multer adds a `body` object and a `file` or `files` object to the `request` object. The `body` object contains the values of the text fields of the form, the `file` or `files` object contains the files uploaded via the form. + +Basic usage example: + +Don't forget the `enctype="multipart/form-data"` in your form. + +```html +
+ +
+``` + +```javascript +const express = require('express') +const multer = require('multer') +const upload = multer({ dest: 'uploads/' }) + +const app = express() + +app.post('/profile', upload.single('avatar'), function (req, res, next) { + // req.file is the `avatar` file + // req.body will hold the text fields, if there were any +}) + +app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) { + // req.files is array of `photos` files + // req.body will contain the text fields, if there were any +}) + +const uploadMiddleware = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]) +app.post('/cool-profile', uploadMiddleware, function (req, res, next) { + // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files + // + // e.g. + // req.files['avatar'][0] -> File + // req.files['gallery'] -> Array + // + // req.body will contain the text fields, if there were any +}) +``` + +In case you need to handle a text-only multipart form, you should use the `.none()` method: + +```javascript +const express = require('express') +const app = express() +const multer = require('multer') +const upload = multer() + +app.post('/profile', upload.none(), function (req, res, next) { + // req.body contains the text fields +}) +``` + +Here's an example on how multer is used in a HTML form. Take special note of the `enctype="multipart/form-data"` and `name="uploaded_file"` fields: + +```html +
+
+ + + +
+
+``` + +Then in your javascript file you would add these lines to access both the file and the body. It is important that you use the `name` field value from the form in your upload function. This tells multer which field on the request it should look for the files in. If these fields aren't the same in the HTML form and on your server, your upload will fail: + +```javascript +const multer = require('multer') +const upload = multer({ dest: './public/data/uploads/' }) +app.post('/stats', upload.single('uploaded_file'), function (req, res) { + // req.file is the name of your file in the form above, here 'uploaded_file' + // req.body will hold the text fields, if there were any + console.log(req.file, req.body) +}); +``` + + + +## API + +### File information + +Each file contains the following information: + +Key | Description | Note +--- | --- | --- +`fieldname` | Field name specified in the form | +`originalname` | Name of the file on the user's computer | +`encoding` | Encoding type of the file | +`mimetype` | Mime type of the file | +`size` | Size of the file in bytes | +`destination` | The folder to which the file has been saved | `DiskStorage` +`filename` | The name of the file within the `destination` | `DiskStorage` +`path` | The full path to the uploaded file | `DiskStorage` +`buffer` | A `Buffer` of the entire file | `MemoryStorage` + +### `multer(opts)` + +Multer accepts an options object, the most basic of which is the `dest` +property, which tells Multer where to upload the files. In case you omit the +options object, the files will be kept in memory and never written to disk. + +By default, Multer will rename the files so as to avoid naming conflicts. The +renaming function can be customized according to your needs. + +The following are the options that can be passed to Multer. + +Key | Description +--- | --- +`dest` or `storage` | Where to store the files +`fileFilter` | Function to control which files are accepted +`limits` | Limits of the uploaded data +`preservePath` | Keep the full path of files instead of just the base name +`defParamCharset` | Default character set to use for values of part header parameters (e.g. filename) that are not extended parameters (that contain an explicit charset). Default: `'latin1'` + +In an average web app, only `dest` might be required, and configured as shown in +the following example. + +```javascript +const upload = multer({ dest: 'uploads/' }) +``` + +If you want more control over your uploads, you'll want to use the `storage` +option instead of `dest`. Multer ships with storage engines `DiskStorage` +and `MemoryStorage`; More engines are available from third parties. + +#### `.single(fieldname)` + +Accept a single file with the name `fieldname`. The single file will be stored +in `req.file`. + +#### `.array(fieldname[, maxCount])` + +Accept an array of files, all with the name `fieldname`. Optionally error out if +more than `maxCount` files are uploaded. The array of files will be stored in +`req.files`. + +#### `.fields(fields)` + +Accept a mix of files, specified by `fields`. An object with arrays of files +will be stored in `req.files`. + +`fields` should be an array of objects with `name` and optionally a `maxCount`. +Example: + +```javascript +[ + { name: 'avatar', maxCount: 1 }, + { name: 'gallery', maxCount: 8 } +] +``` + +#### `.none()` + +Accept only text fields. If any file upload is made, error with code +"LIMIT\_UNEXPECTED\_FILE" will be issued. + +#### `.any()` + +Accepts all files that comes over the wire. An array of files will be stored in +`req.files`. + +**WARNING:** Make sure that you always handle the files that a user uploads. +Never add multer as a global middleware since a malicious user could upload +files to a route that you didn't anticipate. Only use this function on routes +where you are handling the uploaded files. + +### `storage` + +#### `DiskStorage` + +The disk storage engine gives you full control on storing files to disk. + +```javascript +const storage = multer.diskStorage({ + destination: function (req, file, cb) { + cb(null, '/tmp/my-uploads') + }, + filename: function (req, file, cb) { + const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9) + cb(null, file.fieldname + '-' + uniqueSuffix) + } +}) + +const upload = multer({ storage: storage }) +``` + +There are two options available, `destination` and `filename`. They are both +functions that determine where the file should be stored. + +`destination` is used to determine within which folder the uploaded files should +be stored. This can also be given as a `string` (e.g. `'/tmp/uploads'`). If no +`destination` is given, the operating system's default directory for temporary +files is used. + +**Note:** You are responsible for creating the directory when providing +`destination` as a function. When passing a string, multer will make sure that +the directory is created for you. + +`filename` is used to determine what the file should be named inside the folder. +If no `filename` is given, each file will be given a random name that doesn't +include any file extension. + +**Note:** Multer will not append any file extension for you, your function +should return a filename complete with a file extension. + +Each function gets passed both the request (`req`) and some information about +the file (`file`) to aid with the decision. + +Note that `req.body` might not have been fully populated yet. It depends on the +order that the client transmits fields and files to the server. + +For understanding the calling convention used in the callback (needing to pass +null as the first param), refer to +[Node.js error handling](https://web.archive.org/web/20220417042018/https://www.joyent.com/node-js/production/design/errors) + +#### `MemoryStorage` + +The memory storage engine stores the files in memory as `Buffer` objects. It +doesn't have any options. + +```javascript +const storage = multer.memoryStorage() +const upload = multer({ storage: storage }) +``` + +When using memory storage, the file info will contain a field called +`buffer` that contains the entire file. + +**WARNING**: Uploading very large files, or relatively small files in large +numbers very quickly, can cause your application to run out of memory when +memory storage is used. + +### `limits` + +An object specifying the size limits of the following optional properties. Multer passes this object into busboy directly, and the details of the properties can be found on [busboy's page](https://github.com/mscdex/busboy#busboy-methods). + +The following integer values are available: + +Key | Description | Default +--- | --- | --- +`fieldNameSize` | Max field name size | 100 bytes +`fieldSize` | Max field value size (in bytes) | 1MB +`fields` | Max number of non-file fields | Infinity +`fileSize` | For multipart forms, the max file size (in bytes) | Infinity +`files` | For multipart forms, the max number of file fields | Infinity +`parts` | For multipart forms, the max number of parts (fields + files) | Infinity +`headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000 +`fieldNestingDepth` | Max number of nesting levels for field names (e.g. `a[b][c]` has 2 levels) | Infinity + +Specifying the limits can help protect your site against denial of service (DoS) attacks. + +### `fileFilter` + +Set this to a function to control which files should be uploaded and which +should be skipped. The function should look like this: + +```javascript +function fileFilter (req, file, cb) { + + // The function should call `cb` with a boolean + // to indicate if the file should be accepted + + // To reject this file pass `false`, like so: + cb(null, false) + + // To accept the file pass `true`, like so: + cb(null, true) + + // You can always pass an error if something goes wrong: + cb(new Error('I don\'t have a clue!')) + +} +``` + +## Security + +Specifying the [limits](#limits) can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications: + +- `fileSize` -- set to the maximum expected file size for your use case +- `files` -- set to the maximum number of files per request +- `fields` -- set to the maximum number of text fields per request +- `fieldNestingDepth` -- set to the minimum depth your field names require (e.g. `3` for `a[b][c]`) + +## Error handling + +When encountering an error, Multer will delegate the error to Express. You can +display a nice error page using [the standard express way](http://expressjs.com/guide/error-handling.html). + +If you want to catch errors specifically from Multer, you can call the +middleware function by yourself. Also, if you want to catch only [the Multer errors](https://github.com/expressjs/multer/blob/main/lib/multer-error.js), you can use the `MulterError` class that is attached to the `multer` object itself (e.g. `err instanceof multer.MulterError`). + +```javascript +const multer = require('multer') +const upload = multer().single('avatar') + +app.post('/profile', function (req, res) { + upload(req, res, function (err) { + if (err instanceof multer.MulterError) { + // A Multer error occurred when uploading. + } else if (err) { + // An unknown error occurred when uploading. + } + + // Everything went fine. + }) +}) +``` + +## Custom storage engine + +For information on how to build your own storage engine, see [Multer Storage Engine](https://github.com/expressjs/multer/blob/main/StorageEngine.md). + +## License + +[MIT](LICENSE) + +[ci-image]: https://github.com/expressjs/multer/actions/workflows/ci.yml/badge.svg +[ci-url]: https://github.com/expressjs/multer/actions/workflows/ci.yml +[test-url]: https://coveralls.io/r/expressjs/multer?branch=main +[test-image]: https://badgen.net/coveralls/c/github/expressjs/multer/main +[npm-downloads-image]: https://badgen.net/npm/dm/multer +[npm-url]: https://npmjs.org/package/multer +[npm-version-image]: https://badgen.net/npm/v/multer +[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/multer/badge +[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/multer diff --git a/node_modules/multer/index.js b/node_modules/multer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1dbfaacb1c64dd1c929f1cfcf09716c7e6fa7b35 --- /dev/null +++ b/node_modules/multer/index.js @@ -0,0 +1,107 @@ +var makeMiddleware = require('./lib/make-middleware') + +var diskStorage = require('./storage/disk') +var memoryStorage = require('./storage/memory') +var MulterError = require('./lib/multer-error') + +function allowAll (req, file, cb) { + cb(null, true) +} + +function Multer (options) { + if (options.storage) { + this.storage = options.storage + } else if (options.dest) { + this.storage = diskStorage({ destination: options.dest }) + } else { + this.storage = memoryStorage() + } + + this.limits = options.limits + this.preservePath = options.preservePath + this.defParamCharset = options.defParamCharset || 'latin1' + this.fileFilter = options.fileFilter || allowAll +} + +Multer.prototype._makeMiddleware = function (fields, fileStrategy) { + function setup () { + var fileFilter = this.fileFilter + var filesLeft = Object.create(null) + + fields.forEach(function (field) { + if (typeof field.maxCount === 'number') { + filesLeft[field.name] = field.maxCount + } else { + filesLeft[field.name] = Infinity + } + }) + + function wrappedFileFilter (req, file, cb) { + if ((filesLeft[file.fieldname] || 0) <= 0) { + return cb(new MulterError('LIMIT_UNEXPECTED_FILE', file.fieldname)) + } + + filesLeft[file.fieldname] -= 1 + fileFilter(req, file, cb) + } + + return { + limits: this.limits, + preservePath: this.preservePath, + defParamCharset: this.defParamCharset, + storage: this.storage, + fileFilter: wrappedFileFilter, + fileStrategy: fileStrategy + } + } + + return makeMiddleware(setup.bind(this)) +} + +Multer.prototype.single = function (name) { + return this._makeMiddleware([{ name: name, maxCount: 1 }], 'VALUE') +} + +Multer.prototype.array = function (name, maxCount) { + return this._makeMiddleware([{ name: name, maxCount: maxCount }], 'ARRAY') +} + +Multer.prototype.fields = function (fields) { + return this._makeMiddleware(fields, 'OBJECT') +} + +Multer.prototype.none = function () { + return this._makeMiddleware([], 'NONE') +} + +Multer.prototype.any = function () { + function setup () { + return { + limits: this.limits, + preservePath: this.preservePath, + defParamCharset: this.defParamCharset, + storage: this.storage, + fileFilter: this.fileFilter, + fileStrategy: 'ARRAY' + } + } + + return makeMiddleware(setup.bind(this)) +} + +function multer (options) { + if (options === undefined) { + return new Multer({}) + } + + if (typeof options === 'object' && options !== null) { + return new Multer(options) + } + + throw new TypeError('Expected object for argument options') +} + +module.exports = multer +module.exports.diskStorage = diskStorage +module.exports.memoryStorage = memoryStorage +module.exports.MulterError = MulterError diff --git a/node_modules/multer/lib/counter.js b/node_modules/multer/lib/counter.js new file mode 100644 index 0000000000000000000000000000000000000000..29c410c7b4850d2640fef61629508a534fc98a74 --- /dev/null +++ b/node_modules/multer/lib/counter.js @@ -0,0 +1,28 @@ +var EventEmitter = require('events').EventEmitter + +function Counter () { + EventEmitter.call(this) + this.value = 0 +} + +Counter.prototype = Object.create(EventEmitter.prototype) + +Counter.prototype.increment = function increment () { + this.value++ +} + +Counter.prototype.decrement = function decrement () { + if (--this.value === 0) this.emit('zero') +} + +Counter.prototype.isZero = function isZero () { + return (this.value === 0) +} + +Counter.prototype.onceZero = function onceZero (fn) { + if (this.isZero()) return fn() + + this.once('zero', fn) +} + +module.exports = Counter diff --git a/node_modules/multer/lib/file-appender.js b/node_modules/multer/lib/file-appender.js new file mode 100644 index 0000000000000000000000000000000000000000..a760d8bb5f2879e4ee9fb5ee3951d9953c97cbb0 --- /dev/null +++ b/node_modules/multer/lib/file-appender.js @@ -0,0 +1,65 @@ +function arrayRemove (arr, item) { + var idx = arr.indexOf(item) + if (~idx) arr.splice(idx, 1) +} + +function FileAppender (strategy, req) { + this.strategy = strategy + this.req = req + + switch (strategy) { + case 'NONE': break + case 'VALUE': break + case 'ARRAY': req.files = []; break + case 'OBJECT': req.files = Object.create(null); break + default: throw new Error('Unknown file strategy: ' + strategy) + } +} + +FileAppender.prototype.insertPlaceholder = function (file) { + var placeholder = { + fieldname: file.fieldname + } + + switch (this.strategy) { + case 'NONE': break + case 'VALUE': break + case 'ARRAY': this.req.files.push(placeholder); break + case 'OBJECT': + if (this.req.files[file.fieldname]) { + this.req.files[file.fieldname].push(placeholder) + } else { + this.req.files[file.fieldname] = [placeholder] + } + break + } + + return placeholder +} + +FileAppender.prototype.removePlaceholder = function (placeholder) { + switch (this.strategy) { + case 'NONE': break + case 'VALUE': break + case 'ARRAY': arrayRemove(this.req.files, placeholder); break + case 'OBJECT': + if (this.req.files[placeholder.fieldname].length === 1) { + delete this.req.files[placeholder.fieldname] + } else { + arrayRemove(this.req.files[placeholder.fieldname], placeholder) + } + break + } +} + +FileAppender.prototype.replacePlaceholder = function (placeholder, file) { + if (this.strategy === 'VALUE') { + this.req.file = file + return + } + + delete placeholder.fieldname + Object.assign(placeholder, file) +} + +module.exports = FileAppender diff --git a/node_modules/multer/lib/make-middleware.js b/node_modules/multer/lib/make-middleware.js new file mode 100644 index 0000000000000000000000000000000000000000..2c15f248d4f4d221bd9e2b2e1092b8d5c46d2bdd --- /dev/null +++ b/node_modules/multer/lib/make-middleware.js @@ -0,0 +1,265 @@ +var is = require('type-is') +var Busboy = require('busboy') +var appendField = require('append-field') + +var Counter = require('./counter') +var MulterError = require('./multer-error') +var FileAppender = require('./file-appender') +var removeUploadedFiles = require('./remove-uploaded-files') + +function drainStream (stream) { + stream.on('readable', () => { + while (stream.read() !== null) {} + }) +} + +function makeMiddleware (setup) { + return function multerMiddleware (req, res, next) { + if (!is(req, ['multipart'])) return next() + + var options = setup() + + var limits = options.limits + var storage = options.storage + var fileFilter = options.fileFilter + var fileStrategy = options.fileStrategy + var preservePath = options.preservePath + var defParamCharset = options.defParamCharset + + req.body = Object.create(null) + + var busboy + var appender = null + var isDone = false + var readFinished = false + var errorOccured = false + var pendingWrites = new Counter() + var uploadedFiles = [] + var pendingFiles = [] + + function done (err) { + var called = false + function onFinished () { + if (called) return + called = true + next(err) + } + + if (isDone) return + isDone = true + if (busboy) { + req.unpipe(busboy) + setImmediate(() => { + busboy.removeAllListeners() + }) + } + drainStream(req) + req.resume() + + // - if responding with an error, drain request body before calling + // next(err) -- avoids EPIPE on the client (server closing connection + // while the client is still sending the request body) + // - also listen for 'close' so we don't hang when the client aborts (stream may never 'end') + // - skip waiting if the stream is already destroyed (e.g. client aborted) + if (err && req.readable && !req.destroyed) { + req.once('end', onFinished) + req.once('error', onFinished) + req.once('close', onFinished) + return + } + next(err) + } + + function indicateDone () { + if (readFinished && pendingWrites.isZero() && !errorOccured) done() + } + + function abortWithError (uploadError, skipPendingWait) { + if (errorOccured) return + errorOccured = true + + function finishAbort () { + function remove (file, cb) { + storage._removeFile(req, file, cb) + } + + var filesToRemove = uploadedFiles.concat( + pendingFiles.filter(function (f) { return f.path }) + ) + pendingFiles = [] + + removeUploadedFiles(filesToRemove, remove, function (err, storageErrors) { + if (err) return done(err) + + uploadError.storageErrors = storageErrors + done(uploadError) + }) + } + + if (skipPendingWait) { + finishAbort() + } else { + pendingWrites.onceZero(finishAbort) + } + } + + function abortWithCode (code, optionalField) { + abortWithError(new MulterError(code, optionalField)) + } + + function handleRequestFailure (err) { + if (isDone) return + if (busboy) { + req.unpipe(busboy) + busboy.destroy(err) + } + abortWithError(err, true) + } + + req.on('error', function (err) { + handleRequestFailure(err || new Error('Request error')) + }) + + req.on('aborted', function () { + handleRequestFailure(new Error('Request aborted')) + }) + + req.on('close', function () { + if (req.readableEnded) return + handleRequestFailure(new Error('Request closed')) + }) + + try { + busboy = Busboy({ + headers: req.headers, + limits: limits, + preservePath: preservePath, + defParamCharset: defParamCharset + }) + } catch (err) { + return next(err) + } + + appender = new FileAppender(fileStrategy, req) + + // handle text field data + busboy.on('field', function (fieldname, value, { nameTruncated, valueTruncated }) { + if (fieldname == null) return abortWithCode('MISSING_FIELD_NAME') + if (nameTruncated) return abortWithCode('LIMIT_FIELD_KEY') + if (valueTruncated) return abortWithCode('LIMIT_FIELD_VALUE', fieldname) + + // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6) + if (limits && Object.prototype.hasOwnProperty.call(limits, 'fieldNameSize')) { + if (fieldname.length > limits.fieldNameSize) return abortWithCode('LIMIT_FIELD_KEY') + } + + if (limits && Object.prototype.hasOwnProperty.call(limits, 'fieldNestingDepth')) { + if (fieldname.split('[').length - 1 > limits.fieldNestingDepth) return abortWithCode('LIMIT_FIELD_NESTING', fieldname) + } + + appendField(req.body, fieldname, value) + }) + + // handle files + busboy.on('file', function (fieldname, fileStream, { filename, encoding, mimeType }) { + var pendingWritesIncremented = false + + fileStream.on('error', function (err) { + if (pendingWritesIncremented) { + pendingWrites.decrement() + } + abortWithError(err) + }) + + if (fieldname == null) return abortWithCode('MISSING_FIELD_NAME') + + // don't attach to the files object, if there is no file + if (!filename) return fileStream.resume() + + // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6) + if (limits && Object.prototype.hasOwnProperty.call(limits, 'fieldNameSize')) { + if (fieldname.length > limits.fieldNameSize) return abortWithCode('LIMIT_FIELD_KEY') + } + + var file = { + fieldname: fieldname, + originalname: filename, + encoding: encoding, + mimetype: mimeType + } + + var placeholder = appender.insertPlaceholder(file) + + fileFilter(req, file, function (err, includeFile) { + if (errorOccured) { + appender.removePlaceholder(placeholder) + return fileStream.resume() + } + + if (err) { + appender.removePlaceholder(placeholder) + return abortWithError(err) + } + + if (!includeFile) { + appender.removePlaceholder(placeholder) + return fileStream.resume() + } + + var aborting = false + pendingWritesIncremented = true + pendingWrites.increment() + + Object.defineProperty(file, 'stream', { + configurable: true, + enumerable: false, + value: fileStream + }) + + fileStream.on('limit', function () { + aborting = true + abortWithCode('LIMIT_FILE_SIZE', fieldname) + }) + + pendingFiles.push(file) + + storage._handleFile(req, file, function (err, info) { + var idx = pendingFiles.indexOf(file) + if (idx !== -1) pendingFiles.splice(idx, 1) + + if (aborting) { + appender.removePlaceholder(placeholder) + uploadedFiles.push({ ...file, ...info }) + return pendingWrites.decrement() + } + + if (err) { + appender.removePlaceholder(placeholder) + pendingWrites.decrement() + return abortWithError(err) + } + + var fileInfo = { ...file, ...info } + + appender.replacePlaceholder(placeholder, fileInfo) + uploadedFiles.push(fileInfo) + pendingWrites.decrement() + indicateDone() + }) + }) + }) + + busboy.on('error', function (err) { abortWithError(err) }) + busboy.on('partsLimit', function () { abortWithCode('LIMIT_PART_COUNT') }) + busboy.on('filesLimit', function () { abortWithCode('LIMIT_FILE_COUNT') }) + busboy.on('fieldsLimit', function () { abortWithCode('LIMIT_FIELD_COUNT') }) + busboy.on('close', function () { + readFinished = true + indicateDone() + }) + + req.pipe(busboy) + } +} + +module.exports = makeMiddleware diff --git a/node_modules/multer/lib/multer-error.js b/node_modules/multer/lib/multer-error.js new file mode 100644 index 0000000000000000000000000000000000000000..c2b8c4573915e930cb3be13e772bb05ac2eb9d81 --- /dev/null +++ b/node_modules/multer/lib/multer-error.js @@ -0,0 +1,25 @@ +var util = require('util') + +var errorMessages = { + LIMIT_PART_COUNT: 'Too many parts', + LIMIT_FILE_SIZE: 'File too large', + LIMIT_FILE_COUNT: 'Too many files', + LIMIT_FIELD_KEY: 'Field name too long', + LIMIT_FIELD_VALUE: 'Field value too long', + LIMIT_FIELD_COUNT: 'Too many fields', + LIMIT_UNEXPECTED_FILE: 'Unexpected field', + MISSING_FIELD_NAME: 'Field name missing', + LIMIT_FIELD_NESTING: 'Field name nesting too deep' +} + +function MulterError (code, field) { + Error.captureStackTrace(this, this.constructor) + this.name = this.constructor.name + this.message = errorMessages[code] + this.code = code + if (field) this.field = field +} + +util.inherits(MulterError, Error) + +module.exports = MulterError diff --git a/node_modules/multer/lib/remove-uploaded-files.js b/node_modules/multer/lib/remove-uploaded-files.js new file mode 100644 index 0000000000000000000000000000000000000000..d225c4842fa4bcb53c579fc40c32ec7696a8c1b9 --- /dev/null +++ b/node_modules/multer/lib/remove-uploaded-files.js @@ -0,0 +1,28 @@ +function removeUploadedFiles (uploadedFiles, remove, cb) { + var length = uploadedFiles.length + var errors = [] + + if (length === 0) return cb(null, errors) + + function handleFile (idx) { + var file = uploadedFiles[idx] + + remove(file, function (err) { + if (err) { + err.file = file + err.field = file.fieldname + errors.push(err) + } + + if (idx < length - 1) { + setImmediate(function () { handleFile(idx + 1) }) + } else { + cb(null, errors) + } + }) + } + + handleFile(0) +} + +module.exports = removeUploadedFiles diff --git a/node_modules/multer/package.json b/node_modules/multer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1d0137e23795a2214ba9495aea7e869a952b2522 --- /dev/null +++ b/node_modules/multer/package.json @@ -0,0 +1,58 @@ +{ + "name": "multer", + "description": "Middleware for handling `multipart/form-data`.", + "version": "2.2.0", + "contributors": [ + "Hage Yaapa (http://www.hacksparrow.com)", + "Jaret Pfluger ", + "Linus Unnebäck " + ], + "license": "MIT", + "repository": "expressjs/multer", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "keywords": [ + "form", + "post", + "multipart", + "form-data", + "formdata", + "express", + "middleware" + ], + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "concat-stream": "^2.0.0", + "type-is": "^1.6.18" + }, + "devDependencies": { + "deep-equal": "^2.0.3", + "express": "^4.21.2", + "form-data": "^4.0.2", + "fs-temp": "^1.2.1", + "mocha": "^11.5.0", + "nyc": "^15.1.0", + "rimraf": "^2.4.1", + "standard": "^14.3.3", + "testdata-w3c-json-form": "^1.0.0" + }, + "engines": { + "node": ">= 10.16.0" + }, + "files": [ + "LICENSE", + "index.js", + "storage/", + "lib/" + ], + "scripts": { + "lint": "standard", + "lint:fix": "standard --fix", + "test": "mocha --reporter spec --exit --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/multer/storage/disk.js b/node_modules/multer/storage/disk.js new file mode 100644 index 0000000000000000000000000000000000000000..e47e16a950eec3ceae578205e78496548de21774 --- /dev/null +++ b/node_modules/multer/storage/disk.js @@ -0,0 +1,70 @@ +var fs = require('fs') +var os = require('os') +var path = require('path') +var crypto = require('crypto') + +function getFilename (req, file, cb) { + crypto.randomBytes(16, function (err, raw) { + cb(err, err ? undefined : raw.toString('hex')) + }) +} + +function getDestination (req, file, cb) { + cb(null, os.tmpdir()) +} + +function DiskStorage (opts) { + this.getFilename = (opts.filename || getFilename) + + if (typeof opts.destination === 'string') { + fs.mkdirSync(opts.destination, { recursive: true }) + this.getDestination = function ($0, $1, cb) { cb(null, opts.destination) } + } else { + this.getDestination = (opts.destination || getDestination) + } +} + +DiskStorage.prototype._handleFile = function _handleFile (req, file, cb) { + var that = this + + that.getDestination(req, file, function (err, destination) { + if (err) return cb(err) + + that.getFilename(req, file, function (err, filename) { + if (err) return cb(err) + + var finalPath = path.join(destination, filename) + + if (file.stream.destroyed) return + + var outStream = fs.createWriteStream(finalPath) + + file.path = finalPath + + file.stream.pipe(outStream) + outStream.on('error', cb) + outStream.on('finish', function () { + cb(null, { + destination: destination, + filename: filename, + path: finalPath, + size: outStream.bytesWritten + }) + }) + }) + }) +} + +DiskStorage.prototype._removeFile = function _removeFile (req, file, cb) { + var path = file.path + + delete file.destination + delete file.filename + delete file.path + + fs.unlink(path, cb) +} + +module.exports = function (opts) { + return new DiskStorage(opts) +} diff --git a/node_modules/multer/storage/memory.js b/node_modules/multer/storage/memory.js new file mode 100644 index 0000000000000000000000000000000000000000..f953ded15a2baf5cf59d3c2a716a8d5576db086c --- /dev/null +++ b/node_modules/multer/storage/memory.js @@ -0,0 +1,21 @@ +var concat = require('concat-stream') + +function MemoryStorage (opts) {} + +MemoryStorage.prototype._handleFile = function _handleFile (req, file, cb) { + file.stream.pipe(concat({ encoding: 'buffer' }, function (data) { + cb(null, { + buffer: data, + size: data.length + }) + })) +} + +MemoryStorage.prototype._removeFile = function _removeFile (req, file, cb) { + delete file.buffer + cb(null) +} + +module.exports = function (opts) { + return new MemoryStorage(opts) +} diff --git a/node_modules/murmurhash-js/README.md b/node_modules/murmurhash-js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..62cb1e9aad8c886a2c5967e9c7ad2bb0e7571fa6 --- /dev/null +++ b/node_modules/murmurhash-js/README.md @@ -0,0 +1,40 @@ +# MurmurHash.js + +An optimized JavaScript implementation of the MurmurHash algorithms. + +These algorithms take a JavaScript string (and a seed), and quickly create a non-cryptographic 32-bit hash from it. And by quick I mean sub-millisecond performance. + +More information about these algorithms can be found at: + +* [MurmurHash Homepage](http://sites.google.com/site/murmurhash/) +* [Wikipedia Entry on MurmurHash](http://en.wikipedia.org/wiki/MurmurHash) + +## Install + + npm install murmurhash-js + +## API + +```javascript +var murmur = require("murmurhash-js") +``` + +### Methods + +#### `murmur.murmur2(key, seed)` +Runs the murmur2 hash algorithm on the string `key` with initial seed `seed`. + +#### `murmur.murmur3(key, seed)` +Runs the murmur3 hash algorithm on the string `key` with initial seed `seed`. + +**Note** `require("murmur-hash")` is the same as `murmur.murmur3` + +## License (MIT) + +Copyright (c) 2011 Gary Court + +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. \ No newline at end of file diff --git a/node_modules/murmurhash-js/index.js b/node_modules/murmurhash-js/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d56fbcf780307cc4671d08f8376633dae3fb00b7 --- /dev/null +++ b/node_modules/murmurhash-js/index.js @@ -0,0 +1,6 @@ +var murmur3 = require("./murmurhash3_gc.js") +var murmur2 = require("./murmurhash2_gc.js") + +module.exports = murmur3 +module.exports.murmur3 = murmur3 +module.exports.murmur2 = murmur2 diff --git a/node_modules/murmurhash-js/murmurhash2_gc.js b/node_modules/murmurhash-js/murmurhash2_gc.js new file mode 100644 index 0000000000000000000000000000000000000000..1d169614b50d541927649f2f2089e48a69d86c28 --- /dev/null +++ b/node_modules/murmurhash-js/murmurhash2_gc.js @@ -0,0 +1,54 @@ +/** + * JS Implementation of MurmurHash2 + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} str ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ + +function murmurhash2_32_gc(str, seed) { + var + l = str.length, + h = seed ^ l, + i = 0, + k; + + while (l >= 4) { + k = + ((str.charCodeAt(i) & 0xff)) | + ((str.charCodeAt(++i) & 0xff) << 8) | + ((str.charCodeAt(++i) & 0xff) << 16) | + ((str.charCodeAt(++i) & 0xff) << 24); + + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + k ^= k >>> 24; + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; + + l -= 4; + ++i; + } + + switch (l) { + case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; + case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; + case 1: h ^= (str.charCodeAt(i) & 0xff); + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + } + + h ^= h >>> 13; + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + h ^= h >>> 15; + + return h >>> 0; +} + +if(typeof module !== undefined) { + module.exports = murmurhash2_32_gc +} diff --git a/node_modules/murmurhash-js/murmurhash3_gc.js b/node_modules/murmurhash-js/murmurhash3_gc.js new file mode 100644 index 0000000000000000000000000000000000000000..c9b0b6ad7757dacffefecc534f0a5b5d8082fd0b --- /dev/null +++ b/node_modules/murmurhash-js/murmurhash3_gc.js @@ -0,0 +1,68 @@ +/** + * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} key ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ + +function murmurhash3_32_gc(key, seed) { + var remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i; + + remainder = key.length & 3; // key.length % 4 + bytes = key.length - remainder; + h1 = seed; + c1 = 0xcc9e2d51; + c2 = 0x1b873593; + i = 0; + + while (i < bytes) { + k1 = + ((key.charCodeAt(i) & 0xff)) | + ((key.charCodeAt(++i) & 0xff) << 8) | + ((key.charCodeAt(++i) & 0xff) << 16) | + ((key.charCodeAt(++i) & 0xff) << 24); + ++i; + + k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff; + + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff; + h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16)); + } + + k1 = 0; + + switch (remainder) { + case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; + case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; + case 1: k1 ^= (key.charCodeAt(i) & 0xff); + + k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; + h1 ^= k1; + } + + h1 ^= key.length; + + h1 ^= h1 >>> 16; + h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff; + h1 ^= h1 >>> 16; + + return h1 >>> 0; +} + +if(typeof module !== "undefined") { + module.exports = murmurhash3_32_gc +} \ No newline at end of file diff --git a/node_modules/murmurhash-js/package.json b/node_modules/murmurhash-js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f12ada4fad29ce2ac369bf960e947b6941986464 --- /dev/null +++ b/node_modules/murmurhash-js/package.json @@ -0,0 +1,28 @@ +{ + "name": "murmurhash-js", + "version": "1.0.0", + "description": "Native JS murmur hash implementation", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/mikolalysenko/murmurhash-js.git" + }, + "keywords": [ + "murmur", + "hash", + "string", + "murmur2", + "murmur3", + "fast" + ], + "author": "Gary Court", + "license": "MIT", + "readmeFilename": "README.md", + "gitHead": "72aabce3f52cb8f16245692a69fd35951e165af0", + "bugs": { + "url": "https://github.com/mikolalysenko/murmurhash-js/issues" + } +} diff --git a/node_modules/mute-stream/LICENSE b/node_modules/mute-stream/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..19129e315fe593965a2fdd50ec0d1253bcbd2ece --- /dev/null +++ b/node_modules/mute-stream/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mute-stream/README.md b/node_modules/mute-stream/README.md new file mode 100644 index 0000000000000000000000000000000000000000..42ff9fb516039da8d2d27f3e3347cc3d624dbe29 --- /dev/null +++ b/node_modules/mute-stream/README.md @@ -0,0 +1,68 @@ +# mute-stream + +Bytes go in, but they don't come out (when muted). + +This is a basic pass-through stream, but when muted, the bytes are +silently dropped, rather than being passed through. + +## Usage + +```javascript +const MuteStream = require('mute-stream') + +const ms = new MuteStream(options) + +ms.pipe(process.stdout) +ms.write('foo') // writes 'foo' to stdout +ms.mute() +ms.write('bar') // does not write 'bar' +ms.unmute() +ms.write('baz') // writes 'baz' to stdout + +// can also be used to mute incoming data +const ms = new MuteStream() +input.pipe(ms) + +ms.on('data', function (c) { + console.log('data: ' + c) +}) + +input.emit('data', 'foo') // logs 'foo' +ms.mute() +input.emit('data', 'bar') // does not log 'bar' +ms.unmute() +input.emit('data', 'baz') // logs 'baz' +``` + +## Options + +All options are optional. + +* `replace` Set to a string to replace each character with the + specified string when muted. (So you can show `****` instead of the + password, for example.) + +* `prompt` If you are using a replacement char, and also using a + prompt with a readline stream (as for a `Password: *****` input), + then specify what the prompt is so that backspace will work + properly. Otherwise, pressing backspace will overwrite the prompt + with the replacement character, which is weird. + +## ms.mute() + +Set `muted` to `true`. Turns `.write()` into a no-op. + +## ms.unmute() + +Set `muted` to `false` + +## ms.isTTY + +True if the pipe destination is a TTY, or if the incoming pipe source is +a TTY. + +## Other stream methods... + +The other standard readable and writable stream methods are all +available. The MuteStream object acts as a facade to its pipe source +and destination. diff --git a/node_modules/mute-stream/lib/index.js b/node_modules/mute-stream/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..368f727e2c3ed8354e824915a119346442e09486 --- /dev/null +++ b/node_modules/mute-stream/lib/index.js @@ -0,0 +1,142 @@ +const Stream = require('stream') + +class MuteStream extends Stream { + #isTTY = null + + constructor (opts = {}) { + super(opts) + this.writable = this.readable = true + this.muted = false + this.on('pipe', this._onpipe) + this.replace = opts.replace + + // For readline-type situations + // This much at the start of a line being redrawn after a ctrl char + // is seen (such as backspace) won't be redrawn as the replacement + this._prompt = opts.prompt || null + this._hadControl = false + } + + #destSrc (key, def) { + if (this._dest) { + return this._dest[key] + } + if (this._src) { + return this._src[key] + } + return def + } + + #proxy (method, ...args) { + if (typeof this._dest?.[method] === 'function') { + this._dest[method](...args) + } + if (typeof this._src?.[method] === 'function') { + this._src[method](...args) + } + } + + get isTTY () { + if (this.#isTTY !== null) { + return this.#isTTY + } + return this.#destSrc('isTTY', false) + } + + // basically just get replace the getter/setter with a regular value + set isTTY (val) { + this.#isTTY = val + } + + get rows () { + return this.#destSrc('rows') + } + + get columns () { + return this.#destSrc('columns') + } + + mute () { + this.muted = true + } + + unmute () { + this.muted = false + } + + _onpipe (src) { + this._src = src + } + + pipe (dest, options) { + this._dest = dest + return super.pipe(dest, options) + } + + pause () { + if (this._src) { + return this._src.pause() + } + } + + resume () { + if (this._src) { + return this._src.resume() + } + } + + write (c) { + if (this.muted) { + if (!this.replace) { + return true + } + // eslint-disable-next-line no-control-regex + if (c.match(/^\u001b/)) { + if (c.indexOf(this._prompt) === 0) { + c = c.slice(this._prompt.length) + c = c.replace(/./g, this.replace) + c = this._prompt + c + } + this._hadControl = true + return this.emit('data', c) + } else { + if (this._prompt && this._hadControl && + c.indexOf(this._prompt) === 0) { + this._hadControl = false + this.emit('data', this._prompt) + c = c.slice(this._prompt.length) + } + c = c.toString().replace(/./g, this.replace) + } + } + this.emit('data', c) + } + + end (c) { + if (this.muted) { + if (c && this.replace) { + c = c.toString().replace(/./g, this.replace) + } else { + c = null + } + } + if (c) { + this.emit('data', c) + } + this.emit('end') + } + + destroy (...args) { + return this.#proxy('destroy', ...args) + } + + destroySoon (...args) { + return this.#proxy('destroySoon', ...args) + } + + close (...args) { + return this.#proxy('close', ...args) + } +} + +module.exports = MuteStream diff --git a/node_modules/mute-stream/package.json b/node_modules/mute-stream/package.json new file mode 100644 index 0000000000000000000000000000000000000000..25e0af473d276afa478360bebeb64123df734bd5 --- /dev/null +++ b/node_modules/mute-stream/package.json @@ -0,0 +1,54 @@ +{ + "name": "mute-stream", + "version": "3.0.0", + "main": "lib/index.js", + "devDependencies": { + "@npmcli/eslint-config": "^5.0.0", + "@npmcli/template-oss": "4.27.1", + "tap": "^16.3.0" + }, + "scripts": { + "test": "tap", + "lint": "npm run eslint", + "postlint": "template-oss-check", + "template-oss-apply": "template-oss-apply --force", + "lintfix": "npm run eslint -- --fix", + "snap": "tap", + "posttest": "npm run lint", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/npm/mute-stream.git" + }, + "keywords": [ + "mute", + "stream", + "pipe" + ], + "author": "GitHub Inc.", + "license": "ISC", + "description": "Bytes go in, but they don't come out (when muted).", + "files": [ + "bin/", + "lib/" + ], + "tap": { + "statements": 70, + "branches": 60, + "functions": 81, + "lines": 70, + "nyc-arg": [ + "--exclude", + "tap-snapshots/**" + ] + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + }, + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "4.27.1", + "publish": true + } +} diff --git a/node_modules/mz/HISTORY.md b/node_modules/mz/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..6ebee21db896ba29798ccdd7627d26c534c6d8c3 --- /dev/null +++ b/node_modules/mz/HISTORY.md @@ -0,0 +1,66 @@ + +2.7.0 / 2017-09-13 +================== + + * feat: support fs.copyFile (#58) + +2.6.0 / 2016-11-22 +================== + + * Added fdatasync to fs api (#46) + +2.5.0 / 2016-11-04 +================== + + * feat: support fs.mkdtemp + +2.4.0 / 2016-03-23 +================== + + * add `fs.truncate()` [#34](https://github.com/normalize/mz/pull/34) + +2.3.1 / 2016-02-01 +================== + + * update `any-promise@v1` + +2.3.0 / 2016-01-30 +================== + + * feat(package): switch to `any-promise` to support more promise engines + +2.2.0 / 2016-01-24 +================== + + * feat(package): add index.js to files + +2.1.0 / 2015-10-15 +================== + + * support for readline library + +2.0.0 / 2015-05-24 +================== + + * support callbacks as well + +1.2.0 / 2014-12-16 +================== + + * refactor promisification to `thenify` and `thenify-all` + +1.1.0 / 2014-11-14 +================== + + * use `graceful-fs` if available + +1.0.1 / 2014-08-18 +================== + + * don't use `bluebird.promisify()` - unnecessarily wraps runtime errors, causing issues + +1.0.0 / 2014-06-18 +================== + + * use `bluebird` by default if found + * support node 0.8 diff --git a/node_modules/mz/LICENSE b/node_modules/mz/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1835f3d9f5acb61a4dbbcb5f655f74503471d956 --- /dev/null +++ b/node_modules/mz/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/mz/README.md b/node_modules/mz/README.md new file mode 100644 index 0000000000000000000000000000000000000000..50d6557ca9eaa238fc50ed0c07b185d5a105445c --- /dev/null +++ b/node_modules/mz/README.md @@ -0,0 +1,106 @@ + +# MZ - Modernize node.js + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![Dependency Status][david-image]][david-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +Modernize node.js to current ECMAScript specifications! +node.js will not update their API to ES6+ [for a while](https://github.com/joyent/node/issues/7549). +This library is a wrapper for various aspects of node.js' API. + +## Installation and Usage + +Set `mz` as a dependency and install it. + +```bash +npm i mz +``` + +Then prefix the relevant `require()`s with `mz/`: + +```js +var fs = require('mz/fs') + +fs.exists(__filename).then(function (exists) { + if (exists) // do something +}) +``` + +With ES2017, this will allow you to use async functions cleanly with node's core API: + +```js +const fs = require('mz/fs') + + +async function doSomething () { + if (await fs.exists(__filename)) // do something +} +``` + +## Promisification + +Many node methods are converted into promises. +Any properties that are deprecated or aren't asynchronous will simply be proxied. +The modules wrapped are: + +- `child_process` +- `crypto` +- `dns` +- `fs` (uses `graceful-fs` if available) +- `readline` +- `zlib` + +```js +var exec = require('mz/child_process').exec + +exec('node --version').then(function (stdout) { + console.log(stdout) +}) +``` + +## Promise Engine + +`mz` uses [`any-promise`](https://github.com/kevinbeaty/any-promise). + +## FAQ + +### Can I use this in production? + +Yes, Node 4.x ships with stable promises support. For older engines, +you should probably install your own promise implementation and register it with +`require('any-promise/register')('bluebird')`. + +### Will this make my app faster? + +Nope, probably slower actually. + +### Can I add more features? + +Sure. +Open an issue. + +Currently, the plans are to eventually support: + +- New APIs in node.js that are not available in older versions of node +- ECMAScript7 Streams + +[bluebird]: https://github.com/petkaantonov/bluebird + +[npm-image]: https://img.shields.io/npm/v/mz.svg?style=flat-square +[npm-url]: https://npmjs.org/package/mz +[github-tag]: http://img.shields.io/github/tag/normalize/mz.svg?style=flat-square +[github-url]: https://github.com/normalize/mz/tags +[travis-image]: https://img.shields.io/travis/normalize/mz.svg?style=flat-square +[travis-url]: https://travis-ci.org/normalize/mz +[coveralls-image]: https://img.shields.io/coveralls/normalize/mz.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/normalize/mz?branch=master +[david-image]: http://img.shields.io/david/normalize/mz.svg?style=flat-square +[david-url]: https://david-dm.org/normalize/mz +[license-image]: http://img.shields.io/npm/l/mz.svg?style=flat-square +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/mz.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/mz diff --git a/node_modules/mz/child_process.js b/node_modules/mz/child_process.js new file mode 100644 index 0000000000000000000000000000000000000000..06d5d9e3ca12cd1ee179f8dfd5ad1cd4b6e3187b --- /dev/null +++ b/node_modules/mz/child_process.js @@ -0,0 +1,8 @@ + +require('thenify-all').withCallback( + require('child_process'), + exports, [ + 'exec', + 'execFile', + ] +) diff --git a/node_modules/mz/crypto.js b/node_modules/mz/crypto.js new file mode 100644 index 0000000000000000000000000000000000000000..d8cff57f5e09da25905678ae6710869a6ef07d2d --- /dev/null +++ b/node_modules/mz/crypto.js @@ -0,0 +1,9 @@ + +require('thenify-all').withCallback( + require('crypto'), + exports, [ + 'pbkdf2', + 'pseudoRandomBytes', + 'randomBytes' + ] +) diff --git a/node_modules/mz/dns.js b/node_modules/mz/dns.js new file mode 100644 index 0000000000000000000000000000000000000000..c1035822971acdc3b5a03f416072f1b3ddafd510 --- /dev/null +++ b/node_modules/mz/dns.js @@ -0,0 +1,16 @@ + +require('thenify-all').withCallback( + require('dns'), + exports, [ + 'lookup', + 'resolve', + 'resolve4', + 'resolve6', + 'resolveCname', + 'resolveMx', + 'resolveNs', + 'resolveSrv', + 'resolveTxt', + 'reverse' + ] +) diff --git a/node_modules/mz/fs.js b/node_modules/mz/fs.js new file mode 100644 index 0000000000000000000000000000000000000000..1cfd2d776b0f6981d0d6941c533afcdf68c6cd68 --- /dev/null +++ b/node_modules/mz/fs.js @@ -0,0 +1,62 @@ + +var Promise = require('any-promise') +var fs +try { + fs = require('graceful-fs') +} catch(err) { + fs = require('fs') +} + +var api = [ + 'appendFile', + 'chmod', + 'chown', + 'close', + 'fchmod', + 'fchown', + 'fdatasync', + 'fstat', + 'fsync', + 'ftruncate', + 'futimes', + 'lchown', + 'link', + 'lstat', + 'mkdir', + 'open', + 'read', + 'readFile', + 'readdir', + 'readlink', + 'realpath', + 'rename', + 'rmdir', + 'stat', + 'symlink', + 'truncate', + 'unlink', + 'utimes', + 'write', + 'writeFile' +] + +typeof fs.access === 'function' && api.push('access') +typeof fs.copyFile === 'function' && api.push('copyFile') +typeof fs.mkdtemp === 'function' && api.push('mkdtemp') + +require('thenify-all').withCallback(fs, exports, api) + +exports.exists = function (filename, callback) { + // callback + if (typeof callback === 'function') { + return fs.stat(filename, function (err) { + callback(null, !err); + }) + } + // or promise + return new Promise(function (resolve) { + fs.stat(filename, function (err) { + resolve(!err) + }) + }) +} diff --git a/node_modules/mz/index.js b/node_modules/mz/index.js new file mode 100644 index 0000000000000000000000000000000000000000..cef508dc4c0be0f437914db472911a008e72dd2a --- /dev/null +++ b/node_modules/mz/index.js @@ -0,0 +1,8 @@ +module.exports = { + fs: require('./fs'), + dns: require('./dns'), + zlib: require('./zlib'), + crypto: require('./crypto'), + readline: require('./readline'), + child_process: require('./child_process') +} diff --git a/node_modules/mz/package.json b/node_modules/mz/package.json new file mode 100644 index 0000000000000000000000000000000000000000..de8d542cff88b294b7ae0d84e43fc67407dbbc5b --- /dev/null +++ b/node_modules/mz/package.json @@ -0,0 +1,44 @@ +{ + "name": "mz", + "description": "modernize node.js to current ECMAScript standards", + "version": "2.7.0", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "license": "MIT", + "repository": "normalize/mz", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + }, + "devDependencies": { + "istanbul": "^0.4.0", + "bluebird": "^3.0.0", + "mocha": "^3.0.0" + }, + "scripts": { + "test": "mocha --reporter spec", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "keywords": [ + "promisify", + "promise", + "thenify", + "then", + "es6" + ], + "files": [ + "index.js", + "child_process.js", + "crypto.js", + "dns.js", + "fs.js", + "readline.js", + "zlib.js" + ] +} diff --git a/node_modules/mz/readline.js b/node_modules/mz/readline.js new file mode 100644 index 0000000000000000000000000000000000000000..eb70c46f08cb42a6a8d50b49adddf751684fe1f1 --- /dev/null +++ b/node_modules/mz/readline.js @@ -0,0 +1,64 @@ +var readline = require('readline') +var Promise = require('any-promise') +var objectAssign = require('object-assign') +var Interface = readline.Interface + +function wrapCompleter (completer) { + if (completer.length === 2) return completer + + return function (line, cb) { + var result = completer(line) + + if (typeof result.then !== 'function') { + return cb(null, result) + } + + result.catch(cb).then(function (result) { + process.nextTick(function () { cb(null, result) }) + }) + } +} + +function InterfaceAsPromised (input, output, completer, terminal) { + if (arguments.length === 1) { + var options = input + + if (typeof options.completer === 'function') { + options = objectAssign({}, options, { + completer: wrapCompleter(options.completer) + }) + } + + Interface.call(this, options) + } else { + if (typeof completer === 'function') { + completer = wrapCompleter(completer) + } + + Interface.call(this, input, output, completer, terminal) + } +} + +InterfaceAsPromised.prototype = Object.create(Interface.prototype) + +InterfaceAsPromised.prototype.question = function (question, callback) { + if (typeof callback === 'function') { + return Interface.prototype.question.call(this, question, callback) + } + + var self = this + return new Promise(function (resolve) { + Interface.prototype.question.call(self, question, resolve) + }) +} + +objectAssign(exports, readline, { + Interface: InterfaceAsPromised, + createInterface: function (input, output, completer, terminal) { + if (arguments.length === 1) { + return new InterfaceAsPromised(input) + } + + return new InterfaceAsPromised(input, output, completer, terminal) + } +}) diff --git a/node_modules/mz/zlib.js b/node_modules/mz/zlib.js new file mode 100644 index 0000000000000000000000000000000000000000..a05c26a6abba33c8a87cde2928251257652fc5a4 --- /dev/null +++ b/node_modules/mz/zlib.js @@ -0,0 +1,13 @@ + +require('thenify-all').withCallback( + require('zlib'), + exports, [ + 'deflate', + 'deflateRaw', + 'gzip', + 'gunzip', + 'inflate', + 'inflateRaw', + 'unzip', + ] +) diff --git a/node_modules/nanoid/.claude/settings.local.json b/node_modules/nanoid/.claude/settings.local.json new file mode 100644 index 0000000000000000000000000000000000000000..7ee57f3087641d65d9b0bf49e70a5a1722ca6821 --- /dev/null +++ b/node_modules/nanoid/.claude/settings.local.json @@ -0,0 +1,14 @@ +{ + "permissions": { + "allow": [ + "Bash(node /workspaces/nanoid/test/check-versions.js)", + "Bash(echo \"Exit: $?\")", + "Bash(node --version)", + "Bash(node --experimental-strip-types test/check-prebuild.js)", + "Bash(node --experimental-strip-types test/update-prebuild.js)", + "Bash(node test/check-versions.js)", + "Bash(node bin/nanoid.js --version)", + "Bash(node bin/nanoid.js -s 10)" + ] + } +} diff --git a/node_modules/nanoid/LICENSE b/node_modules/nanoid/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..37f56aa49f8e009ed7e582cb3e905a1e0d1666fd --- /dev/null +++ b/node_modules/nanoid/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2017 Andrey Sitnik + +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. diff --git a/node_modules/nanoid/README.md b/node_modules/nanoid/README.md new file mode 100644 index 0000000000000000000000000000000000000000..35abb57d88a7613ff9c47a84cfb3ba4afbedea84 --- /dev/null +++ b/node_modules/nanoid/README.md @@ -0,0 +1,39 @@ +# Nano ID + +Nano ID logo by Anton Lovchikov + +**English** | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md) + +A tiny, secure, URL-friendly, unique string ID generator for JavaScript. + +> “An amazing level of senseless perfectionism, +> which is simply impossible not to respect.” + +* **Small.** 130 bytes (minified and gzipped). No dependencies. + [Size Limit] controls the size. +* **Fast.** It is 2 times faster than UUID. +* **Safe.** It uses hardware random generator. Can be used in clusters. +* **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`). + So ID size was reduced from 36 to 21 symbols. +* **Portable.** Nano ID was ported + to [20 programming languages](#other-programming-languages). + +```js +import { nanoid } from 'nanoid' +model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" +``` + +Supports modern browsers, IE [with Babel], Node.js and React Native. + +[online tool]: https://gitpod.io/#https://github.com/ai/nanoid/ +[with Babel]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/ +[Size Limit]: https://github.com/ai/size-limit + + + Sponsored by Evil Martians + + +## Docs +Read full docs **[here](https://github.com/ai/nanoid#readme)**. diff --git a/node_modules/nanoid/async/index.browser.cjs b/node_modules/nanoid/async/index.browser.cjs new file mode 100644 index 0000000000000000000000000000000000000000..80d18716feaad2c0afca754745dda540d47bacec --- /dev/null +++ b/node_modules/nanoid/async/index.browser.cjs @@ -0,0 +1,69 @@ +let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes)) + +let customAlphabet = (alphabet, defaultSize = 21) => { + // First, a bitmask is necessary to generate the ID. The bitmask makes bytes + // values closer to the alphabet size. The bitmask calculates the closest + // `2^31 - 1` number, which exceeds the alphabet size. + // For example, the bitmask for the alphabet size 30 is 31 (00011111). + // `Math.clz32` is not used, because it is not available in browsers. + let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 + // Though, the bitmask solution is not perfect since the bytes exceeding + // the alphabet size are refused. Therefore, to reliably generate the ID, + // the random bytes redundancy has to be satisfied. + + // Note: every hardware random generator call is performance expensive, + // because the system call for entropy collection takes a lot of time. + // So, to avoid additional system calls, extra bytes are requested in advance. + + // Next, a step determines how many random bytes to generate. + // The number of random bytes gets decided upon the ID size, mask, + // alphabet size, and magic number 1.6 (using 1.6 peaks at performance + // according to benchmarks). + + // `-~f => Math.ceil(f)` if f is a float + // `-~i => i + 1` if i is an integer + let step = -~((1.6 * mask * defaultSize) / alphabet.length) + + return async (size = defaultSize) => { + let id = '' + while (true) { + let bytes = crypto.getRandomValues(new Uint8Array(step)) + // A compact alternative for `for (var i = 0; i < step; i++)`. + let i = step | 0 + while (i--) { + // Adding `|| ''` refuses a random byte that exceeds the alphabet size. + id += alphabet[bytes[i] & mask] || '' + if (id.length === size) return id + } + } + } +} + +let nanoid = async (size = 21) => { + let id = '' + let bytes = crypto.getRandomValues(new Uint8Array((size |= 0))) + + // A compact alternative for `for (var i = 0; i < step; i++)`. + while (size--) { + // It is incorrect to use bytes exceeding the alphabet size. + // The following mask reduces the random byte in the 0-255 value + // range to the 0-63 value range. Therefore, adding hacks, such + // as empty string fallback or magic numbers, is unneccessary because + // the bitmask trims bytes down to the alphabet size. + let byte = bytes[size] & 63 + if (byte < 36) { + // `0-9a-z` + id += byte.toString(36) + } else if (byte < 62) { + // `A-Z` + id += (byte - 26).toString(36).toUpperCase() + } else if (byte < 63) { + id += '_' + } else { + id += '-' + } + } + return id +} + +module.exports = { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/index.browser.js b/node_modules/nanoid/async/index.browser.js new file mode 100644 index 0000000000000000000000000000000000000000..fbaa23005cdf3cb9b1e8dada338ec2854df6e9fa --- /dev/null +++ b/node_modules/nanoid/async/index.browser.js @@ -0,0 +1,34 @@ +let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes)) +let customAlphabet = (alphabet, defaultSize = 21) => { + let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 + let step = -~((1.6 * mask * defaultSize) / alphabet.length) + return async (size = defaultSize) => { + let id = '' + while (true) { + let bytes = crypto.getRandomValues(new Uint8Array(step)) + let i = step | 0 + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length === size) return id + } + } + } +} +let nanoid = async (size = 21) => { + let id = '' + let bytes = crypto.getRandomValues(new Uint8Array((size |= 0))) + while (size--) { + let byte = bytes[size] & 63 + if (byte < 36) { + id += byte.toString(36) + } else if (byte < 62) { + id += (byte - 26).toString(36).toUpperCase() + } else if (byte < 63) { + id += '_' + } else { + id += '-' + } + } + return id +} +export { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/index.cjs b/node_modules/nanoid/async/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..f1b0ad0267aa71bc29b00e869276ab7bd51b4f32 --- /dev/null +++ b/node_modules/nanoid/async/index.cjs @@ -0,0 +1,71 @@ +let crypto = require('crypto') + +let { urlAlphabet } = require('../url-alphabet/index.cjs') + +// `crypto.randomFill()` is a little faster than `crypto.randomBytes()`, +// because it is possible to use in combination with `Buffer.allocUnsafe()`. +let random = bytes => + new Promise((resolve, reject) => { + // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory. + // Memory flushing is unnecessary since the buffer allocation itself resets + // the memory with the new bytes. + crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { + if (err) { + reject(err) + } else { + resolve(buf) + } + }) + }) + +let customAlphabet = (alphabet, defaultSize = 21) => { + // First, a bitmask is necessary to generate the ID. The bitmask makes bytes + // values closer to the alphabet size. The bitmask calculates the closest + // `2^31 - 1` number, which exceeds the alphabet size. + // For example, the bitmask for the alphabet size 30 is 31 (00011111). + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + // Though, the bitmask solution is not perfect since the bytes exceeding + // the alphabet size are refused. Therefore, to reliably generate the ID, + // the random bytes redundancy has to be satisfied. + + // Note: every hardware random generator call is performance expensive, + // because the system call for entropy collection takes a lot of time. + // So, to avoid additional system calls, extra bytes are requested in advance. + + // Next, a step determines how many random bytes to generate. + // The number of random bytes gets decided upon the ID size, mask, + // alphabet size, and magic number 1.6 (using 1.6 peaks at performance + // according to benchmarks). + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + + let tick = (id, size = defaultSize) => + random(step).then(bytes => { + // A compact alternative for `for (var i = 0; i < step; i++)`. + let i = step + while (i--) { + // Adding `|| ''` refuses a random byte that exceeds the alphabet size. + id += alphabet[bytes[i] & mask] || '' + if (id.length >= size) return id + } + return tick(id, size) + }) + + return size => tick('', size) +} + +let nanoid = (size = 21) => + random((size |= 0)).then(bytes => { + let id = '' + // A compact alternative for `for (var i = 0; i < step; i++)`. + while (size--) { + // It is incorrect to use bytes exceeding the alphabet size. + // The following mask reduces the random byte in the 0-255 value + // range to the 0-63 value range. Therefore, adding hacks, such + // as empty string fallback or magic numbers, is unneccessary because + // the bitmask trims bytes down to the alphabet size. + id += urlAlphabet[bytes[size] & 63] + } + return id + }) + +module.exports = { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/index.d.ts b/node_modules/nanoid/async/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e919658b82e66e3bd39800232da5a469c8d13a8 --- /dev/null +++ b/node_modules/nanoid/async/index.d.ts @@ -0,0 +1,56 @@ +/** + * Generate secure URL-friendly unique ID. The non-blocking version. + * + * By default, the ID will have 21 symbols to have a collision probability + * similar to UUID v4. + * + * ```js + * import { nanoid } from 'nanoid/async' + * nanoid().then(id => { + * model.id = id + * }) + * ``` + * + * @param size Size of the ID. The default size is 21. + * @returns A promise with a random string. + */ +export function nanoid(size?: number): Promise + +/** + * A low-level function. + * Generate secure unique ID with custom alphabet. The non-blocking version. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * @param alphabet Alphabet used to generate the ID. + * @param defaultSize Size of the ID. The default size is 21. + * @returns A function that returns a promise with a random string. + * + * ```js + * import { customAlphabet } from 'nanoid/async' + * const nanoid = customAlphabet('0123456789абвгдеё', 5) + * nanoid().then(id => { + * model.id = id //=> "8ё56а" + * }) + * ``` + */ +export function customAlphabet( + alphabet: string, + defaultSize?: number +): (size?: number) => Promise + +/** + * Generate an array of random bytes collected from hardware noise. + * + * ```js + * import { random } from 'nanoid/async' + * random(5).then(bytes => { + * bytes //=> [10, 67, 212, 67, 89] + * }) + * ``` + * + * @param bytes Size of the array. + * @returns A promise with a random bytes array. + */ +export function random(bytes: number): Promise diff --git a/node_modules/nanoid/async/index.js b/node_modules/nanoid/async/index.js new file mode 100644 index 0000000000000000000000000000000000000000..cec454a2a1986932acb22141113ec0c852a59f9b --- /dev/null +++ b/node_modules/nanoid/async/index.js @@ -0,0 +1,35 @@ +import crypto from 'crypto' +import { urlAlphabet } from '../url-alphabet/index.js' +let random = bytes => + new Promise((resolve, reject) => { + crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { + if (err) { + reject(err) + } else { + resolve(buf) + } + }) + }) +let customAlphabet = (alphabet, defaultSize = 21) => { + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + let tick = (id, size = defaultSize) => + random(step).then(bytes => { + let i = step + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length >= size) return id + } + return tick(id, size) + }) + return size => tick('', size) +} +let nanoid = (size = 21) => + random((size |= 0)).then(bytes => { + let id = '' + while (size--) { + id += urlAlphabet[bytes[size] & 63] + } + return id + }) +export { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/index.native.js b/node_modules/nanoid/async/index.native.js new file mode 100644 index 0000000000000000000000000000000000000000..7c1d6f39e34d731715f551fa8a6c7520b04cda82 --- /dev/null +++ b/node_modules/nanoid/async/index.native.js @@ -0,0 +1,26 @@ +import { getRandomBytesAsync } from 'expo-random' +import { urlAlphabet } from '../url-alphabet/index.js' +let random = getRandomBytesAsync +let customAlphabet = (alphabet, defaultSize = 21) => { + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + let tick = (id, size = defaultSize) => + random(step).then(bytes => { + let i = step + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length >= size) return id + } + return tick(id, size) + }) + return size => tick('', size) +} +let nanoid = (size = 21) => + random((size |= 0)).then(bytes => { + let id = '' + while (size--) { + id += urlAlphabet[bytes[size] & 63] + } + return id + }) +export { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/package.json b/node_modules/nanoid/async/package.json new file mode 100644 index 0000000000000000000000000000000000000000..578cdb4cb9babb17e4e08b4f6a30c2e195d2afed --- /dev/null +++ b/node_modules/nanoid/async/package.json @@ -0,0 +1,12 @@ +{ + "type": "module", + "main": "index.cjs", + "module": "index.js", + "react-native": { + "./index.js": "./index.native.js" + }, + "browser": { + "./index.js": "./index.browser.js", + "./index.cjs": "./index.browser.cjs" + } +} \ No newline at end of file diff --git a/node_modules/nanoid/bin/nanoid.cjs b/node_modules/nanoid/bin/nanoid.cjs new file mode 100644 index 0000000000000000000000000000000000000000..c76db0faa81f6d683c4a18a212f804fb70cf8143 --- /dev/null +++ b/node_modules/nanoid/bin/nanoid.cjs @@ -0,0 +1,55 @@ +#!/usr/bin/env node + +let { nanoid, customAlphabet } = require('..') + +function print(msg) { + process.stdout.write(msg + '\n') +} + +function error(msg) { + process.stderr.write(msg + '\n') + process.exit(1) +} + +if (process.argv.includes('--help') || process.argv.includes('-h')) { + print(` + Usage + $ nanoid [options] + + Options + -s, --size Generated ID size + -a, --alphabet Alphabet to use + -h, --help Show this help + + Examples + $ nanoid --s 15 + S9sBF77U6sDB8Yg + + $ nanoid --size 10 --alphabet abc + bcabababca`) + process.exit() +} + +let alphabet, size +for (let i = 2; i < process.argv.length; i++) { + let arg = process.argv[i] + if (arg === '--size' || arg === '-s') { + size = Number(process.argv[i + 1]) + i += 1 + if (Number.isNaN(size) || size <= 0) { + error('Size must be positive integer') + } + } else if (arg === '--alphabet' || arg === '-a') { + alphabet = process.argv[i + 1] + i += 1 + } else { + error('Unknown argument ' + arg) + } +} + +if (alphabet) { + let customNanoid = customAlphabet(alphabet, size) + print(customNanoid()) +} else { + print(nanoid(size)) +} diff --git a/node_modules/nanoid/index.browser.cjs b/node_modules/nanoid/index.browser.cjs new file mode 100644 index 0000000000000000000000000000000000000000..d21a91fcf3d4fb63515c79b3a47f0433c3ca1e4b --- /dev/null +++ b/node_modules/nanoid/index.browser.cjs @@ -0,0 +1,72 @@ +// This file replaces `index.js` in bundlers like webpack or Rollup, +// according to `browser` config in `package.json`. + +let { urlAlphabet } = require('./url-alphabet/index.cjs') + +let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) + +let customRandom = (alphabet, defaultSize, getRandom) => { + // First, a bitmask is necessary to generate the ID. The bitmask makes bytes + // values closer to the alphabet size. The bitmask calculates the closest + // `2^31 - 1` number, which exceeds the alphabet size. + // For example, the bitmask for the alphabet size 30 is 31 (00011111). + // `Math.clz32` is not used, because it is not available in browsers. + let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 + // Though, the bitmask solution is not perfect since the bytes exceeding + // the alphabet size are refused. Therefore, to reliably generate the ID, + // the random bytes redundancy has to be satisfied. + + // Note: every hardware random generator call is performance expensive, + // because the system call for entropy collection takes a lot of time. + // So, to avoid additional system calls, extra bytes are requested in advance. + + // Next, a step determines how many random bytes to generate. + // The number of random bytes gets decided upon the ID size, mask, + // alphabet size, and magic number 1.6 (using 1.6 peaks at performance + // according to benchmarks). + + // `-~f => Math.ceil(f)` if f is a float + // `-~i => i + 1` if i is an integer + let step = -~((1.6 * mask * defaultSize) / alphabet.length) + + return (size = defaultSize) => { + let id = '' + while (true) { + let bytes = getRandom(step) + // A compact alternative for `for (var i = 0; i < step; i++)`. + let j = step | 0 + while (j--) { + // Adding `|| ''` refuses a random byte that exceeds the alphabet size. + id += alphabet[bytes[j] & mask] || '' + if (id.length === size) return id + } + } + } +} + +let customAlphabet = (alphabet, size = 21) => + customRandom(alphabet, size, random) + +let nanoid = (size = 21) => + crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => { + // It is incorrect to use bytes exceeding the alphabet size. + // The following mask reduces the random byte in the 0-255 value + // range to the 0-63 value range. Therefore, adding hacks, such + // as empty string fallback or magic numbers, is unneccessary because + // the bitmask trims bytes down to the alphabet size. + byte &= 63 + if (byte < 36) { + // `0-9a-z` + id += byte.toString(36) + } else if (byte < 62) { + // `A-Z` + id += (byte - 26).toString(36).toUpperCase() + } else if (byte > 62) { + id += '-' + } else { + id += '_' + } + return id + }, '') + +module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/index.browser.js b/node_modules/nanoid/index.browser.js new file mode 100644 index 0000000000000000000000000000000000000000..7d3b876caefe8df0d4856199d0de5ff1ddf45cae --- /dev/null +++ b/node_modules/nanoid/index.browser.js @@ -0,0 +1,34 @@ +import { urlAlphabet } from './url-alphabet/index.js' +let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) +let customRandom = (alphabet, defaultSize, getRandom) => { + let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 + let step = -~((1.6 * mask * defaultSize) / alphabet.length) + return (size = defaultSize) => { + let id = '' + while (true) { + let bytes = getRandom(step) + let j = step | 0 + while (j--) { + id += alphabet[bytes[j] & mask] || '' + if (id.length === size) return id + } + } + } +} +let customAlphabet = (alphabet, size = 21) => + customRandom(alphabet, size, random) +let nanoid = (size = 21) => + crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => { + byte &= 63 + if (byte < 36) { + id += byte.toString(36) + } else if (byte < 62) { + id += (byte - 26).toString(36).toUpperCase() + } else if (byte > 62) { + id += '-' + } else { + id += '_' + } + return id + }, '') +export { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/index.cjs b/node_modules/nanoid/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..0623c668e9fd0ccb65f05c33bead51a420f458aa --- /dev/null +++ b/node_modules/nanoid/index.cjs @@ -0,0 +1,86 @@ +let crypto = require('crypto') + +let { urlAlphabet } = require('./url-alphabet/index.cjs') + +// It is best to make fewer, larger requests to the crypto module to +// avoid system call overhead. So, random numbers are generated in a +// pool. The pool is a Buffer that is larger than the initial random +// request size by this multiplier. The pool is enlarged if subsequent +// requests exceed the maximum buffer size. +const POOL_SIZE_MULTIPLIER = 128 +let pool, poolOffset + +let fillPool = bytes => { + if (bytes < 0 || bytes > 1024) throw new RangeError('Wrong ID size') + if (!pool || pool.length < bytes) { + pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER) + crypto.randomFillSync(pool) + poolOffset = 0 + } else if (poolOffset + bytes > pool.length) { + crypto.randomFillSync(pool) + poolOffset = 0 + } + poolOffset += bytes +} + +let random = bytes => { + // `|=` convert `bytes` to number to prevent `valueOf` abusing and pool pollution + fillPool((bytes |= 0)) + return pool.subarray(poolOffset - bytes, poolOffset) +} + +let customRandom = (alphabet, defaultSize, getRandom) => { + // First, a bitmask is necessary to generate the ID. The bitmask makes bytes + // values closer to the alphabet size. The bitmask calculates the closest + // `2^31 - 1` number, which exceeds the alphabet size. + // For example, the bitmask for the alphabet size 30 is 31 (00011111). + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + // Though, the bitmask solution is not perfect since the bytes exceeding + // the alphabet size are refused. Therefore, to reliably generate the ID, + // the random bytes redundancy has to be satisfied. + + // Note: every hardware random generator call is performance expensive, + // because the system call for entropy collection takes a lot of time. + // So, to avoid additional system calls, extra bytes are requested in advance. + + // Next, a step determines how many random bytes to generate. + // The number of random bytes gets decided upon the ID size, mask, + // alphabet size, and magic number 1.6 (using 1.6 peaks at performance + // according to benchmarks). + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + + return (size = defaultSize) => { + let id = '' + while (true) { + let bytes = getRandom(step) + // A compact alternative for `for (let i = 0; i < step; i++)`. + let i = step + while (i--) { + // Adding `|| ''` refuses a random byte that exceeds the alphabet size. + id += alphabet[bytes[i] & mask] || '' + if (id.length === size) return id + } + } + } +} + +let customAlphabet = (alphabet, size = 21) => + customRandom(alphabet, size, random) + +let nanoid = (size = 21) => { + // `|=` convert `size` to number to prevent `valueOf` abusing and pool pollution + fillPool((size |= 0)) + let id = '' + // We are reading directly from the random pool to avoid creating new array + for (let i = poolOffset - size; i < poolOffset; i++) { + // It is incorrect to use bytes exceeding the alphabet size. + // The following mask reduces the random byte in the 0-255 value + // range to the 0-63 value range. Therefore, adding hacks, such + // as empty string fallback or magic numbers, is unneccessary because + // the bitmask trims bytes down to the alphabet size. + id += urlAlphabet[pool[i] & 63] + } + return id +} + +module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/index.d.cts b/node_modules/nanoid/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..3e111a39de010f548d397f06f8f964191834b869 --- /dev/null +++ b/node_modules/nanoid/index.d.cts @@ -0,0 +1,91 @@ +/** + * Generate secure URL-friendly unique ID. + * + * By default, the ID will have 21 symbols to have a collision probability + * similar to UUID v4. + * + * ```js + * import { nanoid } from 'nanoid' + * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" + * ``` + * + * @param size Size of the ID. The default size is 21. + * @returns A random string. + */ +export function nanoid(size?: number): string + +/** + * Generate secure unique ID with custom alphabet. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * @param alphabet Alphabet used to generate the ID. + * @param defaultSize Size of the ID. The default size is 21. + * @returns A random string generator. + * + * ```js + * const { customAlphabet } = require('nanoid') + * const nanoid = customAlphabet('0123456789абвгдеё', 5) + * nanoid() //=> "8ё56а" + * ``` + */ +export function customAlphabet( + alphabet: string, + defaultSize?: number +): (size?: number) => string + +/** + * Generate unique ID with custom random generator and alphabet. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * ```js + * import { customRandom } from 'nanoid/format' + * + * const nanoid = customRandom('abcdef', 5, size => { + * const random = [] + * for (let i = 0; i < size; i++) { + * random.push(randomByte()) + * } + * return random + * }) + * + * nanoid() //=> "fbaef" + * ``` + * + * @param alphabet Alphabet used to generate a random string. + * @param size Size of the random string. + * @param random A random bytes generator. + * @returns A random string generator. + */ +export function customRandom( + alphabet: string, + size: number, + random: (bytes: number) => Uint8Array +): () => string + +/** + * URL safe symbols. + * + * ```js + * import { urlAlphabet } from 'nanoid' + * const nanoid = customAlphabet(urlAlphabet, 10) + * nanoid() //=> "Uakgb_J5m9" + * ``` + */ +export const urlAlphabet: string + +/** + * Generate an array of random bytes collected from hardware noise. + * + * ```js + * import { customRandom, random } from 'nanoid' + * const nanoid = customRandom("abcdef", 5, random) + * ``` + * + * @param bytes Size of the array. + * @returns An array of random bytes. + */ +export function random(bytes: number): Uint8Array diff --git a/node_modules/nanoid/index.d.ts b/node_modules/nanoid/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e111a39de010f548d397f06f8f964191834b869 --- /dev/null +++ b/node_modules/nanoid/index.d.ts @@ -0,0 +1,91 @@ +/** + * Generate secure URL-friendly unique ID. + * + * By default, the ID will have 21 symbols to have a collision probability + * similar to UUID v4. + * + * ```js + * import { nanoid } from 'nanoid' + * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" + * ``` + * + * @param size Size of the ID. The default size is 21. + * @returns A random string. + */ +export function nanoid(size?: number): string + +/** + * Generate secure unique ID with custom alphabet. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * @param alphabet Alphabet used to generate the ID. + * @param defaultSize Size of the ID. The default size is 21. + * @returns A random string generator. + * + * ```js + * const { customAlphabet } = require('nanoid') + * const nanoid = customAlphabet('0123456789абвгдеё', 5) + * nanoid() //=> "8ё56а" + * ``` + */ +export function customAlphabet( + alphabet: string, + defaultSize?: number +): (size?: number) => string + +/** + * Generate unique ID with custom random generator and alphabet. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * ```js + * import { customRandom } from 'nanoid/format' + * + * const nanoid = customRandom('abcdef', 5, size => { + * const random = [] + * for (let i = 0; i < size; i++) { + * random.push(randomByte()) + * } + * return random + * }) + * + * nanoid() //=> "fbaef" + * ``` + * + * @param alphabet Alphabet used to generate a random string. + * @param size Size of the random string. + * @param random A random bytes generator. + * @returns A random string generator. + */ +export function customRandom( + alphabet: string, + size: number, + random: (bytes: number) => Uint8Array +): () => string + +/** + * URL safe symbols. + * + * ```js + * import { urlAlphabet } from 'nanoid' + * const nanoid = customAlphabet(urlAlphabet, 10) + * nanoid() //=> "Uakgb_J5m9" + * ``` + */ +export const urlAlphabet: string + +/** + * Generate an array of random bytes collected from hardware noise. + * + * ```js + * import { customRandom, random } from 'nanoid' + * const nanoid = customRandom("abcdef", 5, random) + * ``` + * + * @param bytes Size of the array. + * @returns An array of random bytes. + */ +export function random(bytes: number): Uint8Array diff --git a/node_modules/nanoid/index.js b/node_modules/nanoid/index.js new file mode 100644 index 0000000000000000000000000000000000000000..186d3399c6a00c89d1daf3d5b537152b1973e5d4 --- /dev/null +++ b/node_modules/nanoid/index.js @@ -0,0 +1,46 @@ +import crypto from 'crypto' +import { urlAlphabet } from './url-alphabet/index.js' +const POOL_SIZE_MULTIPLIER = 128 +let pool, poolOffset +let fillPool = bytes => { + if (bytes < 0 || bytes > 1024) throw new RangeError('Wrong ID size') + if (!pool || pool.length < bytes) { + pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER) + crypto.randomFillSync(pool) + poolOffset = 0 + } else if (poolOffset + bytes > pool.length) { + crypto.randomFillSync(pool) + poolOffset = 0 + } + poolOffset += bytes +} +let random = bytes => { + fillPool((bytes |= 0)) + return pool.subarray(poolOffset - bytes, poolOffset) +} +let customRandom = (alphabet, defaultSize, getRandom) => { + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + return (size = defaultSize) => { + let id = '' + while (true) { + let bytes = getRandom(step) + let i = step + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length === size) return id + } + } + } +} +let customAlphabet = (alphabet, size = 21) => + customRandom(alphabet, size, random) +let nanoid = (size = 21) => { + fillPool((size |= 0)) + let id = '' + for (let i = poolOffset - size; i < poolOffset; i++) { + id += urlAlphabet[pool[i] & 63] + } + return id +} +export { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/nanoid.js b/node_modules/nanoid/nanoid.js new file mode 100644 index 0000000000000000000000000000000000000000..ec242eadc85e4b0ef546c8fdc771f7e9d7d2f081 --- /dev/null +++ b/node_modules/nanoid/nanoid.js @@ -0,0 +1 @@ +export let nanoid=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce(((t,e)=>t+=(e&=63)<36?e.toString(36):e<62?(e-26).toString(36).toUpperCase():e<63?"_":"-"),""); \ No newline at end of file diff --git a/node_modules/nanoid/non-secure/index.cjs b/node_modules/nanoid/non-secure/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..d51fcb6cedb809967ece5cc568f658245fe95f58 --- /dev/null +++ b/node_modules/nanoid/non-secure/index.cjs @@ -0,0 +1,34 @@ +// This alphabet uses `A-Za-z0-9_-` symbols. +// The order of characters is optimized for better gzip and brotli compression. +// References to the same file (works both for gzip and brotli): +// `'use`, `andom`, and `rict'` +// References to the brotli default dictionary: +// `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf` +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' + +let customAlphabet = (alphabet, defaultSize = 21) => { + return (size = defaultSize) => { + let id = '' + // A compact alternative for `for (var i = 0; i < step; i++)`. + let i = size | 0 + while (i--) { + // `| 0` is more compact and faster than `Math.floor()`. + id += alphabet[(Math.random() * alphabet.length) | 0] + } + return id + } +} + +let nanoid = (size = 21) => { + let id = '' + // A compact alternative for `for (var i = 0; i < step; i++)`. + let i = size | 0 + while (i--) { + // `| 0` is more compact and faster than `Math.floor()`. + id += urlAlphabet[(Math.random() * 64) | 0] + } + return id +} + +module.exports = { nanoid, customAlphabet } diff --git a/node_modules/nanoid/non-secure/index.d.ts b/node_modules/nanoid/non-secure/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4965322d636016d678fccdd94c3aacdf1fc50075 --- /dev/null +++ b/node_modules/nanoid/non-secure/index.d.ts @@ -0,0 +1,33 @@ +/** + * Generate URL-friendly unique ID. This method uses the non-secure + * predictable random generator with bigger collision probability. + * + * ```js + * import { nanoid } from 'nanoid/non-secure' + * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" + * ``` + * + * @param size Size of the ID. The default size is 21. + * @returns A random string. + */ +export function nanoid(size?: number): string + +/** + * Generate a unique ID based on a custom alphabet. + * This method uses the non-secure predictable random generator + * with bigger collision probability. + * + * @param alphabet Alphabet used to generate the ID. + * @param defaultSize Size of the ID. The default size is 21. + * @returns A random string generator. + * + * ```js + * import { customAlphabet } from 'nanoid/non-secure' + * const nanoid = customAlphabet('0123456789абвгдеё', 5) + * model.id = //=> "8ё56а" + * ``` + */ +export function customAlphabet( + alphabet: string, + defaultSize?: number +): (size?: number) => string diff --git a/node_modules/nanoid/non-secure/index.js b/node_modules/nanoid/non-secure/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2ea5827c627331d5d7a2e38e0acca3b9824a668d --- /dev/null +++ b/node_modules/nanoid/non-secure/index.js @@ -0,0 +1,21 @@ +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' +let customAlphabet = (alphabet, defaultSize = 21) => { + return (size = defaultSize) => { + let id = '' + let i = size | 0 + while (i--) { + id += alphabet[(Math.random() * alphabet.length) | 0] + } + return id + } +} +let nanoid = (size = 21) => { + let id = '' + let i = size | 0 + while (i--) { + id += urlAlphabet[(Math.random() * 64) | 0] + } + return id +} +export { nanoid, customAlphabet } diff --git a/node_modules/nanoid/non-secure/package.json b/node_modules/nanoid/non-secure/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9930d6ad1671e19bfddbdeeb9bbcdeab83dc00ba --- /dev/null +++ b/node_modules/nanoid/non-secure/package.json @@ -0,0 +1,6 @@ +{ + "type": "module", + "main": "index.cjs", + "module": "index.js", + "react-native": "index.js" +} \ No newline at end of file diff --git a/node_modules/nanoid/package.json b/node_modules/nanoid/package.json new file mode 100644 index 0000000000000000000000000000000000000000..416c53f21f051c9934f50ad6e4bf3cb13f22d288 --- /dev/null +++ b/node_modules/nanoid/package.json @@ -0,0 +1,89 @@ +{ + "name": "nanoid", + "version": "3.3.12", + "description": "A tiny (116 bytes), secure URL-friendly unique string ID generator", + "keywords": [ + "uuid", + "random", + "id", + "url" + ], + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "author": "Andrey Sitnik ", + "license": "MIT", + "repository": "ai/nanoid", + "browser": { + "./index.js": "./index.browser.js", + "./async/index.js": "./async/index.browser.js", + "./async/index.cjs": "./async/index.browser.cjs", + "./index.cjs": "./index.browser.cjs" + }, + "react-native": "index.js", + "bin": "./bin/nanoid.cjs", + "sideEffects": false, + "types": "./index.d.ts", + "type": "module", + "main": "index.cjs", + "module": "index.js", + "exports": { + ".": { + "react-native": "./index.browser.js", + "browser": "./index.browser.js", + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + }, + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "default": "./index.js" + }, + "./package.json": "./package.json", + "./async/package.json": "./async/package.json", + "./async": { + "browser": "./async/index.browser.js", + "require": { + "types": "./index.d.cts", + "default": "./async/index.cjs" + }, + "import": { + "types": "./index.d.ts", + "default": "./async/index.js" + }, + "default": "./async/index.js" + }, + "./non-secure/package.json": "./non-secure/package.json", + "./non-secure": { + "require": { + "types": "./index.d.cts", + "default": "./non-secure/index.cjs" + }, + "import": { + "types": "./index.d.ts", + "default": "./non-secure/index.js" + }, + "default": "./non-secure/index.js" + }, + "./url-alphabet/package.json": "./url-alphabet/package.json", + "./url-alphabet": { + "require": { + "types": "./index.d.cts", + "default": "./url-alphabet/index.cjs" + }, + "import": { + "types": "./index.d.ts", + "default": "./url-alphabet/index.js" + }, + "default": "./url-alphabet/index.js" + } + } +} diff --git a/node_modules/nanoid/url-alphabet/index.cjs b/node_modules/nanoid/url-alphabet/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..a332f0bff69ed88326a611860a8e5a8cdb881dc4 --- /dev/null +++ b/node_modules/nanoid/url-alphabet/index.cjs @@ -0,0 +1,7 @@ +// This alphabet uses `A-Za-z0-9_-` symbols. +// The order of characters is optimized for better gzip and brotli compression. +// Same as in non-secure/index.js +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' + +module.exports = { urlAlphabet } diff --git a/node_modules/nanoid/url-alphabet/index.js b/node_modules/nanoid/url-alphabet/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c2782e592e541a8ec8bd07038e997e63a16beb70 --- /dev/null +++ b/node_modules/nanoid/url-alphabet/index.js @@ -0,0 +1,3 @@ +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' +export { urlAlphabet } diff --git a/node_modules/nanoid/url-alphabet/package.json b/node_modules/nanoid/url-alphabet/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9930d6ad1671e19bfddbdeeb9bbcdeab83dc00ba --- /dev/null +++ b/node_modules/nanoid/url-alphabet/package.json @@ -0,0 +1,6 @@ +{ + "type": "module", + "main": "index.cjs", + "module": "index.js", + "react-native": "index.js" +} \ No newline at end of file diff --git a/node_modules/napi-build-utils/.github/workflows/run-npm-tests.yml b/node_modules/napi-build-utils/.github/workflows/run-npm-tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..3298868e26bfbb8a700da74a67eafca3e51b3dcf --- /dev/null +++ b/node_modules/napi-build-utils/.github/workflows/run-npm-tests.yml @@ -0,0 +1,31 @@ +name: Run npm Tests + +on: + workflow_dispatch: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +jobs: + test: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [22, 23] + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Set up Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node-version }} + + - name: Install dependencies + run: npm install + + - name: Run tests + run: npm test \ No newline at end of file diff --git a/node_modules/napi-build-utils/LICENSE b/node_modules/napi-build-utils/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8e0248a4e3012dff539713b61b9c80d9c04c1fdf --- /dev/null +++ b/node_modules/napi-build-utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 inspiredware + +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. diff --git a/node_modules/napi-build-utils/README.md b/node_modules/napi-build-utils/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7c29b680aabb76cb5c437bd61a075ba8d370fc39 --- /dev/null +++ b/node_modules/napi-build-utils/README.md @@ -0,0 +1,52 @@ +# napi-build-utils + +[![npm](https://img.shields.io/npm/v/napi-build-utils.svg)](https://www.npmjs.com/package/napi-build-utils) +![Node version](https://img.shields.io/node/v/prebuild.svg) +![Build Status](https://github.com/inspiredware/napi-build-utils/actions/workflows/run-npm-tests.yml/badge.svg) +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) + +A set of utilities to assist developers of tools that build [Node-API](https://nodejs.org/api/n-api.html#n_api_n_api) native add-ons. + +## Background + +This module is targeted to developers creating tools that build Node-API native add-ons. + +It implements a set of functions that aid in determining the Node-API version supported by the currently running Node instance and the set of Node-API versions against which the Node-API native add-on is designed to be built. Other functions determine whether a particular Node-API version can be built and can issue console warnings for unsupported Node-API versions. + +Unlike the modules this code is designed to facilitate building, this module is written entirely in JavaScript. + +## Quick start + +```bash +npm install napi-build-utils +``` + +The module exports a set of functions documented [here](./index.md). For example: + +```javascript +var napiBuildUtils = require('napi-build-utils'); +var napiVersion = napiBuildUtils.getNapiVersion(); // Node-API version supported by Node, or undefined. +``` + +## Declaring supported Node-API versions + +Native modules that are designed to work with [Node-API](https://nodejs.org/api/n-api.html#n_api_n_api) must explicitly declare the Node-API version(s) against which they are coded to build. This is accomplished by including a `binary.napi_versions` property in the module's `package.json` file. For example: + +```json +"binary": { + "napi_versions": [2,3] +} +``` + +In the absence of a need to compile against a specific Node-API version, the value `3` is a good choice as this is the Node-API version that was supported when Node-API left experimental status. + +Modules that are built against a specific Node-API version will continue to operate indefinitely, even as later versions of Node-API are introduced. + +## History + +**v2.0.0** This version was introduced to address a limitation when the Node-API version reached `10` in NodeJS `v23.6.0`. There was no change in the API, but a SemVer bump to `2.0.0` was made out of an abundance of caution. + +## Support + +If you run into problems or limitations, please file an issue and we'll take a look. Pull requests are also welcome. diff --git a/node_modules/napi-build-utils/index.js b/node_modules/napi-build-utils/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d143d5d05c9a1d1502f369356c921ca7e3f0fd43 --- /dev/null +++ b/node_modules/napi-build-utils/index.js @@ -0,0 +1,214 @@ +'use strict' +// Copyright (c) 2018 inspiredware + +var path = require('path') +var pkg = require(path.resolve('package.json')) + +var versionArray = process.version + .substr(1) + .replace(/-.*$/, '') + .split('.') + .map(function (item) { + return +item + }) + +/** + * + * A set of utilities to assist developers of tools that build + * [N-API](https://nodejs.org/api/n-api.html#n_api_n_api) native add-ons. + * + * The main repository can be found + * [here](https://github.com/inspiredware/napi-build-utils#napi-build-utils). + * + * @module napi-build-utils + */ + +/** + * Implements a consistent name of `napi` for N-API runtimes. + * + * @param {string} runtime The runtime string. + * @returns {boolean} + */ +exports.isNapiRuntime = function (runtime) { + return runtime === 'napi' +} + +/** + * Determines whether the specified N-API version is supported + * by both the currently running Node instance and the package. + * + * @param {string} napiVersion The N-API version to check. + * @returns {boolean} + */ +exports.isSupportedVersion = function (napiVersion) { + var version = parseInt(napiVersion, 10) + return version <= exports.getNapiVersion() && exports.packageSupportsVersion(version) +} + +/** + * Determines whether the specified N-API version is supported by the package. + * The N-API version must be present in the `package.json` + * `binary.napi_versions` array. + * + * @param {number} napiVersion The N-API version to check. + * @returns {boolean} + * @private + */ +exports.packageSupportsVersion = function (napiVersion) { + if (pkg.binary && pkg.binary.napi_versions && + pkg.binary.napi_versions instanceof Array) { // integer array + for (var i = 0; i < pkg.binary.napi_versions.length; i++) { + if (pkg.binary.napi_versions[i] === napiVersion) return true + }; + }; + return false +} + +/** + * Issues a warning to the supplied log if the N-API version is not supported + * by the current Node instance or if the N-API version is not supported + * by the package. + * + * @param {string} napiVersion The N-API version to check. + * @param {Object} log The log object to which the warnings are to be issued. + * Must implement the `warn` method. + */ +exports.logUnsupportedVersion = function (napiVersion, log) { + if (!exports.isSupportedVersion(napiVersion)) { + if (exports.packageSupportsVersion(napiVersion)) { + log.warn('This Node instance does not support N-API version ' + napiVersion) + } else { + log.warn('This package does not support N-API version ' + napiVersion) + } + } +} + +/** + * Issues warnings to the supplied log for those N-API versions not supported + * by the N-API runtime or the package. + * + * Note that this function is specific to the + * [`prebuild`](https://github.com/prebuild/prebuild#prebuild) package. + * + * `target` is the list of targets to be built and is determined in one of + * three ways from the command line arguments: + * (1) `--target` specifies a specific target to build. + * (2) `--all` specifies all N-API versions supported by the package. + * (3) Neither of these specifies to build the single "best version available." + * + * `prebuild` is an array of objects in the form `{runtime: 'napi', target: '2'}`. + * The array contains the list of N-API versions that are supported by both the + * package being built and the currently running Node instance. + * + * The objective of this function is to issue a warning for those items that appear + * in the `target` argument but not in the `prebuild` argument. + * If a specific target is supported by the package (`packageSupportsVersion`) but + * but note in `prebuild`, the assumption is that the target is not supported by + * Node. + * + * @param {(Array|string)} target The N-API version(s) to check. Target is + * @param {Array} prebuild A config object created by the `prebuild` package. + * @param {Object} log The log object to which the warnings are to be issued. + * Must implement the `warn` method. + * @private + */ +exports.logMissingNapiVersions = function (target, prebuild, log) { + if (exports.getNapiBuildVersions()) { + var targets = [].concat(target) + targets.forEach(function (napiVersion) { + if (!prebuildExists(prebuild, napiVersion)) { + if (exports.packageSupportsVersion(parseInt(napiVersion, 10))) { + log.warn('This Node instance does not support N-API version ' + napiVersion) + } else { + log.warn('This package does not support N-API version ' + napiVersion) + } + } + }) + } else { + log.error('Builds with runtime \'napi\' require a binary.napi_versions ' + + 'property on the package.json file') + } +} + +/** + * Determines whether the specified N-API version exists in the prebuild + * configuration object. + * + * Note that this function is specific to the `prebuild` and `prebuild-install` + * packages. + * + * @param {Object} prebuild A config object created by the `prebuild` package. + * @param {string} napiVersion The N-APi version to be checked. + * @return {boolean} + * @private + */ +var prebuildExists = function (prebuild, napiVersion) { + if (prebuild) { + for (var i = 0; i < prebuild.length; i++) { + if (prebuild[i].target === napiVersion) return true + } + } + return false +} + +/** + * Returns the best N-API version to build given the highest N-API + * version supported by the current Node instance and the N-API versions + * supported by the package, or undefined if a suitable N-API version + * cannot be determined. + * + * The best build version is the greatest N-API version supported by + * the package that is less than or equal to the highest N-API version + * supported by the current Node instance. + * + * @returns {number|undefined} + */ +exports.getBestNapiBuildVersion = function () { + var bestNapiBuildVersion = 0 + var napiBuildVersions = exports.getNapiBuildVersions(pkg) // array of integer strings + if (napiBuildVersions) { + var ourNapiVersion = exports.getNapiVersion() + napiBuildVersions.forEach(function (napiBuildVersionStr) { + var napiBuildVersion = parseInt(napiBuildVersionStr, 10) + if (napiBuildVersion > bestNapiBuildVersion && + napiBuildVersion <= ourNapiVersion) { + bestNapiBuildVersion = napiBuildVersion + } + }) + } + return bestNapiBuildVersion === 0 ? undefined : bestNapiBuildVersion +} + +/** + * Returns an array of N-API versions supported by the package. + * + * @returns {Array|undefined} + */ +exports.getNapiBuildVersions = function () { + var napiBuildVersions = [] + // remove duplicates, convert to text + if (pkg.binary && pkg.binary.napi_versions) { + pkg.binary.napi_versions.forEach(function (napiVersion) { + var duplicated = napiBuildVersions.indexOf('' + napiVersion) !== -1 + if (!duplicated) { + napiBuildVersions.push('' + napiVersion) + } + }) + } + return napiBuildVersions.length ? napiBuildVersions : undefined +} + +/** + * Returns the highest N-API version supported by the current node instance + * or undefined if N-API is not supported. + * + * @returns {string|undefined} + */ +exports.getNapiVersion = function () { + var version = process.versions.napi // integer string, can be undefined + if (!version) { // this code should never need to be updated + if (versionArray[0] === 9 && versionArray[1] >= 3) version = '2' // 9.3.0+ + else if (versionArray[0] === 8) version = '1' // 8.0.0+ + } + return version +} diff --git a/node_modules/napi-build-utils/index.md b/node_modules/napi-build-utils/index.md new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/napi-build-utils/package.json b/node_modules/napi-build-utils/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ad15183cbd7aa1de0d991fbf21c098aaf01908ec --- /dev/null +++ b/node_modules/napi-build-utils/package.json @@ -0,0 +1,42 @@ +{ + "name": "napi-build-utils", + "version": "2.0.0", + "description": "A set of utilities to assist developers of tools that build N-API native add-ons", + "main": "index.js", + "scripts": { + "doc": "jsdoc2md index.js >index.md", + "test": "mocha test/ && npm run lint", + "lint": "standard", + "prepublishOnly": "npm run test" + }, + "keywords": [ + "n-api", + "prebuild", + "prebuild-install" + ], + "author": "Jim Schlight", + "license": "MIT", + "homepage": "https://github.com/inspiredware/napi-build-utils#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/inspiredware/napi-build-utils.git" + }, + "bugs": { + "url": "https://github.com/inspiredware/napi-build-utils/issues" + }, + "devDependencies": { + "chai": "^4.1.2", + "jsdoc-to-markdown": "^4.0.1", + "mocha": "^5.2.0", + "standard": "^12.0.1" + }, + "binary": { + "note": "napi-build-tools is not an N-API module. This entry is for unit testing.", + "napi_versions": [ + 2, + 2, + 3, + 10 + ] + } +} diff --git a/node_modules/natural-compare/README.md b/node_modules/natural-compare/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c85dfdf98ce8750965d43a5ebb1b1bedc7a363e6 --- /dev/null +++ b/node_modules/natural-compare/README.md @@ -0,0 +1,125 @@ + +[Build]: http://img.shields.io/travis/litejs/natural-compare-lite.png +[Coverage]: http://img.shields.io/coveralls/litejs/natural-compare-lite.png +[1]: https://travis-ci.org/litejs/natural-compare-lite +[2]: https://coveralls.io/r/litejs/natural-compare-lite +[npm package]: https://npmjs.org/package/natural-compare-lite +[GitHub repo]: https://github.com/litejs/natural-compare-lite + + + + @version 1.4.0 + @date 2015-10-26 + @stability 3 - Stable + + +Natural Compare – [![Build][]][1] [![Coverage][]][2] +=============== + +Compare strings containing a mix of letters and numbers +in the way a human being would in sort order. +This is described as a "natural ordering". + +```text +Standard sorting: Natural order sorting: + img1.png img1.png + img10.png img2.png + img12.png img10.png + img2.png img12.png +``` + +String.naturalCompare returns a number indicating +whether a reference string comes before or after or is the same +as the given string in sort order. +Use it with builtin sort() function. + + + +### Installation + +- In browser + +```html + +``` + +- In node.js: `npm install natural-compare-lite` + +```javascript +require("natural-compare-lite") +``` + +### Usage + +```javascript +// Simple case sensitive example +var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"]; +a.sort(String.naturalCompare); +// ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"] + +// Use wrapper function for case insensitivity +a.sort(function(a, b){ + return String.naturalCompare(a.toLowerCase(), b.toLowerCase()); +}) + +// In most cases we want to sort an array of objects +var a = [ {"street":"350 5th Ave", "room":"A-1021"} + , {"street":"350 5th Ave", "room":"A-21046-b"} ]; + +// sort by street, then by room +a.sort(function(a, b){ + return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room); +}) + +// When text transformation is needed (eg toLowerCase()), +// it is best for performance to keep +// transformed key in that object. +// There are no need to do text transformation +// on each comparision when sorting. +var a = [ {"make":"Audi", "model":"A6"} + , {"make":"Kia", "model":"Rio"} ]; + +// sort by make, then by model +a.map(function(car){ + car.sort_key = (car.make + " " + car.model).toLowerCase(); +}) +a.sort(function(a, b){ + return String.naturalCompare(a.sort_key, b.sort_key); +}) +``` + +- Works well with dates in ISO format eg "Rev 2012-07-26.doc". + + +### Custom alphabet + +It is possible to configure a custom alphabet +to achieve a desired order. + +```javascript +// Estonian alphabet +String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy" +["t", "z", "x", "õ"].sort(String.naturalCompare) +// ["z", "t", "õ", "x"] + +// Russian alphabet +String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя" +["Ё", "А", "Б"].sort(String.naturalCompare) +// ["А", "Б", "Ё"] +``` + + +External links +-------------- + +- [GitHub repo][https://github.com/litejs/natural-compare-lite] +- [jsperf test](http://jsperf.com/natural-sort-2/12) + + +Licence +------- + +Copyright (c) 2012-2015 Lauri Rooden <lauri@rooden.ee> +[The MIT License](http://lauri.rooden.ee/mit-license.txt) + + diff --git a/node_modules/natural-compare/index.js b/node_modules/natural-compare/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e705d49f5f1ba936086ae6d0fa24db176eb82adf --- /dev/null +++ b/node_modules/natural-compare/index.js @@ -0,0 +1,57 @@ + + + +/* + * @version 1.4.0 + * @date 2015-10-26 + * @stability 3 - Stable + * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite) + * @license MIT License + */ + + +var naturalCompare = function(a, b) { + var i, codeA + , codeB = 1 + , posA = 0 + , posB = 0 + , alphabet = String.alphabet + + function getCode(str, pos, code) { + if (code) { + for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i; + return +str.slice(pos - 1, i) + } + code = alphabet && alphabet.indexOf(str.charAt(pos)) + return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code + : code < 46 ? 65 // - + : code < 48 ? code - 1 + : code < 58 ? code + 18 // 0-9 + : code < 65 ? code - 11 + : code < 91 ? code + 11 // A-Z + : code < 97 ? code - 37 + : code < 123 ? code + 5 // a-z + : code - 63 + } + + + if ((a+="") != (b+="")) for (;codeB;) { + codeA = getCode(a, posA++) + codeB = getCode(b, posB++) + + if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) { + codeA = getCode(a, posA, posA) + codeB = getCode(b, posB, posA = i) + posB = i + } + + if (codeA != codeB) return (codeA < codeB) ? -1 : 1 + } + return 0 +} + +try { + module.exports = naturalCompare; +} catch (e) { + String.naturalCompare = naturalCompare; +} diff --git a/node_modules/natural-compare/package.json b/node_modules/natural-compare/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1a71362eea81a28d88aea31ea94942f6a675e40b --- /dev/null +++ b/node_modules/natural-compare/package.json @@ -0,0 +1,42 @@ +{ + "name": "natural-compare", + "version": "1.4.0", + "stability": 3, + "author": "Lauri Rooden (https://github.com/litejs/natural-compare-lite)", + "license": "MIT", + "description": "Compare strings containing a mix of letters and numbers in the way a human being would in sort order.", + "keywords": [ + "string", + "natural", + "order", + "sort", + "natsort", + "natcmp", + "compare", + "alphanum", + "litejs" + ], + "main": "index.js", + "readmeFilename": "README.md", + "files": [ + "index.js" + ], + "scripts": { + "build": "node node_modules/buildman/index.js --all", + "test": "node tests/index.js" + }, + "repository": "git://github.com/litejs/natural-compare-lite.git", + "bugs": { + "url": "https://github.com/litejs/natural-compare-lite/issues" + }, + "devDependencies": { + "buildman": "*", + "testman": "*" + }, + "buildman": { + "dist/index-min.js": { + "banner": "/*! litejs.com/MIT-LICENSE.txt */", + "input": "index.js" + } + } +} diff --git a/node_modules/negotiator/HISTORY.md b/node_modules/negotiator/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..a9a544914c43bb8927b9ee9ff02aa2c2c7277fdb --- /dev/null +++ b/node_modules/negotiator/HISTORY.md @@ -0,0 +1,108 @@ +0.6.3 / 2022-01-22 +================== + + * Revert "Lazy-load modules from main entry point" + +0.6.2 / 2019-04-29 +================== + + * Fix sorting charset, encoding, and language with extra parameters + +0.6.1 / 2016-05-02 +================== + + * perf: improve `Accept` parsing speed + * perf: improve `Accept-Charset` parsing speed + * perf: improve `Accept-Encoding` parsing speed + * perf: improve `Accept-Language` parsing speed + +0.6.0 / 2015-09-29 +================== + + * Fix including type extensions in parameters in `Accept` parsing + * Fix parsing `Accept` parameters with quoted equals + * Fix parsing `Accept` parameters with quoted semicolons + * Lazy-load modules from main entry point + * perf: delay type concatenation until needed + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove closures getting spec properties + * perf: remove a closure from media type parsing + * perf: remove property delete from media type parsing + +0.5.3 / 2015-05-10 +================== + + * Fix media type parameter matching to be case-insensitive + +0.5.2 / 2015-05-06 +================== + + * Fix comparing media types with quoted values + * Fix splitting media types with quoted commas + +0.5.1 / 2015-02-14 +================== + + * Fix preference sorting to be stable for long acceptable lists + +0.5.0 / 2014-12-18 +================== + + * Fix list return order when large accepted list + * Fix missing identity encoding when q=0 exists + * Remove dynamic building of Negotiator class + +0.4.9 / 2014-10-14 +================== + + * Fix error when media type has invalid parameter + +0.4.8 / 2014-09-28 +================== + + * Fix all negotiations to be case-insensitive + * Stable sort preferences of same quality according to client order + * Support Node.js 0.6 + +0.4.7 / 2014-06-24 +================== + + * Handle invalid provided languages + * Handle invalid provided media types + +0.4.6 / 2014-06-11 +================== + + * Order by specificity when quality is the same + +0.4.5 / 2014-05-29 +================== + + * Fix regression in empty header handling + +0.4.4 / 2014-05-29 +================== + + * Fix behaviors when headers are not present + +0.4.3 / 2014-04-16 +================== + + * Handle slashes on media params correctly + +0.4.2 / 2014-02-28 +================== + + * Fix media type sorting + * Handle media types params strictly + +0.4.1 / 2014-01-16 +================== + + * Use most specific matches + +0.4.0 / 2014-01-09 +================== + + * Remove preferred prefix from methods diff --git a/node_modules/negotiator/LICENSE b/node_modules/negotiator/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ea6b9e2e9ac251526c95df2dd995cf5f1e861854 --- /dev/null +++ b/node_modules/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Federico Romero +Copyright (c) 2012-2014 Isaac Z. Schlueter +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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. diff --git a/node_modules/negotiator/README.md b/node_modules/negotiator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..82915e521b4d321d90111316c6193706f1d7b8bf --- /dev/null +++ b/node_modules/negotiator/README.md @@ -0,0 +1,203 @@ +# negotiator + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +An HTTP content negotiator for Node.js + +## Installation + +```sh +$ npm install negotiator +``` + +## API + +```js +var Negotiator = require('negotiator') +``` + +### Accept Negotiation + +```js +availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + +// The negotiator constructor receives a request object +negotiator = new Negotiator(request) + +// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + +negotiator.mediaTypes() +// -> ['text/html', 'image/jpeg', 'application/*'] + +negotiator.mediaTypes(availableMediaTypes) +// -> ['text/html', 'application/json'] + +negotiator.mediaType(availableMediaTypes) +// -> 'text/html' +``` + +You can check a working example at `examples/accept.js`. + +#### Methods + +##### mediaType() + +Returns the most preferred media type from the client. + +##### mediaType(availableMediaType) + +Returns the most preferred media type from a list of available media types. + +##### mediaTypes() + +Returns an array of preferred media types ordered by the client preference. + +##### mediaTypes(availableMediaTypes) + +Returns an array of preferred media types ordered by priority from a list of +available media types. + +### Accept-Language Negotiation + +```js +negotiator = new Negotiator(request) + +availableLanguages = ['en', 'es', 'fr'] + +// Let's say Accept-Language header is 'en;q=0.8, es, pt' + +negotiator.languages() +// -> ['es', 'pt', 'en'] + +negotiator.languages(availableLanguages) +// -> ['es', 'en'] + +language = negotiator.language(availableLanguages) +// -> 'es' +``` + +You can check a working example at `examples/language.js`. + +#### Methods + +##### language() + +Returns the most preferred language from the client. + +##### language(availableLanguages) + +Returns the most preferred language from a list of available languages. + +##### languages() + +Returns an array of preferred languages ordered by the client preference. + +##### languages(availableLanguages) + +Returns an array of preferred languages ordered by priority from a list of +available languages. + +### Accept-Charset Negotiation + +```js +availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + +negotiator.charsets() +// -> ['utf-8', 'iso-8859-1', 'utf-7'] + +negotiator.charsets(availableCharsets) +// -> ['utf-8', 'iso-8859-1'] + +negotiator.charset(availableCharsets) +// -> 'utf-8' +``` + +You can check a working example at `examples/charset.js`. + +#### Methods + +##### charset() + +Returns the most preferred charset from the client. + +##### charset(availableCharsets) + +Returns the most preferred charset from a list of available charsets. + +##### charsets() + +Returns an array of preferred charsets ordered by the client preference. + +##### charsets(availableCharsets) + +Returns an array of preferred charsets ordered by priority from a list of +available charsets. + +### Accept-Encoding Negotiation + +```js +availableEncodings = ['identity', 'gzip'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + +negotiator.encodings() +// -> ['gzip', 'identity', 'compress'] + +negotiator.encodings(availableEncodings) +// -> ['gzip', 'identity'] + +negotiator.encoding(availableEncodings) +// -> 'gzip' +``` + +You can check a working example at `examples/encoding.js`. + +#### Methods + +##### encoding() + +Returns the most preferred encoding from the client. + +##### encoding(availableEncodings) + +Returns the most preferred encoding from a list of available encodings. + +##### encodings() + +Returns an array of preferred encodings ordered by the client preference. + +##### encodings(availableEncodings) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings. + +## See Also + +The [accepts](https://npmjs.org/package/accepts#readme) module builds on +this module and provides an alternative interface, mime type validation, +and more. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/negotiator.svg +[npm-url]: https://npmjs.org/package/negotiator +[node-version-image]: https://img.shields.io/node/v/negotiator.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master +[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg +[downloads-url]: https://npmjs.org/package/negotiator +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/jshttp/negotiator/ci/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/negotiator/actions/workflows/ci.yml diff --git a/node_modules/negotiator/index.js b/node_modules/negotiator/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4788264b16c9f2282bba539529577ed31920425d --- /dev/null +++ b/node_modules/negotiator/index.js @@ -0,0 +1,82 @@ +/*! + * negotiator + * Copyright(c) 2012 Federico Romero + * Copyright(c) 2012-2014 Isaac Z. Schlueter + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +var preferredCharsets = require('./lib/charset') +var preferredEncodings = require('./lib/encoding') +var preferredLanguages = require('./lib/language') +var preferredMediaTypes = require('./lib/mediaType') + +/** + * Module exports. + * @public + */ + +module.exports = Negotiator; +module.exports.Negotiator = Negotiator; + +/** + * Create a Negotiator instance from a request. + * @param {object} request + * @public + */ + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available) { + var set = this.encodings(available); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available) { + return preferredEncodings(this.request.headers['accept-encoding'], available); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; diff --git a/node_modules/negotiator/lib/charset.js b/node_modules/negotiator/lib/charset.js new file mode 100644 index 0000000000000000000000000000000000000000..cdd014803474a4b76b981c475a32ebcaa81a36e5 --- /dev/null +++ b/node_modules/negotiator/lib/charset.js @@ -0,0 +1,169 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredCharsets; +module.exports.preferredCharsets = preferredCharsets; + +/** + * Module variables. + * @private + */ + +var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Charset header. + * @private + */ + +function parseAcceptCharset(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var charset = parseCharset(accepts[i].trim(), i); + + if (charset) { + accepts[j++] = charset; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a charset from the Accept-Charset header. + * @private + */ + +function parseCharset(str, i) { + var match = simpleCharsetRegExp.exec(str); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +/** + * Get the priority of a charset. + * @private + */ + +function getCharsetPriority(charset, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(charset, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the charset. + * @private + */ + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +/** + * Get the preferred charsets from an Accept-Charset header. + * @public + */ + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all charsets + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullCharset); + } + + var priorities = provided.map(function getPriority(type, index) { + return getCharsetPriority(type, accepts, index); + }); + + // sorted list of accepted charsets + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full charset string. + * @private + */ + +function getFullCharset(spec) { + return spec.charset; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/encoding.js b/node_modules/negotiator/lib/encoding.js new file mode 100644 index 0000000000000000000000000000000000000000..8432cd77b8a96940b87d747dbb30ee9c2d065a31 --- /dev/null +++ b/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,184 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredEncodings; +module.exports.preferredEncodings = preferredEncodings; + +/** + * Module variables. + * @private + */ + +var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Encoding header. + * @private + */ + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + for (var i = 0, j = 0; i < accepts.length; i++) { + var encoding = parseEncoding(accepts[i].trim(), i); + + if (encoding) { + accepts[j++] = encoding; + hasIdentity = hasIdentity || specify('identity', encoding); + minQuality = Math.min(minQuality, encoding.q || 1); + } + } + + if (!hasIdentity) { + /* + * If identity doesn't explicitly appear in the accept-encoding header, + * it's added to the list of acceptable encoding with the lowest q + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse an encoding from the Accept-Encoding header. + * @private + */ + +function parseEncoding(str, i) { + var match = simpleEncodingRegExp.exec(str); + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +/** + * Get the priority of an encoding. + * @private + */ + +function getEncodingPriority(encoding, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(encoding, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the encoding. + * @private + */ + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred encodings from an Accept-Encoding header. + * @public + */ + +function preferredEncodings(accept, provided) { + var accepts = parseAcceptEncoding(accept || ''); + + if (!provided) { + // sorted list of all encodings + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullEncoding); + } + + var priorities = provided.map(function getPriority(type, index) { + return getEncodingPriority(type, accepts, index); + }); + + // sorted list of accepted encodings + return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full encoding string. + * @private + */ + +function getFullEncoding(spec) { + return spec.encoding; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/language.js b/node_modules/negotiator/lib/language.js new file mode 100644 index 0000000000000000000000000000000000000000..a23167252719be841ad570eb655a703a4ae8fe9e --- /dev/null +++ b/node_modules/negotiator/lib/language.js @@ -0,0 +1,179 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredLanguages; +module.exports.preferredLanguages = preferredLanguages; + +/** + * Module variables. + * @private + */ + +var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Language header. + * @private + */ + +function parseAcceptLanguage(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var language = parseLanguage(accepts[i].trim(), i); + + if (language) { + accepts[j++] = language; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a language from the Accept-Language header. + * @private + */ + +function parseLanguage(str, i) { + var match = simpleLanguageRegExp.exec(str); + if (!match) return null; + + var prefix = match[1] + var suffix = match[2] + var full = prefix + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +/** + * Get the priority of a language. + * @private + */ + +function getLanguagePriority(language, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(language, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the language. + * @private + */ + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred languages from an Accept-Language header. + * @public + */ + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all languages + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullLanguage); + } + + var priorities = provided.map(function getPriority(type, index) { + return getLanguagePriority(type, accepts, index); + }); + + // sorted list of accepted languages + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full language string. + * @private + */ + +function getFullLanguage(spec) { + return spec.full; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/mediaType.js b/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 0000000000000000000000000000000000000000..67309dd75f1b62cfe90bfa622919fdae8b80bc0b --- /dev/null +++ b/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,294 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredMediaTypes; +module.exports.preferredMediaTypes = preferredMediaTypes; + +/** + * Module variables. + * @private + */ + +var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept header. + * @private + */ + +function parseAccept(accept) { + var accepts = splitMediaTypes(accept); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var mediaType = parseMediaType(accepts[i].trim(), i); + + if (mediaType) { + accepts[j++] = mediaType; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a media type from the Accept header. + * @private + */ + +function parseMediaType(str, i) { + var match = simpleMediaTypeRegExp.exec(str); + if (!match) return null; + + var params = Object.create(null); + var q = 1; + var subtype = match[2]; + var type = match[1]; + + if (match[3]) { + var kvps = splitParameters(match[3]).map(splitKeyValuePair); + + for (var j = 0; j < kvps.length; j++) { + var pair = kvps[j]; + var key = pair[0].toLowerCase(); + var val = pair[1]; + + // get the value, unwrapping quotes + var value = val && val[0] === '"' && val[val.length - 1] === '"' + ? val.substr(1, val.length - 2) + : val; + + if (key === 'q') { + q = parseFloat(value); + break; + } + + // store parameter + params[key] = value; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i + }; +} + +/** + * Get the priority of a media type. + * @private + */ + +function getMediaTypePriority(type, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(type, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the media type. + * @private + */ + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } +} + +/** + * Get the preferred media types from an Accept header. + * @public + */ + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + if (!provided) { + // sorted list of all types + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullType); + } + + var priorities = provided.map(function getPriority(type, index) { + return getMediaTypePriority(type, accepts, index); + }); + + // sorted list of accepted types + return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full type string. + * @private + */ + +function getFullType(spec) { + return spec.type + '/' + spec.subtype; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} + +/** + * Count the number of quotes in a string. + * @private + */ + +function quoteCount(string) { + var count = 0; + var index = 0; + + while ((index = string.indexOf('"', index)) !== -1) { + count++; + index++; + } + + return count; +} + +/** + * Split a key value pair. + * @private + */ + +function splitKeyValuePair(str) { + var index = str.indexOf('='); + var key; + var val; + + if (index === -1) { + key = str; + } else { + key = str.substr(0, index); + val = str.substr(index + 1); + } + + return [key, val]; +} + +/** + * Split an Accept header into media types. + * @private + */ + +function splitMediaTypes(accept) { + var accepts = accept.split(','); + + for (var i = 1, j = 0; i < accepts.length; i++) { + if (quoteCount(accepts[j]) % 2 == 0) { + accepts[++j] = accepts[i]; + } else { + accepts[j] += ',' + accepts[i]; + } + } + + // trim accepts + accepts.length = j + 1; + + return accepts; +} + +/** + * Split a string of parameters. + * @private + */ + +function splitParameters(str) { + var parameters = str.split(';'); + + for (var i = 1, j = 0; i < parameters.length; i++) { + if (quoteCount(parameters[j]) % 2 == 0) { + parameters[++j] = parameters[i]; + } else { + parameters[j] += ';' + parameters[i]; + } + } + + // trim parameters + parameters.length = j + 1; + + for (var i = 0; i < parameters.length; i++) { + parameters[i] = parameters[i].trim(); + } + + return parameters; +} diff --git a/node_modules/negotiator/package.json b/node_modules/negotiator/package.json new file mode 100644 index 0000000000000000000000000000000000000000..297635f6d34177956186df7c6a7e502ebb576da2 --- /dev/null +++ b/node_modules/negotiator/package.json @@ -0,0 +1,42 @@ +{ + "name": "negotiator", + "description": "HTTP content negotiation", + "version": "0.6.3", + "contributors": [ + "Douglas Christopher Wilson ", + "Federico Romero ", + "Isaac Z. Schlueter (http://blog.izs.me/)" + ], + "license": "MIT", + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "repository": "jshttp/negotiator", + "devDependencies": { + "eslint": "7.32.0", + "eslint-plugin-markdown": "2.2.1", + "mocha": "9.1.3", + "nyc": "15.1.0" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/node-abi/LICENSE b/node_modules/node-abi/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5513de0dac227e711f80c9504d181f95a8395cd1 --- /dev/null +++ b/node_modules/node-abi/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Lukas Geiger + +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. diff --git a/node_modules/node-abi/README.md b/node_modules/node-abi/README.md new file mode 100644 index 0000000000000000000000000000000000000000..680a0d0b6878291a696e3b7fcd6f48e48c6d910c --- /dev/null +++ b/node_modules/node-abi/README.md @@ -0,0 +1,54 @@ +# Node.js ABI + +[![Build Status](https://github.com/electron/node-abi/actions/workflows/test.yml/badge.svg)](https://github.com/electron/node-abi/actions/workflows/test.yml) +[![Auto-update ABI JSON file](https://github.com/electron/node-abi/actions/workflows/update-abi.yml/badge.svg)](https://github.com/electron/node-abi/actions/workflows/update-abi.yml) +[![Snyk badge](https://snyk.io/test/github/electron/node-abi/badge.svg)](https://snyk.io/test/github/electron/node-abi) +[![npm version](http://img.shields.io/npm/v/node-abi.svg)](https://npmjs.org/package/node-abi) + +Get the Node ABI (application binary interface) for a given target and runtime, and vice versa. + +## Installation + +```shell +npm install node-abi +``` + +## Usage + +```javascript +const nodeAbi = require('node-abi') + +nodeAbi.getAbi('7.2.0', 'node') +// '51' +nodeAbi.getAbi('1.4.10', 'electron') +// '50' +nodeAbi.getTarget('51', 'node') +// '7.2.0' +nodeAbi.getTarget('50', 'electron') +// '1.4.15' + +nodeAbi.allTargets +// [ +// { runtime: 'node', target: '0.10.48', abi: '11', lts: false }, +// { runtime: 'node', target: '0.12.17', abi: '14', lts: false }, +// { runtime: 'node', target: '4.6.1', abi: '46', lts: true }, +// { runtime: 'node', target: '5.12.0', abi: '47', lts: false }, +// { runtime: 'node', target: '6.9.4', abi: '48', lts: true }, +// { runtime: 'node', target: '7.4.0', abi: '51', lts: false }, +// { runtime: 'electron', target: '1.0.2', abi: '47', lts: false }, +// { runtime: 'electron', target: '1.2.8', abi: '48', lts: false }, +// { runtime: 'electron', target: '1.3.13', abi: '49', lts: false }, +// { runtime: 'electron', target: '1.4.15', abi: '50', lts: false } +// ] +nodeAbi.deprecatedTargets +nodeAbi.supportedTargets +nodeAbi.additionalTargets +nodeAbi.futureTargets +// ... +``` + +## References + +- https://github.com/lgeiger/electron-abi +- https://nodejs.org/en/download/releases/ +- https://github.com/nodejs/Release diff --git a/node_modules/node-abi/abi_registry.json b/node_modules/node-abi/abi_registry.json new file mode 100644 index 0000000000000000000000000000000000000000..32288e523ba694a290889f74dbfbed50ee61791f --- /dev/null +++ b/node_modules/node-abi/abi_registry.json @@ -0,0 +1,446 @@ +[ + { + "runtime": "node", + "target": "11.0.0", + "lts": false, + "future": false, + "abi": "67" + }, + { + "runtime": "node", + "target": "12.0.0", + "lts": [ + "2019-10-21", + "2020-11-30" + ], + "future": false, + "abi": "72" + }, + { + "runtime": "node", + "target": "13.0.0", + "lts": false, + "future": false, + "abi": "79" + }, + { + "runtime": "node", + "target": "14.0.0", + "lts": [ + "2020-10-27", + "2021-10-19" + ], + "future": false, + "abi": "83" + }, + { + "runtime": "node", + "target": "15.0.0", + "lts": false, + "future": false, + "abi": "88" + }, + { + "runtime": "node", + "target": "16.0.0", + "lts": [ + "2021-10-26", + "2022-10-18" + ], + "future": false, + "abi": "93" + }, + { + "runtime": "node", + "target": "17.0.0", + "lts": false, + "future": false, + "abi": "102" + }, + { + "runtime": "node", + "target": "18.0.0", + "lts": [ + "2022-10-25", + "2023-10-18" + ], + "future": false, + "abi": "108" + }, + { + "runtime": "node", + "target": "19.0.0", + "lts": false, + "future": false, + "abi": "111" + }, + { + "runtime": "node", + "target": "20.0.0", + "lts": [ + "2023-10-24", + "2024-10-22" + ], + "future": false, + "abi": "115" + }, + { + "runtime": "node", + "target": "21.0.0", + "lts": false, + "future": false, + "abi": "120" + }, + { + "runtime": "node", + "target": "22.0.0", + "lts": [ + "2024-10-29", + "2025-10-21" + ], + "future": false, + "abi": "127" + }, + { + "runtime": "node", + "target": "23.0.0", + "lts": false, + "future": false, + "abi": "131" + }, + { + "runtime": "node", + "target": "24.0.0", + "lts": [ + "2025-10-28", + "2026-10-20" + ], + "future": false, + "abi": "137" + }, + { + "runtime": "node", + "target": "25.0.0", + "lts": false, + "future": false, + "abi": "141" + }, + { + "runtime": "node", + "target": "26.0.0", + "lts": [ + "2026-10-28", + "2027-10-20" + ], + "future": false, + "abi": "147" + }, + { + "abi": "70", + "future": false, + "lts": false, + "runtime": "electron", + "target": "5.0.0-beta.9" + }, + { + "abi": "73", + "future": false, + "lts": false, + "runtime": "electron", + "target": "6.0.0-beta.1" + }, + { + "abi": "75", + "future": false, + "lts": false, + "runtime": "electron", + "target": "7.0.0-beta.1" + }, + { + "abi": "76", + "future": false, + "lts": false, + "runtime": "electron", + "target": "9.0.0-beta.1" + }, + { + "abi": "76", + "future": false, + "lts": false, + "runtime": "electron", + "target": "8.0.0-beta.1" + }, + { + "abi": "80", + "future": false, + "lts": false, + "runtime": "electron", + "target": "9.0.0-beta.2" + }, + { + "abi": "82", + "future": false, + "lts": false, + "runtime": "electron", + "target": "11.0.0-beta.1" + }, + { + "abi": "82", + "future": false, + "lts": false, + "runtime": "electron", + "target": "10.0.0-beta.1" + }, + { + "abi": "85", + "future": false, + "lts": false, + "runtime": "electron", + "target": "11.0.0-beta.11" + }, + { + "abi": "87", + "future": false, + "lts": false, + "runtime": "electron", + "target": "12.0.0-beta.1" + }, + { + "abi": "89", + "future": false, + "lts": false, + "runtime": "electron", + "target": "15.0.0-alpha.1" + }, + { + "abi": "89", + "future": false, + "lts": false, + "runtime": "electron", + "target": "14.0.0-beta.1" + }, + { + "abi": "89", + "future": false, + "lts": false, + "runtime": "electron", + "target": "13.0.0-beta.2" + }, + { + "abi": "97", + "future": false, + "lts": false, + "runtime": "electron", + "target": "14.0.2" + }, + { + "abi": "98", + "future": false, + "lts": false, + "runtime": "electron", + "target": "15.0.0-beta.7" + }, + { + "abi": "99", + "future": false, + "lts": false, + "runtime": "electron", + "target": "16.0.0-alpha.1" + }, + { + "abi": "101", + "future": false, + "lts": false, + "runtime": "electron", + "target": "17.0.0-alpha.1" + }, + { + "abi": "103", + "future": false, + "lts": false, + "runtime": "electron", + "target": "18.0.0-alpha.1" + }, + { + "abi": "106", + "future": false, + "lts": false, + "runtime": "electron", + "target": "19.0.0-alpha.1" + }, + { + "abi": "107", + "future": false, + "lts": false, + "runtime": "electron", + "target": "20.0.0-alpha.1" + }, + { + "abi": "109", + "future": false, + "lts": false, + "runtime": "electron", + "target": "21.0.0-alpha.1" + }, + { + "abi": "110", + "future": false, + "lts": false, + "runtime": "electron", + "target": "22.0.0-alpha.1" + }, + { + "abi": "113", + "future": false, + "lts": false, + "runtime": "electron", + "target": "23.0.0-alpha.1" + }, + { + "abi": "114", + "future": false, + "lts": false, + "runtime": "electron", + "target": "24.0.0-alpha.1" + }, + { + "abi": "116", + "future": false, + "lts": false, + "runtime": "electron", + "target": "26.0.0-alpha.1" + }, + { + "abi": "116", + "future": false, + "lts": false, + "runtime": "electron", + "target": "25.0.0-alpha.1" + }, + { + "abi": "118", + "future": false, + "lts": false, + "runtime": "electron", + "target": "27.0.0-alpha.1" + }, + { + "abi": "119", + "future": false, + "lts": false, + "runtime": "electron", + "target": "28.0.0-alpha.1" + }, + { + "abi": "121", + "future": false, + "lts": false, + "runtime": "electron", + "target": "29.0.0-alpha.1" + }, + { + "abi": "123", + "future": false, + "lts": false, + "runtime": "electron", + "target": "31.0.0-alpha.1" + }, + { + "abi": "123", + "future": false, + "lts": false, + "runtime": "electron", + "target": "30.0.0-alpha.1" + }, + { + "abi": "125", + "future": false, + "lts": false, + "runtime": "electron", + "target": "31.0.0-beta.7" + }, + { + "abi": "128", + "future": false, + "lts": false, + "runtime": "electron", + "target": "32.0.0-alpha.1" + }, + { + "abi": "130", + "future": false, + "lts": false, + "runtime": "electron", + "target": "33.0.0-alpha.1" + }, + { + "abi": "132", + "future": false, + "lts": false, + "runtime": "electron", + "target": "34.0.0-alpha.1" + }, + { + "abi": "133", + "future": false, + "lts": false, + "runtime": "electron", + "target": "35.0.0-alpha.1" + }, + { + "abi": "135", + "future": false, + "lts": false, + "runtime": "electron", + "target": "36.0.0-alpha.1" + }, + { + "abi": "136", + "future": false, + "lts": false, + "runtime": "electron", + "target": "37.0.0-alpha.1" + }, + { + "abi": "139", + "future": false, + "lts": false, + "runtime": "electron", + "target": "38.0.0-alpha.1" + }, + { + "abi": "140", + "future": false, + "lts": false, + "runtime": "electron", + "target": "39.0.0-alpha.1" + }, + { + "abi": "143", + "future": false, + "lts": false, + "runtime": "electron", + "target": "40.0.0-alpha.2" + }, + { + "abi": "145", + "future": false, + "lts": false, + "runtime": "electron", + "target": "41.0.0-alpha.1" + }, + { + "abi": "146", + "future": false, + "lts": false, + "runtime": "electron", + "target": "42.0.0-alpha.1" + }, + { + "abi": "148", + "future": true, + "lts": false, + "runtime": "electron", + "target": "43.0.0-alpha.1" + } +] \ No newline at end of file diff --git a/node_modules/node-abi/index.js b/node_modules/node-abi/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f65613534ea6d6ce276c9483cafcfbde847f0ba1 --- /dev/null +++ b/node_modules/node-abi/index.js @@ -0,0 +1,179 @@ +var semver = require('semver') + +function getNextTarget (runtime, targets) { + if (targets == null) targets = allTargets + var latest = targets.filter(function (t) { return t.runtime === runtime }).slice(-1)[0] + var increment = runtime === 'electron' ? 'minor' : 'major' + var next = semver.inc(latest.target, increment) + // Electron releases appear in the registry in their beta form, sometimes there is + // no active beta line. During this time we need to double bump + if (runtime === 'electron' && semver.parse(latest.target).prerelease.length) { + next = semver.inc(next, 'major') + } + return next +} + +function getAbi (target, runtime) { + if (target === String(Number(target))) return target + if (target) target = target.replace(/^v/, '') + if (!runtime) runtime = 'node' + + if (runtime === 'node') { + if (!target) return process.versions.modules + if (target === process.versions.node) return process.versions.modules + } + + var abi + var lastTarget + + for (var i = 0; i < allTargets.length; i++) { + var t = allTargets[i] + if (t.runtime !== runtime) continue + if (semver.lte(t.target, target) && (!lastTarget || semver.gte(t.target, lastTarget))) { + abi = t.abi + lastTarget = t.target + } + } + + if (abi && semver.lt(target, getNextTarget(runtime))) return abi + throw new Error('Could not detect abi for version ' + target + ' and runtime ' + runtime + '. Updating "node-abi" might help solve this issue if it is a new release of ' + runtime) +} + +function getTarget (abi, runtime) { + if (abi && abi !== String(Number(abi))) return abi + if (!runtime) runtime = 'node' + + if (runtime === 'node' && !abi) return process.versions.node + + var match = allTargets + .filter(function (t) { + return t.abi === abi && t.runtime === runtime + }) + .map(function (t) { + return t.target + }) + if (match.length) { + var betaSeparatorIndex = match[0].indexOf("-") + return betaSeparatorIndex > -1 + ? match[0].substring(0, betaSeparatorIndex) + : match[0] + } + + throw new Error('Could not detect target for abi ' + abi + ' and runtime ' + runtime) +} + +function sortByTargetFn (a, b) { + var abiComp = Number(a.abi) - Number(b.abi) + if (abiComp !== 0) return abiComp + if (a.target < b.target) return -1 + if (a.target > b.target) return 1 + return 0 +} + +function loadGeneratedTargets () { + var registry = require('./abi_registry.json') + var targets = { + supported: [], + additional: [], + future: [] + } + + registry.forEach(function (item) { + var target = { + runtime: item.runtime, + target: item.target, + abi: item.abi + } + if (item.lts) { + var startDate = new Date(Date.parse(item.lts[0])) + var endDate = new Date(Date.parse(item.lts[1])) + var currentDate = new Date() + target.lts = startDate < currentDate && currentDate < endDate + } else { + target.lts = false + } + + if (target.runtime === 'node-webkit') { + targets.additional.push(target) + } else if (item.future) { + targets.future.push(target) + } else { + targets.supported.push(target) + } + }) + + targets.supported.sort(sortByTargetFn) + targets.additional.sort(sortByTargetFn) + targets.future.sort(sortByTargetFn) + + return targets +} + +var generatedTargets = loadGeneratedTargets() + +var supportedTargets = [ + {runtime: 'node', target: '5.0.0', abi: '47', lts: false}, + {runtime: 'node', target: '6.0.0', abi: '48', lts: false}, + {runtime: 'node', target: '7.0.0', abi: '51', lts: false}, + {runtime: 'node', target: '8.0.0', abi: '57', lts: false}, + {runtime: 'node', target: '9.0.0', abi: '59', lts: false}, + {runtime: 'node', target: '10.0.0', abi: '64', lts: new Date(2018, 10, 1) < new Date() && new Date() < new Date(2020, 4, 31)}, + {runtime: 'electron', target: '0.36.0', abi: '47', lts: false}, + {runtime: 'electron', target: '1.1.0', abi: '48', lts: false}, + {runtime: 'electron', target: '1.3.0', abi: '49', lts: false}, + {runtime: 'electron', target: '1.4.0', abi: '50', lts: false}, + {runtime: 'electron', target: '1.5.0', abi: '51', lts: false}, + {runtime: 'electron', target: '1.6.0', abi: '53', lts: false}, + {runtime: 'electron', target: '1.7.0', abi: '54', lts: false}, + {runtime: 'electron', target: '1.8.0', abi: '57', lts: false}, + {runtime: 'electron', target: '2.0.0', abi: '57', lts: false}, + {runtime: 'electron', target: '3.0.0', abi: '64', lts: false}, + {runtime: 'electron', target: '4.0.0', abi: '64', lts: false}, + {runtime: 'electron', target: '4.0.4', abi: '69', lts: false} +] + +supportedTargets.push.apply(supportedTargets, generatedTargets.supported) + +var additionalTargets = [ + {runtime: 'node-webkit', target: '0.13.0', abi: '47', lts: false}, + {runtime: 'node-webkit', target: '0.15.0', abi: '48', lts: false}, + {runtime: 'node-webkit', target: '0.18.3', abi: '51', lts: false}, + {runtime: 'node-webkit', target: '0.23.0', abi: '57', lts: false}, + {runtime: 'node-webkit', target: '0.26.5', abi: '59', lts: false} +] + +additionalTargets.push.apply(additionalTargets, generatedTargets.additional) + +var deprecatedTargets = [ + {runtime: 'node', target: '0.2.0', abi: '1', lts: false}, + {runtime: 'node', target: '0.9.1', abi: '0x000A', lts: false}, + {runtime: 'node', target: '0.9.9', abi: '0x000B', lts: false}, + {runtime: 'node', target: '0.10.4', abi: '11', lts: false}, + {runtime: 'node', target: '0.11.0', abi: '0x000C', lts: false}, + {runtime: 'node', target: '0.11.8', abi: '13', lts: false}, + {runtime: 'node', target: '0.11.11', abi: '14', lts: false}, + {runtime: 'node', target: '1.0.0', abi: '42', lts: false}, + {runtime: 'node', target: '1.1.0', abi: '43', lts: false}, + {runtime: 'node', target: '2.0.0', abi: '44', lts: false}, + {runtime: 'node', target: '3.0.0', abi: '45', lts: false}, + {runtime: 'node', target: '4.0.0', abi: '46', lts: false}, + {runtime: 'electron', target: '0.30.0', abi: '44', lts: false}, + {runtime: 'electron', target: '0.31.0', abi: '45', lts: false}, + {runtime: 'electron', target: '0.33.0', abi: '46', lts: false} +] + +var futureTargets = generatedTargets.future + +var allTargets = deprecatedTargets + .concat(supportedTargets) + .concat(additionalTargets) + .concat(futureTargets) + +exports.getAbi = getAbi +exports.getTarget = getTarget +exports.deprecatedTargets = deprecatedTargets +exports.supportedTargets = supportedTargets +exports.additionalTargets = additionalTargets +exports.futureTargets = futureTargets +exports.allTargets = allTargets +exports._getNextTarget = getNextTarget diff --git a/node_modules/node-abi/package.json b/node_modules/node-abi/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0ad58de5c639723a610e336d6190add39426198e --- /dev/null +++ b/node_modules/node-abi/package.json @@ -0,0 +1,45 @@ +{ + "name": "node-abi", + "version": "3.92.0", + "description": "Get the Node ABI for a given target and runtime, and vice versa.", + "main": "index.js", + "scripts": { + "test": "tape test/index.js", + "update-abi-registry": "node --unhandled-rejections=strict scripts/update-abi-registry.js" + }, + "files": [ + "abi_registry.json" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/electron/node-abi.git" + }, + "keywords": [ + "node", + "electron", + "node_module_version", + "abi", + "v8" + ], + "author": "Lukas Geiger", + "license": "MIT", + "bugs": { + "url": "https://github.com/electron/node-abi/issues" + }, + "homepage": "https://github.com/electron/node-abi#readme", + "devDependencies": { + "@semantic-release/npm": "13.0.0-alpha.15", + "semantic-release": "^24.2.7", + "tape": "^5.3.1" + }, + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + }, + "publishConfig": { + "provenance": true + }, + "packageManager": "yarn@4.10.3+sha512.c38cafb5c7bb273f3926d04e55e1d8c9dfa7d9c3ea1f36a4868fa028b9e5f72298f0b7f401ad5eb921749eb012eb1c3bb74bf7503df3ee43fd600d14a018266f" +} diff --git a/node_modules/node-cron/LICENSE.md b/node_modules/node-cron/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..3da3ff00b8c424d9fdfaef27b0ddfa0fb075f013 --- /dev/null +++ b/node_modules/node-cron/LICENSE.md @@ -0,0 +1,7 @@ +## ISC License + +Copyright (c) 2016, Lucas Merencia \ + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/node-cron/README.md b/node_modules/node-cron/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8c1c3cc52df05e3e46fafa9f5783908e5f81c025 --- /dev/null +++ b/node_modules/node-cron/README.md @@ -0,0 +1,117 @@ +# Node Cron + +[![npm](https://img.shields.io/npm/l/node-cron.svg)](https://github.com/merencia/node-cron/blob/master/LICENSE.md) +[![npm](https://img.shields.io/npm/v/node-cron.svg)](https://img.shields.io/npm/v/node-cron.svg) +![NPM Downloads](https://img.shields.io/npm/dm/node-cron) +[![Coverage Status](https://coveralls.io/repos/github/node-cron/node-cron/badge.svg?branch=main)](https://coveralls.io/github/node-cron/node-cron?branch=main) + +The node-cron module is tiny task scheduler in pure JavaScript for node.js based on [GNU crontab](https://www.gnu.org/software/mcron/manual/html_node/Crontab-file.html). This module allows you to schedule task in node.js using full crontab syntax. + +### [Node-Cron Documentation](http://nodecron.com) + +## Getting Started + +Install node-cron using npm: + +```console +npm install --save node-cron +``` + +Import node-cron and schedule a task: + +- commonjs + +```javascript +const cron = require('node-cron'); + +cron.schedule('* * * * *', () => { + console.log('running a task every minute'); +}); +``` + +- es6 (module) + +```javascript +import cron from 'node-cron'; + +cron.schedule('* * * * *', () => { + console.log('running a task every minute'); +}); +``` + +## Cron Syntax + +This is a quick reference to cron syntax and also shows the options supported by node-cron. + +### Allowed fields + +``` + # ┌────────────── second (optional) + # │ ┌──────────── minute + # │ │ ┌────────── hour + # │ │ │ ┌──────── day of month + # │ │ │ │ ┌────── month + # │ │ │ │ │ ┌──── day of week + # │ │ │ │ │ │ + # │ │ │ │ │ │ + # * * * * * * +``` + +### Allowed values + +| field | value | +| ------------ | --------------------------------- | +| second | 0-59 | +| minute | 0-59 | +| hour | 0-23 | +| day of month | 1-31 | +| month | 1-12 (or names) | +| day of week | 0-7 (or names, 0 or 7 are sunday) | + + +## Issues + +Feel free to submit issues and enhancement requests [here](https://github.com/merencia/node-cron/issues). + +## Contributing + +In general, we follow the "fork-and-pull" Git workflow. + +- Fork the repo on GitHub; +- Commit changes to a branch in your fork; +- Pull request "upstream" with your changes; + +NOTE: Be sure to merge the latest from "upstream" before making a pull request! + +Please do not contribute code you did not write yourself, unless you are certain you have the legal ability to do so. Also ensure all contributed code can be distributed under the ISC License. + +## Contributors + +This project exists thanks to all the people who contribute. + + + +## Backers + +Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/node-cron#backer)] + + + +## Sponsors + +Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/node-cron#sponsor)] + + + + + + + + + + + + +## License + +node-cron is under [ISC License](https://github.com/merencia/node-cron/blob/master/LICENSE.md). diff --git a/node_modules/node-cron/package.json b/node_modules/node-cron/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1b17804bad5c0f2930379fd41fcff796ad21a01a --- /dev/null +++ b/node_modules/node-cron/package.json @@ -0,0 +1,85 @@ +{ + "name": "node-cron", + "version": "4.2.1", + "description": "A Lightweight Task Scheduler for Node.js", + "author": "Lucas Merencia", + "license": "ISC", + "homepage": "https://github.com/merencia/node-cron", + "main": "./dist/cjs/node-cron.js", + "module": "./dist/esm/node-cron.js", + "type": "commonjs", + "exports": { + ".": { + "require": { + "types": "./dist/cjs/node-cron.d.ts", + "default": "./dist/cjs/node-cron.js" + }, + "import": { + "types": "./dist/esm/node-cron.d.ts", + "default": "./dist/esm/node-cron.js" + } + } + }, + "scripts": { + "test": "c8 --reporter text --reporter=lcov --exclude '**/*.test.ts' mocha --recursive './src/**/*.test.ts'", + "test:nocov": "mocha --recursive **/*.test.ts", + "lint": "./node_modules/.bin/eslint ./src", + "check": "npm run lint && npm test", + "build:esm": "tsc -p tsconfig.esm.json", + "build:cjs": "tsc -p tsconfig.cjs.json", + "build": "npm run build:esm; npm run build:cjs", + "prepublishOnly": "npm run build" + }, + "engines": { + "node": ">=6.0.0" + }, + "files": [ + "dist/" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/merencia/node-cron.git" + }, + "keywords": [ + "cron", + "scheduler", + "schedule", + "task", + "job" + ], + "bugs": { + "url": "https://github.com/merencia/node-cron/issues" + }, + "devDependencies": { + "@eslint/js": "^9.26.0", + "@tsconfig/recommended": "^1.0.8", + "@types/chai": "^5.2.1", + "@types/expect": "^1.20.4", + "@types/mocha": "^10.0.10", + "@types/node": "^22.15.3", + "@types/sinon": "^17.0.4", + "@typescript-eslint/eslint-plugin": "^8.32.0", + "@typescript-eslint/parser": "^8.32.0", + "c8": "^10.1.3", + "chai": "^5.2.0", + "eslint": "^9.26.0", + "eslint-plugin-mocha": "^10.5.0", + "eslint-plugin-node": "^11.1.0", + "globals": "^16.1.0", + "mocha": "^11.1.0", + "sinon": "^20.0.0", + "tsup": "^8.4.0", + "tsx": "^4.19.3", + "typescript": "^5.8.3", + "typescript-eslint": "^8.32.0" + }, + "c8": { + "reporter": [ + "html", + "text" + ], + "exclude": [ + "src/test-assets/**" + ] + } +} diff --git a/node_modules/node-int64/.npmignore b/node_modules/node-int64/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..825fc67c2c2aeb2580cb5cedfa03c2251e75f925 --- /dev/null +++ b/node_modules/node-int64/.npmignore @@ -0,0 +1,3 @@ +node_modules +.DS_Store +npm-debug.log diff --git a/node_modules/node-int64/Int64.js b/node_modules/node-int64/Int64.js new file mode 100644 index 0000000000000000000000000000000000000000..f870a2a94d3b5504446978328745326347637264 --- /dev/null +++ b/node_modules/node-int64/Int64.js @@ -0,0 +1,268 @@ +// Int64.js +// +// Copyright (c) 2012 Robert Kieffer +// MIT License - http://opensource.org/licenses/mit-license.php + +/** + * Support for handling 64-bit int numbers in Javascript (node.js) + * + * JS Numbers are IEEE-754 binary double-precision floats, which limits the + * range of values that can be represented with integer precision to: + * + * 2^^53 <= N <= 2^53 + * + * Int64 objects wrap a node Buffer that holds the 8-bytes of int64 data. These + * objects operate directly on the buffer which means that if they are created + * using an existing buffer then setting the value will modify the Buffer, and + * vice-versa. + * + * Internal Representation + * + * The internal buffer format is Big Endian. I.e. the most-significant byte is + * at buffer[0], the least-significant at buffer[7]. For the purposes of + * converting to/from JS native numbers, the value is assumed to be a signed + * integer stored in 2's complement form. + * + * For details about IEEE-754 see: + * http://en.wikipedia.org/wiki/Double_precision_floating-point_format + */ + +// Useful masks and values for bit twiddling +var MASK31 = 0x7fffffff, VAL31 = 0x80000000; +var MASK32 = 0xffffffff, VAL32 = 0x100000000; + +// Map for converting hex octets to strings +var _HEX = []; +for (var i = 0; i < 256; i++) { + _HEX[i] = (i > 0xF ? '' : '0') + i.toString(16); +} + +// +// Int64 +// + +/** + * Constructor accepts any of the following argument types: + * + * new Int64(buffer[, offset=0]) - Existing Buffer with byte offset + * new Int64(Uint8Array[, offset=0]) - Existing Uint8Array with a byte offset + * new Int64(string) - Hex string (throws if n is outside int64 range) + * new Int64(number) - Number (throws if n is outside int64 range) + * new Int64(hi, lo) - Raw bits as two 32-bit values + */ +var Int64 = module.exports = function(a1, a2) { + if (a1 instanceof Buffer) { + this.buffer = a1; + this.offset = a2 || 0; + } else if (Object.prototype.toString.call(a1) == '[object Uint8Array]') { + // Under Browserify, Buffers can extend Uint8Arrays rather than an + // instance of Buffer. We could assume the passed in Uint8Array is actually + // a buffer but that won't handle the case where a raw Uint8Array is passed + // in. We construct a new Buffer just in case. + this.buffer = new Buffer(a1); + this.offset = a2 || 0; + } else { + this.buffer = this.buffer || new Buffer(8); + this.offset = 0; + this.setValue.apply(this, arguments); + } +}; + + +// Max integer value that JS can accurately represent +Int64.MAX_INT = Math.pow(2, 53); + +// Min integer value that JS can accurately represent +Int64.MIN_INT = -Math.pow(2, 53); + +Int64.prototype = { + + constructor: Int64, + + /** + * Do in-place 2's compliment. See + * http://en.wikipedia.org/wiki/Two's_complement + */ + _2scomp: function() { + var b = this.buffer, o = this.offset, carry = 1; + for (var i = o + 7; i >= o; i--) { + var v = (b[i] ^ 0xff) + carry; + b[i] = v & 0xff; + carry = v >> 8; + } + }, + + /** + * Set the value. Takes any of the following arguments: + * + * setValue(string) - A hexidecimal string + * setValue(number) - Number (throws if n is outside int64 range) + * setValue(hi, lo) - Raw bits as two 32-bit values + */ + setValue: function(hi, lo) { + var negate = false; + if (arguments.length == 1) { + if (typeof(hi) == 'number') { + // Simplify bitfield retrieval by using abs() value. We restore sign + // later + negate = hi < 0; + hi = Math.abs(hi); + lo = hi % VAL32; + hi = hi / VAL32; + if (hi > VAL32) throw new RangeError(hi + ' is outside Int64 range'); + hi = hi | 0; + } else if (typeof(hi) == 'string') { + hi = (hi + '').replace(/^0x/, ''); + lo = hi.substr(-8); + hi = hi.length > 8 ? hi.substr(0, hi.length - 8) : ''; + hi = parseInt(hi, 16); + lo = parseInt(lo, 16); + } else { + throw new Error(hi + ' must be a Number or String'); + } + } + + // Technically we should throw if hi or lo is outside int32 range here, but + // it's not worth the effort. Anything past the 32'nd bit is ignored. + + // Copy bytes to buffer + var b = this.buffer, o = this.offset; + for (var i = 7; i >= 0; i--) { + b[o+i] = lo & 0xff; + lo = i == 4 ? hi : lo >>> 8; + } + + // Restore sign of passed argument + if (negate) this._2scomp(); + }, + + /** + * Convert to a native JS number. + * + * WARNING: Do not expect this value to be accurate to integer precision for + * large (positive or negative) numbers! + * + * @param allowImprecise If true, no check is performed to verify the + * returned value is accurate to integer precision. If false, imprecise + * numbers (very large positive or negative numbers) will be forced to +/- + * Infinity. + */ + toNumber: function(allowImprecise) { + var b = this.buffer, o = this.offset; + + // Running sum of octets, doing a 2's complement + var negate = b[o] & 0x80, x = 0, carry = 1; + for (var i = 7, m = 1; i >= 0; i--, m *= 256) { + var v = b[o+i]; + + // 2's complement for negative numbers + if (negate) { + v = (v ^ 0xff) + carry; + carry = v >> 8; + v = v & 0xff; + } + + x += v * m; + } + + // Return Infinity if we've lost integer precision + if (!allowImprecise && x >= Int64.MAX_INT) { + return negate ? -Infinity : Infinity; + } + + return negate ? -x : x; + }, + + /** + * Convert to a JS Number. Returns +/-Infinity for values that can't be + * represented to integer precision. + */ + valueOf: function() { + return this.toNumber(false); + }, + + /** + * Return string value + * + * @param radix Just like Number#toString()'s radix + */ + toString: function(radix) { + return this.valueOf().toString(radix || 10); + }, + + /** + * Return a string showing the buffer octets, with MSB on the left. + * + * @param sep separator string. default is '' (empty string) + */ + toOctetString: function(sep) { + var out = new Array(8); + var b = this.buffer, o = this.offset; + for (var i = 0; i < 8; i++) { + out[i] = _HEX[b[o+i]]; + } + return out.join(sep || ''); + }, + + /** + * Returns the int64's 8 bytes in a buffer. + * + * @param {bool} [rawBuffer=false] If no offset and this is true, return the internal buffer. Should only be used if + * you're discarding the Int64 afterwards, as it breaks encapsulation. + */ + toBuffer: function(rawBuffer) { + if (rawBuffer && this.offset === 0) return this.buffer; + + var out = new Buffer(8); + this.buffer.copy(out, 0, this.offset, this.offset + 8); + return out; + }, + + /** + * Copy 8 bytes of int64 into target buffer at target offset. + * + * @param {Buffer} targetBuffer Buffer to copy into. + * @param {number} [targetOffset=0] Offset into target buffer. + */ + copy: function(targetBuffer, targetOffset) { + this.buffer.copy(targetBuffer, targetOffset || 0, this.offset, this.offset + 8); + }, + + /** + * Returns a number indicating whether this comes before or after or is the + * same as the other in sort order. + * + * @param {Int64} other Other Int64 to compare. + */ + compare: function(other) { + + // If sign bits differ ... + if ((this.buffer[this.offset] & 0x80) != (other.buffer[other.offset] & 0x80)) { + return other.buffer[other.offset] - this.buffer[this.offset]; + } + + // otherwise, compare bytes lexicographically + for (var i = 0; i < 8; i++) { + if (this.buffer[this.offset+i] !== other.buffer[other.offset+i]) { + return this.buffer[this.offset+i] - other.buffer[other.offset+i]; + } + } + return 0; + }, + + /** + * Returns a boolean indicating if this integer is equal to other. + * + * @param {Int64} other Other Int64 to compare. + */ + equals: function(other) { + return this.compare(other) === 0; + }, + + /** + * Pretty output in console.log + */ + inspect: function() { + return '[Int64 value:' + this + ' octets:' + this.toOctetString(' ') + ']'; + } +}; diff --git a/node_modules/node-int64/LICENSE b/node_modules/node-int64/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ddb6a9051edeba15bf12355e6e0bb429936d2d72 --- /dev/null +++ b/node_modules/node-int64/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Robert Kieffer + +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. diff --git a/node_modules/node-int64/README.md b/node_modules/node-int64/README.md new file mode 100644 index 0000000000000000000000000000000000000000..efef18a71205f5125d1429ed1c774bc988f785f4 --- /dev/null +++ b/node_modules/node-int64/README.md @@ -0,0 +1,78 @@ +JavaScript Numbers are represented as [IEEE 754 double-precision floats](http://steve.hollasch.net/cgindex/coding/ieeefloat.html). Unfortunately, this means they lose integer precision for values beyond +/- 2^^53. For projects that need to accurately handle 64-bit ints, such as [node-thrift](https://github.com/wadey/node-thrift), a performant, Number-like class is needed. Int64 is that class. + +Int64 instances look and feel much like JS-native Numbers. By way of example ... +```js +// First, let's illustrate the problem ... +> (0x123456789).toString(16) +'123456789' // <- what we expect. +> (0x123456789abcdef0).toString(16) +'123456789abcdf00' // <- Ugh! JS doesn't do big ints. :( + +// So let's create a couple Int64s using the above values ... + +// Require, of course +> Int64 = require('node-int64') + +// x's value is what we expect (the decimal value of 0x123456789) +> x = new Int64(0x123456789) +[Int64 value:4886718345 octets:00 00 00 01 23 45 67 89] + +// y's value is Infinity because it's outside the range of integer +// precision. But that's okay - it's still useful because it's internal +// representation (octets) is what we passed in +> y = new Int64('123456789abcdef0') +[Int64 value:Infinity octets:12 34 56 78 9a bc de f0] + +// Let's do some math. Int64's behave like Numbers. (Sorry, Int64 isn't +// for doing 64-bit integer arithmetic (yet) - it's just for carrying +// around int64 values +> x + 1 +4886718346 +> y + 1 +Infinity + +// Int64 string operations ... +> 'value: ' + x +'value: 4886718345' +> 'value: ' + y +'value: Infinity' +> x.toString(2) +'100100011010001010110011110001001' +> y.toString(2) +'Infinity' + +// Use JS's isFinite() method to see if the Int64 value is in the +// integer-precise range of JS values +> isFinite(x) +true +> isFinite(y) +false + +// Get an octet string representation. (Yay, y is what we put in!) +> x.toOctetString() +'0000000123456789' +> y.toOctetString() +'123456789abcdef0' + +// Finally, some other ways to create Int64s ... + +// Pass hi/lo words +> new Int64(0x12345678, 0x9abcdef0) +[Int64 value:Infinity octets:12 34 56 78 9a bc de f0] + +// Pass a Buffer +> new Int64(new Buffer([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0])) +[Int64 value:Infinity octets:12 34 56 78 9a bc de f0] + +// Pass a Buffer and offset +> new Int64(new Buffer([0,0,0,0,0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0]), 4) +[Int64 value:Infinity octets:12 34 56 78 9a bc de f0] + +// Pull out into a buffer +> new Int64(new Buffer([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0])).toBuffer() + + +// Or copy into an existing one (at an offset) +> var buf = new Buffer(1024); +> new Int64(new Buffer([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0])).copy(buf, 512); +``` diff --git a/node_modules/node-int64/package.json b/node_modules/node-int64/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3f56f5b9aa5fb7ff776c72de3a7a2fc47c4f485f --- /dev/null +++ b/node_modules/node-int64/package.json @@ -0,0 +1,27 @@ +{ + "name": "node-int64", + "description": "Support for representing 64-bit integers in JavaScript", + "url": "http://github.com/broofa/node-int64", + "keywords": [ + "math", + "integer", + "int64" + ], + "author": "Robert Kieffer ", + "contributors": [], + "dependencies": {}, + "license": "MIT", + "lib": ".", + "main": "./Int64.js", + "version": "0.4.0", + "scripts": { + "test": "nodeunit test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/broofa/node-int64" + }, + "devDependencies": { + "nodeunit": "^0.9.0" + } +} diff --git a/node_modules/node-int64/test.js b/node_modules/node-int64/test.js new file mode 100644 index 0000000000000000000000000000000000000000..cdf4303d786b1ac957b0a7aac623a4dba280b914 --- /dev/null +++ b/node_modules/node-int64/test.js @@ -0,0 +1,120 @@ +var assert = require('assert'); +var Int64 = require('./Int64'); + +exports.setUp = function(done) { + done(); +}; + +exports.testBufferToString = function(test) { + var int = new Int64(0xfffaffff, 0xfffff700); + test.equal( + int.toBuffer().toString('hex'), + 'fffafffffffff700', + 'Buffer to string conversion' + ); + test.done(); +}; + +exports.testBufferCopy = function(test) { + var src = new Int64(0xfffaffff, 0xfffff700); + var dst = new Buffer(8); + + src.copy(dst); + + test.deepEqual( + dst, + new Buffer([0xff, 0xfa, 0xff, 0xff, 0xff, 0xff, 0xf7, 0x00]), + 'Copy to buffer' + ); + + test.done(); +}; + +exports.testValueRepresentation = function(test) { + var args = [ + [0], '0000000000000000', 0, + [1], '0000000000000001', 1, + [-1], 'ffffffffffffffff', -1, + [1e18], '0de0b6b3a7640000', 1e18, + ['0001234500654321'], '0001234500654321', 0x1234500654321, + ['0ff1234500654321'], '0ff1234500654321', 0xff1234500654300, // Imprecise! + [0xff12345, 0x654321], '0ff1234500654321', 0xff1234500654300, // Imprecise! + [0xfffaffff, 0xfffff700],'fffafffffffff700', -0x5000000000900, + [0xafffffff, 0xfffff700],'affffffffffff700', -0x5000000000000800, // Imprecise! + ['0x0000123450654321'], '0000123450654321', 0x123450654321, + ['0xFFFFFFFFFFFFFFFF'], 'ffffffffffffffff', -1 + ]; + + // Test constructor argments + + for (var i = 0; i < args.length; i += 3) { + var a = args[i], octets = args[i+1], number = args[i+2]; + + // Create instance + var x = new Int64(); + Int64.apply(x, a); + + test.equal(x.toOctetString(), octets, 'Constuctor with ' + args.join(', ')); + test.equal(x.toNumber(true), number); + } + + test.done(); +}; + +exports.testBufferOffsets = function(test) { + var sourceBuffer = new Buffer(16); + sourceBuffer.writeUInt32BE(0xfffaffff, 2); + sourceBuffer.writeUInt32BE(0xfffff700, 6); + + var int = new Int64(sourceBuffer, 2); + assert.equal( + int.toBuffer().toString('hex'), 'fffafffffffff700', + 'Construct from offset' + ); + + var targetBuffer = new Buffer(16); + int.copy(targetBuffer, 4); + assert.equal( + targetBuffer.slice(4, 12).toString('hex'), 'fffafffffffff700', + 'Copy to offset' + ); + + test.done(); +}; + +exports.testInstanceOf = function(test) { + var x = new Int64(); + assert(x instanceof Int64, 'Variable is not instance of Int64'); + var y = {}; + assert(!(y instanceof Int64), 'Object is an instance of Int64'); + test.done(); +}; + +exports.testCompare = function(test) { + var intMin = new Int64(2147483648, 0); + var intMinPlusOne = new Int64(2147483648, 1); + var zero = new Int64(0, 0); + var intMaxMinusOne = new Int64(2147483647, 4294967294); + var intMax = new Int64(2147483647, 4294967295); + assert(intMin.compare(intMinPlusOne) < 0, "INT64_MIN is not less than INT64_MIN+1"); + assert(intMin.compare(zero) < 0, "INT64_MIN is not less than 0"); + assert(intMin.compare(zero) < intMax, "INT64_MIN is not less than INT64_MAX"); + assert(intMax.compare(intMaxMinusOne) > 0, "INT64_MAX is not greater than INT64_MAX-1"); + assert(intMax.compare(zero) > 0, "INT64_MAX is not greater than 0"); + assert(intMax.compare(intMin) > 0, "INT64_MAX is not greater than INT_MIN"); + test.done(); +}; + +exports.testEquals = function(test) { + var intMin = new Int64(2147483648, 0); + var zero = new Int64(0, 0); + var intMax = new Int64(2147483647, 4294967295); + assert(intMin.equals(intMin), "INT64_MIN !== INT64_MIN"); + assert(intMax.equals(intMax), "INT64_MAX !== INT64_MAX"); + assert(zero.equals(zero), "0 !== 0"); + assert(!intMin.equals(zero), "INT64_MIN === 0"); + assert(!intMin.equals(intMax), "INT64_MIN === INT64_MAX"); + assert(!intMax.equals(zero), "INT64_MAX === 0"); + assert(!intMax.equals(intMin), "INT64_MAX === INT64_MIN"); + test.done(); +}; diff --git a/node_modules/node-releases/LICENSE b/node_modules/node-releases/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ea39e4f9b798bd59194c506f5b711380affb3b29 --- /dev/null +++ b/node_modules/node-releases/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2017 Sergey Rubanov (https://github.com/chicoxyzzy) + +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. diff --git a/node_modules/node-releases/README.md b/node_modules/node-releases/README.md new file mode 100644 index 0000000000000000000000000000000000000000..56f6166725ea2c22ec131f292d5672f9ae28f9f7 --- /dev/null +++ b/node_modules/node-releases/README.md @@ -0,0 +1,32 @@ +# Node.js releases data + +[![npm version](https://img.shields.io/npm/v/node-releases.svg)](https://www.npmjs.com/package/node-releases) +[![License: MIT](https://img.shields.io/npm/l/node-releases.svg)](./LICENSE) + +All data is located in `data` directory. + +`data/processed` contains `envs.json` with node.js releases data preprocessed to be used by [Browserslist](https://github.com/ai/browserslist) and other projects. Each version in this file contains only necessary info: version, release date, LTS flag/name, and security flag. + +`data/release-schedule` contains `release-schedule.json` with node.js releases date and end of life date. + +## Installation + +```bash +npm install node-releases +``` + +## Usage + +```js +// CommonJS +const envs = require('node-releases/data/processed/envs.json'); +const schedule = require('node-releases/data/release-schedule/release-schedule.json'); + +// ESM (Node.js 22+) +import envs from 'node-releases/data/processed/envs.json' with { type: 'json' }; +import schedule from 'node-releases/data/release-schedule/release-schedule.json' with { type: 'json' }; +``` + +## Releases + +Releases are published automatically by a nightly GitHub Actions workflow whenever upstream Node.js release data changes. Publishing uses [npm trusted publishing](https://docs.npmjs.com/trusted-publishers) (OIDC, no long-lived tokens) and ships [provenance attestations](https://docs.npmjs.com/generating-provenance-statements). diff --git a/node_modules/node-releases/data/processed/envs.json b/node_modules/node-releases/data/processed/envs.json new file mode 100644 index 0000000000000000000000000000000000000000..c80abb50a5ac9068ea41b7df98ce7c7226b1628e --- /dev/null +++ b/node_modules/node-releases/data/processed/envs.json @@ -0,0 +1,2930 @@ +[ + { + "name": "nodejs", + "version": "0.2.0", + "date": "2011-08-26", + "lts": false, + "security": false, + "v8": "2.3.8.0" + }, + { + "name": "nodejs", + "version": "0.3.0", + "date": "2011-08-26", + "lts": false, + "security": false, + "v8": "2.5.1.0" + }, + { + "name": "nodejs", + "version": "0.4.0", + "date": "2011-08-26", + "lts": false, + "security": false, + "v8": "3.1.2.0" + }, + { + "name": "nodejs", + "version": "0.5.0", + "date": "2011-08-26", + "lts": false, + "security": false, + "v8": "3.1.8.25" + }, + { + "name": "nodejs", + "version": "0.6.0", + "date": "2011-11-04", + "lts": false, + "security": false, + "v8": "3.6.6.6" + }, + { + "name": "nodejs", + "version": "0.7.0", + "date": "2012-01-17", + "lts": false, + "security": false, + "v8": "3.8.6.0" + }, + { + "name": "nodejs", + "version": "0.8.0", + "date": "2012-06-22", + "lts": false, + "security": false, + "v8": "3.11.10.10" + }, + { + "name": "nodejs", + "version": "0.9.0", + "date": "2012-07-20", + "lts": false, + "security": false, + "v8": "3.11.10.15" + }, + { + "name": "nodejs", + "version": "0.10.0", + "date": "2013-03-11", + "lts": false, + "security": false, + "v8": "3.14.5.8" + }, + { + "name": "nodejs", + "version": "0.11.0", + "date": "2013-03-28", + "lts": false, + "security": false, + "v8": "3.17.13.0" + }, + { + "name": "nodejs", + "version": "0.12.0", + "date": "2015-02-06", + "lts": false, + "security": false, + "v8": "3.28.73.0" + }, + { + "name": "nodejs", + "version": "4.0.0", + "date": "2015-09-08", + "lts": false, + "security": false, + "v8": "4.5.103.30" + }, + { + "name": "nodejs", + "version": "4.1.0", + "date": "2015-09-17", + "lts": false, + "security": false, + "v8": "4.5.103.33" + }, + { + "name": "nodejs", + "version": "4.2.0", + "date": "2015-10-12", + "lts": "Argon", + "security": false, + "v8": "4.5.103.35" + }, + { + "name": "nodejs", + "version": "4.3.0", + "date": "2016-02-09", + "lts": "Argon", + "security": false, + "v8": "4.5.103.35" + }, + { + "name": "nodejs", + "version": "4.4.0", + "date": "2016-03-08", + "lts": "Argon", + "security": false, + "v8": "4.5.103.35" + }, + { + "name": "nodejs", + "version": "4.5.0", + "date": "2016-08-16", + "lts": "Argon", + "security": false, + "v8": "4.5.103.37" + }, + { + "name": "nodejs", + "version": "4.6.0", + "date": "2016-09-27", + "lts": "Argon", + "security": true, + "v8": "4.5.103.37" + }, + { + "name": "nodejs", + "version": "4.7.0", + "date": "2016-12-06", + "lts": "Argon", + "security": false, + "v8": "4.5.103.43" + }, + { + "name": "nodejs", + "version": "4.8.0", + "date": "2017-02-21", + "lts": "Argon", + "security": false, + "v8": "4.5.103.45" + }, + { + "name": "nodejs", + "version": "4.9.0", + "date": "2018-03-28", + "lts": "Argon", + "security": true, + "v8": "4.5.103.53" + }, + { + "name": "nodejs", + "version": "5.0.0", + "date": "2015-10-29", + "lts": false, + "security": false, + "v8": "4.6.85.28" + }, + { + "name": "nodejs", + "version": "5.1.0", + "date": "2015-11-17", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.2.0", + "date": "2015-12-09", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.3.0", + "date": "2015-12-15", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.4.0", + "date": "2016-01-06", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.5.0", + "date": "2016-01-21", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.6.0", + "date": "2016-02-09", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.7.0", + "date": "2016-02-23", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.8.0", + "date": "2016-03-09", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.9.0", + "date": "2016-03-16", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.10.0", + "date": "2016-04-01", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.11.0", + "date": "2016-04-21", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.12.0", + "date": "2016-06-23", + "lts": false, + "security": false, + "v8": "4.6.85.32" + }, + { + "name": "nodejs", + "version": "6.0.0", + "date": "2016-04-26", + "lts": false, + "security": false, + "v8": "5.0.71.35" + }, + { + "name": "nodejs", + "version": "6.1.0", + "date": "2016-05-05", + "lts": false, + "security": false, + "v8": "5.0.71.35" + }, + { + "name": "nodejs", + "version": "6.2.0", + "date": "2016-05-17", + "lts": false, + "security": false, + "v8": "5.0.71.47" + }, + { + "name": "nodejs", + "version": "6.3.0", + "date": "2016-07-06", + "lts": false, + "security": false, + "v8": "5.0.71.52" + }, + { + "name": "nodejs", + "version": "6.4.0", + "date": "2016-08-12", + "lts": false, + "security": false, + "v8": "5.0.71.60" + }, + { + "name": "nodejs", + "version": "6.5.0", + "date": "2016-08-26", + "lts": false, + "security": false, + "v8": "5.1.281.81" + }, + { + "name": "nodejs", + "version": "6.6.0", + "date": "2016-09-14", + "lts": false, + "security": false, + "v8": "5.1.281.83" + }, + { + "name": "nodejs", + "version": "6.7.0", + "date": "2016-09-27", + "lts": false, + "security": true, + "v8": "5.1.281.83" + }, + { + "name": "nodejs", + "version": "6.8.0", + "date": "2016-10-12", + "lts": false, + "security": false, + "v8": "5.1.281.84" + }, + { + "name": "nodejs", + "version": "6.9.0", + "date": "2016-10-18", + "lts": "Boron", + "security": false, + "v8": "5.1.281.84" + }, + { + "name": "nodejs", + "version": "6.10.0", + "date": "2017-02-21", + "lts": "Boron", + "security": false, + "v8": "5.1.281.93" + }, + { + "name": "nodejs", + "version": "6.11.0", + "date": "2017-06-06", + "lts": "Boron", + "security": false, + "v8": "5.1.281.102" + }, + { + "name": "nodejs", + "version": "6.12.0", + "date": "2017-11-06", + "lts": "Boron", + "security": false, + "v8": "5.1.281.108" + }, + { + "name": "nodejs", + "version": "6.13.0", + "date": "2018-02-10", + "lts": "Boron", + "security": false, + "v8": "5.1.281.111" + }, + { + "name": "nodejs", + "version": "6.14.0", + "date": "2018-03-28", + "lts": "Boron", + "security": true, + "v8": "5.1.281.111" + }, + { + "name": "nodejs", + "version": "6.15.0", + "date": "2018-11-27", + "lts": "Boron", + "security": true, + "v8": "5.1.281.111" + }, + { + "name": "nodejs", + "version": "6.16.0", + "date": "2018-12-26", + "lts": "Boron", + "security": false, + "v8": "5.1.281.111" + }, + { + "name": "nodejs", + "version": "6.17.0", + "date": "2019-02-28", + "lts": "Boron", + "security": true, + "v8": "5.1.281.111" + }, + { + "name": "nodejs", + "version": "7.0.0", + "date": "2016-10-25", + "lts": false, + "security": false, + "v8": "5.4.500.36" + }, + { + "name": "nodejs", + "version": "7.1.0", + "date": "2016-11-08", + "lts": false, + "security": false, + "v8": "5.4.500.36" + }, + { + "name": "nodejs", + "version": "7.2.0", + "date": "2016-11-22", + "lts": false, + "security": false, + "v8": "5.4.500.43" + }, + { + "name": "nodejs", + "version": "7.3.0", + "date": "2016-12-20", + "lts": false, + "security": false, + "v8": "5.4.500.45" + }, + { + "name": "nodejs", + "version": "7.4.0", + "date": "2017-01-04", + "lts": false, + "security": false, + "v8": "5.4.500.45" + }, + { + "name": "nodejs", + "version": "7.5.0", + "date": "2017-01-31", + "lts": false, + "security": false, + "v8": "5.4.500.48" + }, + { + "name": "nodejs", + "version": "7.6.0", + "date": "2017-02-21", + "lts": false, + "security": false, + "v8": "5.5.372.40" + }, + { + "name": "nodejs", + "version": "7.7.0", + "date": "2017-02-28", + "lts": false, + "security": false, + "v8": "5.5.372.41" + }, + { + "name": "nodejs", + "version": "7.8.0", + "date": "2017-03-29", + "lts": false, + "security": false, + "v8": "5.5.372.43" + }, + { + "name": "nodejs", + "version": "7.9.0", + "date": "2017-04-11", + "lts": false, + "security": false, + "v8": "5.5.372.43" + }, + { + "name": "nodejs", + "version": "7.10.0", + "date": "2017-05-02", + "lts": false, + "security": false, + "v8": "5.5.372.43" + }, + { + "name": "nodejs", + "version": "8.0.0", + "date": "2017-05-30", + "lts": false, + "security": false, + "v8": "5.8.283.41" + }, + { + "name": "nodejs", + "version": "8.1.0", + "date": "2017-06-08", + "lts": false, + "security": false, + "v8": "5.8.283.41" + }, + { + "name": "nodejs", + "version": "8.2.0", + "date": "2017-07-19", + "lts": false, + "security": false, + "v8": "5.8.283.41" + }, + { + "name": "nodejs", + "version": "8.3.0", + "date": "2017-08-08", + "lts": false, + "security": false, + "v8": "6.0.286.52" + }, + { + "name": "nodejs", + "version": "8.4.0", + "date": "2017-08-15", + "lts": false, + "security": false, + "v8": "6.0.286.52" + }, + { + "name": "nodejs", + "version": "8.5.0", + "date": "2017-09-12", + "lts": false, + "security": false, + "v8": "6.0.287.53" + }, + { + "name": "nodejs", + "version": "8.6.0", + "date": "2017-09-26", + "lts": false, + "security": false, + "v8": "6.0.287.53" + }, + { + "name": "nodejs", + "version": "8.7.0", + "date": "2017-10-11", + "lts": false, + "security": false, + "v8": "6.1.534.42" + }, + { + "name": "nodejs", + "version": "8.8.0", + "date": "2017-10-24", + "lts": false, + "security": false, + "v8": "6.1.534.42" + }, + { + "name": "nodejs", + "version": "8.9.0", + "date": "2017-10-31", + "lts": "Carbon", + "security": false, + "v8": "6.1.534.46" + }, + { + "name": "nodejs", + "version": "8.10.0", + "date": "2018-03-06", + "lts": "Carbon", + "security": false, + "v8": "6.2.414.50" + }, + { + "name": "nodejs", + "version": "8.11.0", + "date": "2018-03-28", + "lts": "Carbon", + "security": true, + "v8": "6.2.414.50" + }, + { + "name": "nodejs", + "version": "8.12.0", + "date": "2018-09-10", + "lts": "Carbon", + "security": false, + "v8": "6.2.414.66" + }, + { + "name": "nodejs", + "version": "8.13.0", + "date": "2018-11-20", + "lts": "Carbon", + "security": false, + "v8": "6.2.414.72" + }, + { + "name": "nodejs", + "version": "8.14.0", + "date": "2018-11-27", + "lts": "Carbon", + "security": true, + "v8": "6.2.414.72" + }, + { + "name": "nodejs", + "version": "8.15.0", + "date": "2018-12-26", + "lts": "Carbon", + "security": false, + "v8": "6.2.414.75" + }, + { + "name": "nodejs", + "version": "8.16.0", + "date": "2019-04-16", + "lts": "Carbon", + "security": false, + "v8": "6.2.414.77" + }, + { + "name": "nodejs", + "version": "8.17.0", + "date": "2019-12-17", + "lts": "Carbon", + "security": true, + "v8": "6.2.414.78" + }, + { + "name": "nodejs", + "version": "9.0.0", + "date": "2017-10-31", + "lts": false, + "security": false, + "v8": "6.2.414.32" + }, + { + "name": "nodejs", + "version": "9.1.0", + "date": "2017-11-07", + "lts": false, + "security": false, + "v8": "6.2.414.32" + }, + { + "name": "nodejs", + "version": "9.2.0", + "date": "2017-11-14", + "lts": false, + "security": false, + "v8": "6.2.414.44" + }, + { + "name": "nodejs", + "version": "9.3.0", + "date": "2017-12-12", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.4.0", + "date": "2018-01-10", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.5.0", + "date": "2018-01-31", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.6.0", + "date": "2018-02-21", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.7.0", + "date": "2018-03-01", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.8.0", + "date": "2018-03-07", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.9.0", + "date": "2018-03-21", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.10.0", + "date": "2018-03-28", + "lts": false, + "security": true, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.11.0", + "date": "2018-04-04", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "10.0.0", + "date": "2018-04-24", + "lts": false, + "security": false, + "v8": "6.6.346.24" + }, + { + "name": "nodejs", + "version": "10.1.0", + "date": "2018-05-08", + "lts": false, + "security": false, + "v8": "6.6.346.27" + }, + { + "name": "nodejs", + "version": "10.2.0", + "date": "2018-05-23", + "lts": false, + "security": false, + "v8": "6.6.346.32" + }, + { + "name": "nodejs", + "version": "10.3.0", + "date": "2018-05-29", + "lts": false, + "security": false, + "v8": "6.6.346.32" + }, + { + "name": "nodejs", + "version": "10.4.0", + "date": "2018-06-06", + "lts": false, + "security": false, + "v8": "6.7.288.43" + }, + { + "name": "nodejs", + "version": "10.5.0", + "date": "2018-06-20", + "lts": false, + "security": false, + "v8": "6.7.288.46" + }, + { + "name": "nodejs", + "version": "10.6.0", + "date": "2018-07-04", + "lts": false, + "security": false, + "v8": "6.7.288.46" + }, + { + "name": "nodejs", + "version": "10.7.0", + "date": "2018-07-18", + "lts": false, + "security": false, + "v8": "6.7.288.49" + }, + { + "name": "nodejs", + "version": "10.8.0", + "date": "2018-08-01", + "lts": false, + "security": false, + "v8": "6.7.288.49" + }, + { + "name": "nodejs", + "version": "10.9.0", + "date": "2018-08-15", + "lts": false, + "security": false, + "v8": "6.8.275.24" + }, + { + "name": "nodejs", + "version": "10.10.0", + "date": "2018-09-06", + "lts": false, + "security": false, + "v8": "6.8.275.30" + }, + { + "name": "nodejs", + "version": "10.11.0", + "date": "2018-09-19", + "lts": false, + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.12.0", + "date": "2018-10-10", + "lts": false, + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.13.0", + "date": "2018-10-30", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.14.0", + "date": "2018-11-27", + "lts": "Dubnium", + "security": true, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.15.0", + "date": "2018-12-26", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.16.0", + "date": "2019-05-28", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.17.0", + "date": "2019-10-22", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.18.0", + "date": "2019-12-17", + "lts": "Dubnium", + "security": true, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.19.0", + "date": "2020-02-05", + "lts": "Dubnium", + "security": true, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.20.0", + "date": "2020-03-26", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.21.0", + "date": "2020-06-02", + "lts": "Dubnium", + "security": true, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.22.0", + "date": "2020-07-21", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.23.0", + "date": "2020-10-27", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.24.0", + "date": "2021-02-23", + "lts": "Dubnium", + "security": true, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "11.0.0", + "date": "2018-10-23", + "lts": false, + "security": false, + "v8": "7.0.276.28" + }, + { + "name": "nodejs", + "version": "11.1.0", + "date": "2018-10-30", + "lts": false, + "security": false, + "v8": "7.0.276.32" + }, + { + "name": "nodejs", + "version": "11.2.0", + "date": "2018-11-15", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.3.0", + "date": "2018-11-27", + "lts": false, + "security": true, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.4.0", + "date": "2018-12-07", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.5.0", + "date": "2018-12-18", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.6.0", + "date": "2018-12-26", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.7.0", + "date": "2019-01-17", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.8.0", + "date": "2019-01-24", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.9.0", + "date": "2019-01-30", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.10.0", + "date": "2019-02-14", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.11.0", + "date": "2019-03-05", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.12.0", + "date": "2019-03-14", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.13.0", + "date": "2019-03-28", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.14.0", + "date": "2019-04-10", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.15.0", + "date": "2019-04-30", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "12.0.0", + "date": "2019-04-23", + "lts": false, + "security": false, + "v8": "7.4.288.21" + }, + { + "name": "nodejs", + "version": "12.1.0", + "date": "2019-04-29", + "lts": false, + "security": false, + "v8": "7.4.288.21" + }, + { + "name": "nodejs", + "version": "12.2.0", + "date": "2019-05-07", + "lts": false, + "security": false, + "v8": "7.4.288.21" + }, + { + "name": "nodejs", + "version": "12.3.0", + "date": "2019-05-21", + "lts": false, + "security": false, + "v8": "7.4.288.27" + }, + { + "name": "nodejs", + "version": "12.4.0", + "date": "2019-06-04", + "lts": false, + "security": false, + "v8": "7.4.288.27" + }, + { + "name": "nodejs", + "version": "12.5.0", + "date": "2019-06-26", + "lts": false, + "security": false, + "v8": "7.5.288.22" + }, + { + "name": "nodejs", + "version": "12.6.0", + "date": "2019-07-03", + "lts": false, + "security": false, + "v8": "7.5.288.22" + }, + { + "name": "nodejs", + "version": "12.7.0", + "date": "2019-07-23", + "lts": false, + "security": false, + "v8": "7.5.288.22" + }, + { + "name": "nodejs", + "version": "12.8.0", + "date": "2019-08-06", + "lts": false, + "security": false, + "v8": "7.5.288.22" + }, + { + "name": "nodejs", + "version": "12.9.0", + "date": "2019-08-20", + "lts": false, + "security": false, + "v8": "7.6.303.29" + }, + { + "name": "nodejs", + "version": "12.10.0", + "date": "2019-09-04", + "lts": false, + "security": false, + "v8": "7.6.303.29" + }, + { + "name": "nodejs", + "version": "12.11.0", + "date": "2019-09-25", + "lts": false, + "security": false, + "v8": "7.7.299.11" + }, + { + "name": "nodejs", + "version": "12.12.0", + "date": "2019-10-11", + "lts": false, + "security": false, + "v8": "7.7.299.13" + }, + { + "name": "nodejs", + "version": "12.13.0", + "date": "2019-10-21", + "lts": "Erbium", + "security": false, + "v8": "7.7.299.13" + }, + { + "name": "nodejs", + "version": "12.14.0", + "date": "2019-12-17", + "lts": "Erbium", + "security": true, + "v8": "7.7.299.13" + }, + { + "name": "nodejs", + "version": "12.15.0", + "date": "2020-02-05", + "lts": "Erbium", + "security": true, + "v8": "7.7.299.13" + }, + { + "name": "nodejs", + "version": "12.16.0", + "date": "2020-02-11", + "lts": "Erbium", + "security": false, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "12.17.0", + "date": "2020-05-26", + "lts": "Erbium", + "security": false, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "12.18.0", + "date": "2020-06-02", + "lts": "Erbium", + "security": true, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "12.19.0", + "date": "2020-10-06", + "lts": "Erbium", + "security": false, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "12.20.0", + "date": "2020-11-24", + "lts": "Erbium", + "security": false, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "12.21.0", + "date": "2021-02-23", + "lts": "Erbium", + "security": true, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "12.22.0", + "date": "2021-03-30", + "lts": "Erbium", + "security": false, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "13.0.0", + "date": "2019-10-22", + "lts": false, + "security": false, + "v8": "7.8.279.17" + }, + { + "name": "nodejs", + "version": "13.1.0", + "date": "2019-11-05", + "lts": false, + "security": false, + "v8": "7.8.279.17" + }, + { + "name": "nodejs", + "version": "13.2.0", + "date": "2019-11-21", + "lts": false, + "security": false, + "v8": "7.9.317.23" + }, + { + "name": "nodejs", + "version": "13.3.0", + "date": "2019-12-03", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.4.0", + "date": "2019-12-17", + "lts": false, + "security": true, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.5.0", + "date": "2019-12-18", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.6.0", + "date": "2020-01-07", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.7.0", + "date": "2020-01-21", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.8.0", + "date": "2020-02-05", + "lts": false, + "security": true, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.9.0", + "date": "2020-02-18", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.10.0", + "date": "2020-03-04", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.11.0", + "date": "2020-03-12", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.12.0", + "date": "2020-03-26", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.13.0", + "date": "2020-04-14", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.14.0", + "date": "2020-04-29", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "14.0.0", + "date": "2020-04-21", + "lts": false, + "security": false, + "v8": "8.1.307.30" + }, + { + "name": "nodejs", + "version": "14.1.0", + "date": "2020-04-29", + "lts": false, + "security": false, + "v8": "8.1.307.31" + }, + { + "name": "nodejs", + "version": "14.2.0", + "date": "2020-05-05", + "lts": false, + "security": false, + "v8": "8.1.307.31" + }, + { + "name": "nodejs", + "version": "14.3.0", + "date": "2020-05-19", + "lts": false, + "security": false, + "v8": "8.1.307.31" + }, + { + "name": "nodejs", + "version": "14.4.0", + "date": "2020-06-02", + "lts": false, + "security": true, + "v8": "8.1.307.31" + }, + { + "name": "nodejs", + "version": "14.5.0", + "date": "2020-06-30", + "lts": false, + "security": false, + "v8": "8.3.110.9" + }, + { + "name": "nodejs", + "version": "14.6.0", + "date": "2020-07-20", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.7.0", + "date": "2020-07-29", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.8.0", + "date": "2020-08-11", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.9.0", + "date": "2020-08-27", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.10.0", + "date": "2020-09-08", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.11.0", + "date": "2020-09-15", + "lts": false, + "security": true, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.12.0", + "date": "2020-09-22", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.13.0", + "date": "2020-09-29", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.14.0", + "date": "2020-10-15", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.15.0", + "date": "2020-10-27", + "lts": "Fermium", + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.16.0", + "date": "2021-02-23", + "lts": "Fermium", + "security": true, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.17.0", + "date": "2021-05-11", + "lts": "Fermium", + "security": false, + "v8": "8.4.371.23" + }, + { + "name": "nodejs", + "version": "14.18.0", + "date": "2021-09-28", + "lts": "Fermium", + "security": false, + "v8": "8.4.371.23" + }, + { + "name": "nodejs", + "version": "14.19.0", + "date": "2022-02-01", + "lts": "Fermium", + "security": false, + "v8": "8.4.371.23" + }, + { + "name": "nodejs", + "version": "14.20.0", + "date": "2022-07-07", + "lts": "Fermium", + "security": true, + "v8": "8.4.371.23" + }, + { + "name": "nodejs", + "version": "14.21.0", + "date": "2022-11-01", + "lts": "Fermium", + "security": false, + "v8": "8.4.371.23" + }, + { + "name": "nodejs", + "version": "15.0.0", + "date": "2020-10-20", + "lts": false, + "security": false, + "v8": "8.6.395.16" + }, + { + "name": "nodejs", + "version": "15.1.0", + "date": "2020-11-04", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.2.0", + "date": "2020-11-10", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.3.0", + "date": "2020-11-24", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.4.0", + "date": "2020-12-09", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.5.0", + "date": "2020-12-22", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.6.0", + "date": "2021-01-14", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.7.0", + "date": "2021-01-25", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.8.0", + "date": "2021-02-02", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.9.0", + "date": "2021-02-18", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.10.0", + "date": "2021-02-23", + "lts": false, + "security": true, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.11.0", + "date": "2021-03-03", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.12.0", + "date": "2021-03-17", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.13.0", + "date": "2021-03-31", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.14.0", + "date": "2021-04-06", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "16.0.0", + "date": "2021-04-20", + "lts": false, + "security": false, + "v8": "9.0.257.17" + }, + { + "name": "nodejs", + "version": "16.1.0", + "date": "2021-05-04", + "lts": false, + "security": false, + "v8": "9.0.257.24" + }, + { + "name": "nodejs", + "version": "16.2.0", + "date": "2021-05-19", + "lts": false, + "security": false, + "v8": "9.0.257.25" + }, + { + "name": "nodejs", + "version": "16.3.0", + "date": "2021-06-03", + "lts": false, + "security": false, + "v8": "9.0.257.25" + }, + { + "name": "nodejs", + "version": "16.4.0", + "date": "2021-06-23", + "lts": false, + "security": false, + "v8": "9.1.269.36" + }, + { + "name": "nodejs", + "version": "16.5.0", + "date": "2021-07-14", + "lts": false, + "security": false, + "v8": "9.1.269.38" + }, + { + "name": "nodejs", + "version": "16.6.0", + "date": "2021-07-29", + "lts": false, + "security": true, + "v8": "9.2.230.21" + }, + { + "name": "nodejs", + "version": "16.7.0", + "date": "2021-08-18", + "lts": false, + "security": false, + "v8": "9.2.230.21" + }, + { + "name": "nodejs", + "version": "16.8.0", + "date": "2021-08-25", + "lts": false, + "security": false, + "v8": "9.2.230.21" + }, + { + "name": "nodejs", + "version": "16.9.0", + "date": "2021-09-07", + "lts": false, + "security": false, + "v8": "9.3.345.16" + }, + { + "name": "nodejs", + "version": "16.10.0", + "date": "2021-09-22", + "lts": false, + "security": false, + "v8": "9.3.345.19" + }, + { + "name": "nodejs", + "version": "16.11.0", + "date": "2021-10-08", + "lts": false, + "security": false, + "v8": "9.4.146.19" + }, + { + "name": "nodejs", + "version": "16.12.0", + "date": "2021-10-20", + "lts": false, + "security": false, + "v8": "9.4.146.19" + }, + { + "name": "nodejs", + "version": "16.13.0", + "date": "2021-10-26", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.19" + }, + { + "name": "nodejs", + "version": "16.14.0", + "date": "2022-02-08", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.24" + }, + { + "name": "nodejs", + "version": "16.15.0", + "date": "2022-04-26", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.24" + }, + { + "name": "nodejs", + "version": "16.16.0", + "date": "2022-07-07", + "lts": "Gallium", + "security": true, + "v8": "9.4.146.24" + }, + { + "name": "nodejs", + "version": "16.17.0", + "date": "2022-08-16", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.26" + }, + { + "name": "nodejs", + "version": "16.18.0", + "date": "2022-10-12", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.26" + }, + { + "name": "nodejs", + "version": "16.19.0", + "date": "2022-12-13", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.26" + }, + { + "name": "nodejs", + "version": "16.20.0", + "date": "2023-03-28", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.26" + }, + { + "name": "nodejs", + "version": "17.0.0", + "date": "2021-10-19", + "lts": false, + "security": false, + "v8": "9.5.172.21" + }, + { + "name": "nodejs", + "version": "17.1.0", + "date": "2021-11-09", + "lts": false, + "security": false, + "v8": "9.5.172.25" + }, + { + "name": "nodejs", + "version": "17.2.0", + "date": "2021-11-30", + "lts": false, + "security": false, + "v8": "9.6.180.14" + }, + { + "name": "nodejs", + "version": "17.3.0", + "date": "2021-12-17", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "17.4.0", + "date": "2022-01-18", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "17.5.0", + "date": "2022-02-10", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "17.6.0", + "date": "2022-02-22", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "17.7.0", + "date": "2022-03-09", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "17.8.0", + "date": "2022-03-22", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "17.9.0", + "date": "2022-04-07", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "18.0.0", + "date": "2022-04-18", + "lts": false, + "security": false, + "v8": "10.1.124.8" + }, + { + "name": "nodejs", + "version": "18.1.0", + "date": "2022-05-03", + "lts": false, + "security": false, + "v8": "10.1.124.8" + }, + { + "name": "nodejs", + "version": "18.2.0", + "date": "2022-05-17", + "lts": false, + "security": false, + "v8": "10.1.124.8" + }, + { + "name": "nodejs", + "version": "18.3.0", + "date": "2022-06-02", + "lts": false, + "security": false, + "v8": "10.2.154.4" + }, + { + "name": "nodejs", + "version": "18.4.0", + "date": "2022-06-16", + "lts": false, + "security": false, + "v8": "10.2.154.4" + }, + { + "name": "nodejs", + "version": "18.5.0", + "date": "2022-07-06", + "lts": false, + "security": true, + "v8": "10.2.154.4" + }, + { + "name": "nodejs", + "version": "18.6.0", + "date": "2022-07-13", + "lts": false, + "security": false, + "v8": "10.2.154.13" + }, + { + "name": "nodejs", + "version": "18.7.0", + "date": "2022-07-26", + "lts": false, + "security": false, + "v8": "10.2.154.13" + }, + { + "name": "nodejs", + "version": "18.8.0", + "date": "2022-08-24", + "lts": false, + "security": false, + "v8": "10.2.154.13" + }, + { + "name": "nodejs", + "version": "18.9.0", + "date": "2022-09-07", + "lts": false, + "security": false, + "v8": "10.2.154.15" + }, + { + "name": "nodejs", + "version": "18.10.0", + "date": "2022-09-28", + "lts": false, + "security": false, + "v8": "10.2.154.15" + }, + { + "name": "nodejs", + "version": "18.11.0", + "date": "2022-10-13", + "lts": false, + "security": false, + "v8": "10.2.154.15" + }, + { + "name": "nodejs", + "version": "18.12.0", + "date": "2022-10-25", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.15" + }, + { + "name": "nodejs", + "version": "18.13.0", + "date": "2023-01-05", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.23" + }, + { + "name": "nodejs", + "version": "18.14.0", + "date": "2023-02-01", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.23" + }, + { + "name": "nodejs", + "version": "18.15.0", + "date": "2023-03-05", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.26" + }, + { + "name": "nodejs", + "version": "18.16.0", + "date": "2023-04-12", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.26" + }, + { + "name": "nodejs", + "version": "18.17.0", + "date": "2023-07-18", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.26" + }, + { + "name": "nodejs", + "version": "18.18.0", + "date": "2023-09-18", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.26" + }, + { + "name": "nodejs", + "version": "18.19.0", + "date": "2023-11-29", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.26" + }, + { + "name": "nodejs", + "version": "18.20.0", + "date": "2024-03-26", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.26" + }, + { + "name": "nodejs", + "version": "19.0.0", + "date": "2022-10-17", + "lts": false, + "security": false, + "v8": "10.7.193.13" + }, + { + "name": "nodejs", + "version": "19.1.0", + "date": "2022-11-14", + "lts": false, + "security": false, + "v8": "10.7.193.20" + }, + { + "name": "nodejs", + "version": "19.2.0", + "date": "2022-11-29", + "lts": false, + "security": false, + "v8": "10.8.168.20" + }, + { + "name": "nodejs", + "version": "19.3.0", + "date": "2022-12-14", + "lts": false, + "security": false, + "v8": "10.8.168.21" + }, + { + "name": "nodejs", + "version": "19.4.0", + "date": "2023-01-05", + "lts": false, + "security": false, + "v8": "10.8.168.25" + }, + { + "name": "nodejs", + "version": "19.5.0", + "date": "2023-01-24", + "lts": false, + "security": false, + "v8": "10.8.168.25" + }, + { + "name": "nodejs", + "version": "19.6.0", + "date": "2023-02-01", + "lts": false, + "security": false, + "v8": "10.8.168.25" + }, + { + "name": "nodejs", + "version": "19.7.0", + "date": "2023-02-21", + "lts": false, + "security": false, + "v8": "10.8.168.25" + }, + { + "name": "nodejs", + "version": "19.8.0", + "date": "2023-03-14", + "lts": false, + "security": false, + "v8": "10.8.168.25" + }, + { + "name": "nodejs", + "version": "19.9.0", + "date": "2023-04-10", + "lts": false, + "security": false, + "v8": "10.8.168.25" + }, + { + "name": "nodejs", + "version": "20.0.0", + "date": "2023-04-17", + "lts": false, + "security": false, + "v8": "11.3.244.4" + }, + { + "name": "nodejs", + "version": "20.1.0", + "date": "2023-05-03", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.2.0", + "date": "2023-05-16", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.3.0", + "date": "2023-06-08", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.4.0", + "date": "2023-07-04", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.5.0", + "date": "2023-07-19", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.6.0", + "date": "2023-08-23", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.7.0", + "date": "2023-09-18", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.8.0", + "date": "2023-09-28", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.9.0", + "date": "2023-10-24", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.10.0", + "date": "2023-11-22", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.11.0", + "date": "2024-01-09", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.12.0", + "date": "2024-03-26", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.13.0", + "date": "2024-05-07", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.14.0", + "date": "2024-05-28", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.15.0", + "date": "2024-06-20", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.16.0", + "date": "2024-07-24", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.17.0", + "date": "2024-08-21", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.18.0", + "date": "2024-10-03", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.19.0", + "date": "2025-03-13", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.20.0", + "date": "2026-01-12", + "lts": "Iron", + "security": true, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "21.0.0", + "date": "2023-10-17", + "lts": false, + "security": false, + "v8": "11.8.172.13" + }, + { + "name": "nodejs", + "version": "21.1.0", + "date": "2023-10-24", + "lts": false, + "security": false, + "v8": "11.8.172.15" + }, + { + "name": "nodejs", + "version": "21.2.0", + "date": "2023-11-14", + "lts": false, + "security": false, + "v8": "11.8.172.17" + }, + { + "name": "nodejs", + "version": "21.3.0", + "date": "2023-11-30", + "lts": false, + "security": false, + "v8": "11.8.172.17" + }, + { + "name": "nodejs", + "version": "21.4.0", + "date": "2023-12-05", + "lts": false, + "security": false, + "v8": "11.8.172.17" + }, + { + "name": "nodejs", + "version": "21.5.0", + "date": "2023-12-19", + "lts": false, + "security": false, + "v8": "11.8.172.17" + }, + { + "name": "nodejs", + "version": "21.6.0", + "date": "2024-01-14", + "lts": false, + "security": false, + "v8": "11.8.172.17" + }, + { + "name": "nodejs", + "version": "21.7.0", + "date": "2024-03-06", + "lts": false, + "security": false, + "v8": "11.8.172.17" + }, + { + "name": "nodejs", + "version": "22.0.0", + "date": "2024-04-24", + "lts": false, + "security": false, + "v8": "12.4.254.14" + }, + { + "name": "nodejs", + "version": "22.1.0", + "date": "2024-05-02", + "lts": false, + "security": false, + "v8": "12.4.254.14" + }, + { + "name": "nodejs", + "version": "22.2.0", + "date": "2024-05-15", + "lts": false, + "security": false, + "v8": "12.4.254.14" + }, + { + "name": "nodejs", + "version": "22.3.0", + "date": "2024-06-11", + "lts": false, + "security": false, + "v8": "12.4.254.20" + }, + { + "name": "nodejs", + "version": "22.4.0", + "date": "2024-07-02", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.5.0", + "date": "2024-07-17", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.6.0", + "date": "2024-08-06", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.7.0", + "date": "2024-08-21", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.8.0", + "date": "2024-09-03", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.9.0", + "date": "2024-09-17", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.10.0", + "date": "2024-10-16", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.11.0", + "date": "2024-10-29", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.12.0", + "date": "2024-12-02", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.13.0", + "date": "2025-01-06", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.14.0", + "date": "2025-02-11", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.15.0", + "date": "2025-04-22", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.16.0", + "date": "2025-05-20", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.17.0", + "date": "2025-06-24", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.18.0", + "date": "2025-07-31", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.19.0", + "date": "2025-08-28", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.20.0", + "date": "2025-09-24", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.21.0", + "date": "2025-10-20", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.22.0", + "date": "2026-01-12", + "lts": "Jod", + "security": true, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "23.0.0", + "date": "2024-10-16", + "lts": false, + "security": false, + "v8": "12.9.202.26" + }, + { + "name": "nodejs", + "version": "23.1.0", + "date": "2024-10-24", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.2.0", + "date": "2024-11-11", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.3.0", + "date": "2024-11-20", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.4.0", + "date": "2024-12-10", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.5.0", + "date": "2024-12-19", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.6.0", + "date": "2025-01-07", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.7.0", + "date": "2025-01-30", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.8.0", + "date": "2025-02-13", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.9.0", + "date": "2025-02-26", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.10.0", + "date": "2025-03-13", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.11.0", + "date": "2025-04-01", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "24.0.0", + "date": "2025-05-06", + "lts": false, + "security": false, + "v8": "13.6.233.8" + }, + { + "name": "nodejs", + "version": "24.1.0", + "date": "2025-05-20", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.2.0", + "date": "2025-06-09", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.3.0", + "date": "2025-06-24", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.4.0", + "date": "2025-07-09", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.5.0", + "date": "2025-07-31", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.6.0", + "date": "2025-08-14", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.7.0", + "date": "2025-08-27", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.8.0", + "date": "2025-09-10", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.9.0", + "date": "2025-09-25", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.10.0", + "date": "2025-10-08", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.11.0", + "date": "2025-10-28", + "lts": "Krypton", + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.12.0", + "date": "2025-12-10", + "lts": "Krypton", + "security": false, + "v8": "13.6.233.17" + }, + { + "name": "nodejs", + "version": "24.13.0", + "date": "2026-01-12", + "lts": "Krypton", + "security": true, + "v8": "13.6.233.17" + }, + { + "name": "nodejs", + "version": "24.14.0", + "date": "2026-02-24", + "lts": "Krypton", + "security": false, + "v8": "13.6.233.17" + }, + { + "name": "nodejs", + "version": "24.15.0", + "date": "2026-04-15", + "lts": "Krypton", + "security": false, + "v8": "13.6.233.17" + }, + { + "name": "nodejs", + "version": "24.16.0", + "date": "2026-05-21", + "lts": "Krypton", + "security": false, + "v8": "13.6.233.17" + }, + { + "name": "nodejs", + "version": "25.0.0", + "date": "2025-10-15", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.1.0", + "date": "2025-10-28", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.2.0", + "date": "2025-11-11", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.3.0", + "date": "2026-01-12", + "lts": false, + "security": true, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.4.0", + "date": "2026-01-19", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.5.0", + "date": "2026-01-26", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.6.0", + "date": "2026-02-02", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.7.0", + "date": "2026-02-24", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.8.0", + "date": "2026-03-03", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.9.0", + "date": "2026-03-31", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "26.0.0", + "date": "2026-05-05", + "lts": false, + "security": false, + "v8": "14.6.202.33" + }, + { + "name": "nodejs", + "version": "26.1.0", + "date": "2026-05-06", + "lts": false, + "security": false, + "v8": "14.6.202.34" + }, + { + "name": "nodejs", + "version": "26.2.0", + "date": "2026-05-20", + "lts": false, + "security": false, + "v8": "14.6.202.34" + }, + { + "name": "nodejs", + "version": "26.3.0", + "date": "2026-06-01", + "lts": false, + "security": false, + "v8": "14.6.202.34" + } +] diff --git a/node_modules/node-releases/data/release-schedule/release-schedule.json b/node_modules/node-releases/data/release-schedule/release-schedule.json new file mode 100644 index 0000000000000000000000000000000000000000..3a6af719fb943a16a672eeb81dec0a04500d7a59 --- /dev/null +++ b/node_modules/node-releases/data/release-schedule/release-schedule.json @@ -0,0 +1,160 @@ +{ + "v0.8": { + "start": "2012-06-25", + "end": "2014-07-31" + }, + "v0.10": { + "start": "2013-03-11", + "end": "2016-10-31" + }, + "v0.12": { + "start": "2015-02-06", + "end": "2016-12-31" + }, + "v4": { + "start": "2015-09-08", + "lts": "2015-10-12", + "maintenance": "2017-04-01", + "end": "2018-04-30", + "codename": "Argon" + }, + "v5": { + "start": "2015-10-29", + "maintenance": "2016-04-30", + "end": "2016-06-30" + }, + "v6": { + "start": "2016-04-26", + "lts": "2016-10-18", + "maintenance": "2018-04-30", + "end": "2019-04-30", + "codename": "Boron" + }, + "v7": { + "start": "2016-10-25", + "maintenance": "2017-04-30", + "end": "2017-06-30" + }, + "v8": { + "start": "2017-05-30", + "lts": "2017-10-31", + "maintenance": "2019-01-01", + "end": "2019-12-31", + "codename": "Carbon" + }, + "v9": { + "start": "2017-10-01", + "maintenance": "2018-04-01", + "end": "2018-06-30" + }, + "v10": { + "start": "2018-04-24", + "lts": "2018-10-30", + "maintenance": "2020-05-19", + "end": "2021-04-30", + "codename": "Dubnium" + }, + "v11": { + "start": "2018-10-23", + "maintenance": "2019-04-22", + "end": "2019-06-01" + }, + "v12": { + "start": "2019-04-23", + "lts": "2019-10-21", + "maintenance": "2020-11-30", + "end": "2022-04-30", + "codename": "Erbium" + }, + "v13": { + "start": "2019-10-22", + "maintenance": "2020-04-01", + "end": "2020-06-01" + }, + "v14": { + "start": "2020-04-21", + "lts": "2020-10-27", + "maintenance": "2021-10-19", + "end": "2023-04-30", + "codename": "Fermium" + }, + "v15": { + "start": "2020-10-20", + "maintenance": "2021-04-01", + "end": "2021-06-01" + }, + "v16": { + "start": "2021-04-20", + "lts": "2021-10-26", + "maintenance": "2022-10-18", + "end": "2023-09-11", + "codename": "Gallium" + }, + "v17": { + "start": "2021-10-19", + "maintenance": "2022-04-01", + "end": "2022-06-01" + }, + "v18": { + "start": "2022-04-19", + "lts": "2022-10-25", + "maintenance": "2023-10-18", + "end": "2025-04-30", + "codename": "Hydrogen" + }, + "v19": { + "start": "2022-10-18", + "maintenance": "2023-04-01", + "end": "2023-06-01" + }, + "v20": { + "start": "2023-04-18", + "lts": "2023-10-24", + "maintenance": "2024-10-22", + "end": "2026-04-30", + "codename": "Iron" + }, + "v21": { + "start": "2023-10-17", + "maintenance": "2024-04-01", + "end": "2024-06-01" + }, + "v22": { + "start": "2024-04-24", + "lts": "2024-10-29", + "maintenance": "2025-10-21", + "end": "2027-04-30", + "codename": "Jod" + }, + "v23": { + "start": "2024-10-16", + "maintenance": "2025-04-01", + "end": "2025-06-01" + }, + "v24": { + "start": "2025-05-06", + "lts": "2025-10-28", + "maintenance": "2026-10-20", + "end": "2028-04-30", + "codename": "Krypton" + }, + "v25": { + "start": "2025-10-15", + "maintenance": "2026-04-01", + "end": "2026-06-01" + }, + "v26": { + "start": "2026-05-05", + "lts": "2026-10-28", + "maintenance": "2027-10-20", + "end": "2029-04-30", + "codename": "" + }, + "v27": { + "alpha": "2026-10-28", + "start": "2027-04-22", + "maintenance": "2027-10-20", + "end": "2030-04-30", + "codename": "" + } +} diff --git a/node_modules/node-releases/package.json b/node_modules/node-releases/package.json new file mode 100644 index 0000000000000000000000000000000000000000..10547bbc7bb18709d6ea0afbfac11496aeaedbde --- /dev/null +++ b/node_modules/node-releases/package.json @@ -0,0 +1,28 @@ +{ + "name": "node-releases", + "version": "2.0.47", + "description": "Node.js releases data", + "type": "module", + "files": [ + "data" + ], + "scripts": { + "build": "node scripts/build.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/chicoxyzzy/node-releases.git" + }, + "keywords": [ + "nodejs", + "releases" + ], + "author": "Sergey Rubanov ", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "devDependencies": { + "semver": "^7.3.5" + } +} diff --git a/node_modules/nodemailer/.gitattributes b/node_modules/nodemailer/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..0318d52404261711841f40ce05e9df5998e0039f --- /dev/null +++ b/node_modules/nodemailer/.gitattributes @@ -0,0 +1,6 @@ +*.js text eol=lf +*.txt text eol=lf +*.html text eol=lf +*.htm text eol=lf +*.ics -text +*.bin -text \ No newline at end of file diff --git a/node_modules/nodemailer/.ncurc.js b/node_modules/nodemailer/.ncurc.js new file mode 100644 index 0000000000000000000000000000000000000000..391ac07a3d6e118bb2aed24b7c688b0b67cdff48 --- /dev/null +++ b/node_modules/nodemailer/.ncurc.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = { + upgrade: true, + reject: [ + // API changes break existing tests + 'proxy' + ] +}; diff --git a/node_modules/nodemailer/.prettierignore b/node_modules/nodemailer/.prettierignore new file mode 100644 index 0000000000000000000000000000000000000000..ad770c2c31ab804167557d7ecb36f6f9e397800e --- /dev/null +++ b/node_modules/nodemailer/.prettierignore @@ -0,0 +1,8 @@ +node_modules +coverage +*.min.js +dist +build +.nyc_output +package-lock.json +CHANGELOG.md diff --git a/node_modules/nodemailer/.prettierrc b/node_modules/nodemailer/.prettierrc new file mode 100644 index 0000000000000000000000000000000000000000..5e2bbe38a9f8a5ff08fe8dccb1855b1a34d4d192 --- /dev/null +++ b/node_modules/nodemailer/.prettierrc @@ -0,0 +1,12 @@ +{ + "printWidth": 140, + "tabWidth": 4, + "useTabs": false, + "semi": true, + "singleQuote": true, + "quoteProps": "as-needed", + "trailingComma": "none", + "bracketSpacing": true, + "arrowParens": "avoid", + "endOfLine": "lf" +} diff --git a/node_modules/nodemailer/.prettierrc.js b/node_modules/nodemailer/.prettierrc.js new file mode 100644 index 0000000000000000000000000000000000000000..1a6faac392b1be03c3950ae3afbe5d626721ae0a --- /dev/null +++ b/node_modules/nodemailer/.prettierrc.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + printWidth: 160, + tabWidth: 4, + singleQuote: true, + endOfLine: 'lf', + trailingComma: 'none', + arrowParens: 'avoid' +}; diff --git a/node_modules/nodemailer/.release-please-config.json b/node_modules/nodemailer/.release-please-config.json new file mode 100644 index 0000000000000000000000000000000000000000..6241d575e964ebe677d51cdb46ae78d87d1e3029 --- /dev/null +++ b/node_modules/nodemailer/.release-please-config.json @@ -0,0 +1,9 @@ +{ + "packages": { + ".": { + "release-type": "node", + "package-name": "nodemailer", + "pull-request-title-pattern": "chore${scope}: release ${version} [skip-ci]" + } + } +} diff --git a/node_modules/nodemailer/CHANGELOG.md b/node_modules/nodemailer/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..889de6b4a90b7064ec314c554a4fd0dc2ba5eb21 --- /dev/null +++ b/node_modules/nodemailer/CHANGELOG.md @@ -0,0 +1,1040 @@ +# CHANGELOG + +## [8.0.11](https://github.com/nodemailer/nodemailer/compare/v8.0.10...v8.0.11) (2026-06-10) + + +### Bug Fixes + +* apply the transport-level newline option in stream and sendmail transports ([cb4f904](https://github.com/nodemailer/nodemailer/commit/cb4f904a53d2c2feeaf327203c92378d46304398)) +* include icalEvent path/href content in the application/ics attachment ([b801c48](https://github.com/nodemailer/nodemailer/commit/b801c48fab8e9b71bc7e0ea1fb32ce6b34675b15)) +* parse Ethereal response props without polynomial regex backtracking ([067aebe](https://github.com/nodemailer/nodemailer/commit/067aebec83b8cbe7682905e89b30ab19d260b503)) +* resolve oauth2_provision_cb at send time for non-pooled SMTP transports ([203c8ec](https://github.com/nodemailer/nodemailer/commit/203c8ecf97594ac2e69919b0f3ba966c0f86750e)) +* return the promise from every resolveContent branch ([07ffe8c](https://github.com/nodemailer/nodemailer/commit/07ffe8cfd97f0486b8c7b541f398922ddab47882)) +* strip the url scheme from List-ID header values ([77e5885](https://github.com/nodemailer/nodemailer/commit/77e5885cfa0c6723ea7749c1ee74b1c11aeb78bd)) +* tag AWS SES transport errors with the ESES code ([efa647a](https://github.com/nodemailer/nodemailer/commit/efa647a125dd698413a7cf6813b8e36881a06f91)) + +## [8.0.10](https://github.com/nodemailer/nodemailer/compare/v8.0.9...v8.0.10) (2026-05-29) + + +### Bug Fixes + +* fall back to lower-severity handler when custom logger lacks a level method ([6d849df](https://github.com/nodemailer/nodemailer/commit/6d849df59a56184b48844ed10b5fb7b8e9f74634)) + +## [8.0.9](https://github.com/nodemailer/nodemailer/compare/v8.0.8...v8.0.9) (2026-05-26) + + +### Bug Fixes + +* two pending security advisories (jsonTransport access bypass, List-* CRLF injection) ([#1820](https://github.com/nodemailer/nodemailer/issues/1820)) ([5f69497](https://github.com/nodemailer/nodemailer/commit/5f694977da2e0e13dc947037566e8e689a01217e)) + +## [8.0.8](https://github.com/nodemailer/nodemailer/compare/v8.0.7...v8.0.8) (2026-05-23) + + +### Bug Fixes + +* enforce strict TLS for OAuth2 and Ethereal credential requests ([#1818](https://github.com/nodemailer/nodemailer/issues/1818)) ([833d6e5](https://github.com/nodemailer/nodemailer/commit/833d6e58c8b717962bbb1b23e16923cd267c3bc9)) +* four listener/stream leaks in SMTP transport, connection, pool ([#1817](https://github.com/nodemailer/nodemailer/issues/1817)) ([850bb91](https://github.com/nodemailer/nodemailer/commit/850bb91bff7707ed498c1424df01c4e5b30ea14b)) + +## [8.0.7](https://github.com/nodemailer/nodemailer/compare/v8.0.6...v8.0.7) (2026-04-27) + + +### Bug Fixes + +* keep domain as UTF-8 when local part is non-ASCII ([#1814](https://github.com/nodemailer/nodemailer/issues/1814)) ([66d4ecb](https://github.com/nodemailer/nodemailer/commit/66d4ecb5aa431f3614a26b3c08b9c63cdf32a9ea)) + +## [8.0.6](https://github.com/nodemailer/nodemailer/compare/v8.0.5...v8.0.6) (2026-04-24) + + +### Bug Fixes + +* restore base64 wrap() trim behavior to prevent trailing CRLF ([#1810](https://github.com/nodemailer/nodemailer/issues/1810)) ([#1811](https://github.com/nodemailer/nodemailer/issues/1811)) ([b1ae6c1](https://github.com/nodemailer/nodemailer/commit/b1ae6c1c2927240737d9f68f316f0c84042b8adb)) + +## [8.0.5](https://github.com/nodemailer/nodemailer/compare/v8.0.4...v8.0.5) (2026-04-07) + + +### Bug Fixes + +* decode SMTP server responses as UTF-8 at line boundary ([95876b1](https://github.com/nodemailer/nodemailer/commit/95876b103e587e49583e43f88cb2c3a61556f3ac)) +* sanitize CRLF in transport name option to prevent SMTP command injection (GHSA-vvjj-xcjg-gr5g) ([0a43876](https://github.com/nodemailer/nodemailer/commit/0a43876801a420ca528f492eaa01bfc421cc306e)) + +## [8.0.4](https://github.com/nodemailer/nodemailer/compare/v8.0.3...v8.0.4) (2026-03-25) + + +### Bug Fixes + +* sanitize envelope size to prevent SMTP command injection ([2d7b971](https://github.com/nodemailer/nodemailer/commit/2d7b9710e63555a1eb13d721296c51186d4b5651)) + +## [8.0.3](https://github.com/nodemailer/nodemailer/compare/v8.0.2...v8.0.3) (2026-03-18) + + +### Bug Fixes + +* clean up addressparser and fix group name fallback producing undefined ([9d55877](https://github.com/nodemailer/nodemailer/commit/9d55877f8ed15a6aefd7ba76cbb6b6a6cdbcc4fd)) +* fix cookie bugs, remove dead code, and improve hot-path efficiency ([e8c8b92](https://github.com/nodemailer/nodemailer/commit/e8c8b92f46f2a82d06d49cc9a6ffc26067f68524)) +* refactor smtp-connection for clarity and add Node.js 6 syntax compat test ([c5b48ea](https://github.com/nodemailer/nodemailer/commit/c5b48ea61c28eabf347972f4198a12cdab226ff7)) +* remove familySupportCache that broke DNS resolution tests ([c803d90](https://github.com/nodemailer/nodemailer/commit/c803d901f195a21edbb2c276b2e116564467aaaa)) + +## [8.0.2](https://github.com/nodemailer/nodemailer/compare/v8.0.1...v8.0.2) (2026-03-09) + + +### Bug Fixes + +* merge fragmented display names with unquoted commas in addressparser ([fe27f7f](https://github.com/nodemailer/nodemailer/commit/fe27f7fd57f7587d897274438da2f628ad0ad7d9)) + +## [8.0.1](https://github.com/nodemailer/nodemailer/compare/v8.0.0...v8.0.1) (2026-02-07) + + +### Bug Fixes + +* absorb TLS errors during socket teardown ([7f8dde4](https://github.com/nodemailer/nodemailer/commit/7f8dde41438c66b8311e888fa5f8c518fcaba6f1)) +* absorb TLS errors during socket teardown ([381f628](https://github.com/nodemailer/nodemailer/commit/381f628d55e62bb3131bd2a452fa1ce00bc48aea)) +* Add Gmail Workspace service configuration ([#1787](https://github.com/nodemailer/nodemailer/issues/1787)) ([dc97ede](https://github.com/nodemailer/nodemailer/commit/dc97ede417b3030b311771541b1f17f5ca76bcbf)) + +## [8.0.0](https://github.com/nodemailer/nodemailer/compare/v7.0.13...v8.0.0) (2026-02-04) + + +### ⚠ BREAKING CHANGES + +* Error code 'NoAuth' renamed to 'ENOAUTH' + +### Bug Fixes + +* add connection fallback to alternative DNS addresses ([e726d6f](https://github.com/nodemailer/nodemailer/commit/e726d6f44aa7ca14e943d4303243cb5494b09c75)) +* centralize and standardize error codes ([45062ce](https://github.com/nodemailer/nodemailer/commit/45062ce7a4705f3e63c5d9e606547f4d99fd29b5)) +* harden DNS fallback against race conditions and cleanup issues ([4fa3c63](https://github.com/nodemailer/nodemailer/commit/4fa3c63a1f36aefdbaea7f57a133adc458413a47)) +* improve socket cleanup to prevent potential memory leaks ([6069fdc](https://github.com/nodemailer/nodemailer/commit/6069fdcff68a3eef9a9bb16b2bf5ddb924c02091)) + +## [7.0.13](https://github.com/nodemailer/nodemailer/compare/v7.0.12...v7.0.13) (2026-01-27) + + +### Bug Fixes + +* downgrade transient connection error logs to warn level ([4c041db](https://github.com/nodemailer/nodemailer/commit/4c041db85d560e98bc5e1fd5d5a191835c5b7d2f)) + +## [7.0.12](https://github.com/nodemailer/nodemailer/compare/v7.0.11...v7.0.12) (2025-12-22) + + +### Bug Fixes + +* added support for REQUIRETLS ([#1793](https://github.com/nodemailer/nodemailer/issues/1793)) ([053ce6a](https://github.com/nodemailer/nodemailer/commit/053ce6a772a7c608e6bee7f58ebe9900afbd9b84)) +* use 8bit encoding for message/rfc822 attachments ([adf8611](https://github.com/nodemailer/nodemailer/commit/adf86113217b23ff3cd1191af5cd1d360fcc313b)) + +## [7.0.11](https://github.com/nodemailer/nodemailer/compare/v7.0.10...v7.0.11) (2025-11-26) + + +### Bug Fixes + +* prevent stack overflow DoS in addressparser with deeply nested groups ([b61b9c0](https://github.com/nodemailer/nodemailer/commit/b61b9c0cfd682b6f647754ca338373b68336a150)) + +## [7.0.10](https://github.com/nodemailer/nodemailer/compare/v7.0.9...v7.0.10) (2025-10-23) + + +### Bug Fixes + +* Increase data URI size limit from 100KB to 50MB and preserve content type ([28dbf3f](https://github.com/nodemailer/nodemailer/commit/28dbf3fe129653f5756c150a98dc40593bfb2cfe)) + +## [7.0.9](https://github.com/nodemailer/nodemailer/compare/v7.0.8...v7.0.9) (2025-10-07) + + +### Bug Fixes + +* **release:** Trying to fix release proecess by upgrading Node version in runner ([579fce4](https://github.com/nodemailer/nodemailer/commit/579fce4683eb588891613a6c9a00d8092e8c62d1)) + +## [7.0.8](https://github.com/nodemailer/nodemailer/compare/v7.0.7...v7.0.8) (2025-10-07) + + +### Bug Fixes + +* **addressparser:** flatten nested groups per RFC 5322 ([8f8a77c](https://github.com/nodemailer/nodemailer/commit/8f8a77c67f0ba94ddf4e16c68f604a5920fb5d26)) + +## [7.0.7](https://github.com/nodemailer/nodemailer/compare/v7.0.6...v7.0.7) (2025-10-05) + +### Bug Fixes + +- **addressparser:** Fixed addressparser handling of quoted nested email addresses ([1150d99](https://github.com/nodemailer/nodemailer/commit/1150d99fba77280df2cfb1885c43df23109a8626)) +- **dns:** add memory leak prevention for DNS cache ([0240d67](https://github.com/nodemailer/nodemailer/commit/0240d6795ded6d8008d102161a729f120b6d786a)) +- **linter:** Updated eslint and created prettier formatting task ([df13b74](https://github.com/nodemailer/nodemailer/commit/df13b7487e368acded35e45d0887d23c89c9177a)) +- refresh expired DNS cache on error ([#1759](https://github.com/nodemailer/nodemailer/issues/1759)) ([ea0fc5a](https://github.com/nodemailer/nodemailer/commit/ea0fc5a6633a3546f4b00fcf2f428e9ca732cdb6)) +- resolve linter errors in DNS cache tests ([3b8982c](https://github.com/nodemailer/nodemailer/commit/3b8982c1f24508089a8757b74039000a4498b158)) + +## [7.0.6](https://github.com/nodemailer/nodemailer/compare/v7.0.5...v7.0.6) (2025-08-27) + +### Bug Fixes + +- **encoder:** avoid silent data loss by properly flushing trailing base64 ([#1747](https://github.com/nodemailer/nodemailer/issues/1747)) ([01ae76f](https://github.com/nodemailer/nodemailer/commit/01ae76f2cfe991c0c3fe80170f236da60531496b)) +- handle multiple XOAUTH2 token requests correctly ([#1754](https://github.com/nodemailer/nodemailer/issues/1754)) ([dbe0028](https://github.com/nodemailer/nodemailer/commit/dbe00286351cddf012726a41a96ae613d30a34ee)) +- ReDoS vulnerability in parseDataURI and \_processDataUrl ([#1755](https://github.com/nodemailer/nodemailer/issues/1755)) ([90b3e24](https://github.com/nodemailer/nodemailer/commit/90b3e24d23929ebf9f4e16261049b40ee4055a39)) + +## [7.0.5](https://github.com/nodemailer/nodemailer/compare/v7.0.4...v7.0.5) (2025-07-07) + +### Bug Fixes + +- updated well known delivery service list ([fa2724b](https://github.com/nodemailer/nodemailer/commit/fa2724b337eb8d8fdcdd788fe903980b061316b8)) + +## [7.0.4](https://github.com/nodemailer/nodemailer/compare/v7.0.3...v7.0.4) (2025-06-29) + +### Bug Fixes + +- **pools:** Emit 'clear' once transporter is idle and all connections are closed ([839e286](https://github.com/nodemailer/nodemailer/commit/839e28634c9a93ae4321f399a8c893bf487a09fa)) +- **smtp-connection:** jsdoc public annotation for socket ([#1741](https://github.com/nodemailer/nodemailer/issues/1741)) ([c45c84f](https://github.com/nodemailer/nodemailer/commit/c45c84fe9b8e2ec5e0615ab02d4197473911ab3e)) +- **well-known-services:** Added AliyunQiye ([bb9e6da](https://github.com/nodemailer/nodemailer/commit/bb9e6daffb632d7d8f969359859f88a138de3a48)) + +## [7.0.3](https://github.com/nodemailer/nodemailer/compare/v7.0.2...v7.0.3) (2025-05-08) + +### Bug Fixes + +- **attachments:** Set the default transfer encoding for message/rfc822 attachments as '7bit' ([007d5f3](https://github.com/nodemailer/nodemailer/commit/007d5f3f40908c588f1db46c76de8b64ff429327)) + +## [7.0.2](https://github.com/nodemailer/nodemailer/compare/v7.0.1...v7.0.2) (2025-05-04) + +### Bug Fixes + +- **ses:** Fixed structured from header ([faa9a5e](https://github.com/nodemailer/nodemailer/commit/faa9a5eafaacbaf85de3540466a04636e12729b3)) + +## [7.0.1](https://github.com/nodemailer/nodemailer/compare/v7.0.0...v7.0.1) (2025-05-04) + +### Bug Fixes + +- **ses:** Use formatted FromEmailAddress for SES emails ([821cd09](https://github.com/nodemailer/nodemailer/commit/821cd09002f16c20369cc728b9414c7eb99e4113)) + +## [7.0.0](https://github.com/nodemailer/nodemailer/compare/v6.10.1...v7.0.0) (2025-05-03) + +### ⚠ BREAKING CHANGES + +- SESv2 SDK support, removed older SES SDK v2 and v3 , removed SES rate limiting and idling features + +### Features + +- SESv2 SDK support, removed older SES SDK v2 and v3 , removed SES rate limiting and idling features ([15db667](https://github.com/nodemailer/nodemailer/commit/15db667af2d0a5ed835281cfdbab16ee73b5edce)) + +## [6.10.1](https://github.com/nodemailer/nodemailer/compare/v6.10.0...v6.10.1) (2025-02-06) + +### Bug Fixes + +- close correct socket ([a18062c](https://github.com/nodemailer/nodemailer/commit/a18062c04d0e05ca4357fbe8f0a59b690fa5391e)) + +## [6.10.0](https://github.com/nodemailer/nodemailer/compare/v6.9.16...v6.10.0) (2025-01-23) + +### Features + +- **services:** add Seznam email service configuration ([#1695](https://github.com/nodemailer/nodemailer/issues/1695)) ([d1ae0a8](https://github.com/nodemailer/nodemailer/commit/d1ae0a86883ba6011a49a5bbdf076098e2e3637a)) + +### Bug Fixes + +- **proxy:** Set error and timeout errors for proxied sockets ([aa0c99c](https://github.com/nodemailer/nodemailer/commit/aa0c99c8f25440bb3dc91f4f3448777c800604d7)) + +## [6.9.16](https://github.com/nodemailer/nodemailer/compare/v6.9.15...v6.9.16) (2024-10-28) + +### Bug Fixes + +- **addressparser:** Correctly detect if user local part is attached to domain part ([f2096c5](https://github.com/nodemailer/nodemailer/commit/f2096c51b92a69ecfbcc15884c28cb2c2f00b826)) + +## [6.9.15](https://github.com/nodemailer/nodemailer/compare/v6.9.14...v6.9.15) (2024-08-08) + +### Bug Fixes + +- Fix memory leak ([#1667](https://github.com/nodemailer/nodemailer/issues/1667)) ([baa28f6](https://github.com/nodemailer/nodemailer/commit/baa28f659641a4bc30360633673d851618f8e8bd)) +- **mime:** Added GeoJSON closes [#1637](https://github.com/nodemailer/nodemailer/issues/1637) ([#1665](https://github.com/nodemailer/nodemailer/issues/1665)) ([79b8293](https://github.com/nodemailer/nodemailer/commit/79b8293ad557d36f066b4675e649dd80362fd45b)) + +## [6.9.14](https://github.com/nodemailer/nodemailer/compare/v6.9.13...v6.9.14) (2024-06-19) + +### Bug Fixes + +- **api:** Added support for Ethereal authentication ([56b2205](https://github.com/nodemailer/nodemailer/commit/56b22052a98de9e363f6c4d26d1512925349c3f3)) +- **services.json:** Add Email Services Provider Feishu Mail (CN) ([#1648](https://github.com/nodemailer/nodemailer/issues/1648)) ([e9e9ecc](https://github.com/nodemailer/nodemailer/commit/e9e9ecc99b352948a912868c7912b280a05178c6)) +- **services.json:** update Mailtrap host and port in well known ([#1652](https://github.com/nodemailer/nodemailer/issues/1652)) ([fc2c9ea](https://github.com/nodemailer/nodemailer/commit/fc2c9ea0b4c4f4e514143d2a138c9a23095fc827)) +- **well-known-services:** Add Loopia in well known services ([#1655](https://github.com/nodemailer/nodemailer/issues/1655)) ([21a28a1](https://github.com/nodemailer/nodemailer/commit/21a28a18fc9fdf8e0e86ddd846e54641395b2cb6)) + +## [6.9.13](https://github.com/nodemailer/nodemailer/compare/v6.9.12...v6.9.13) (2024-03-20) + +### Bug Fixes + +- **tls:** Ensure servername for SMTP ([d66fdd3](https://github.com/nodemailer/nodemailer/commit/d66fdd3dccacc4bc79d697fe9009204cc8d4bde0)) + +## [6.9.12](https://github.com/nodemailer/nodemailer/compare/v6.9.11...v6.9.12) (2024-03-08) + +### Bug Fixes + +- **message-generation:** Escape single quote in address names ([4ae5fad](https://github.com/nodemailer/nodemailer/commit/4ae5fadeaac70ba91abf529fcaae65f829a39101)) + +## [6.9.11](https://github.com/nodemailer/nodemailer/compare/v6.9.10...v6.9.11) (2024-02-29) + +### Bug Fixes + +- **headers:** Ensure that Content-type is the bottom header ([c7cf97e](https://github.com/nodemailer/nodemailer/commit/c7cf97e5ecc83f8eee773359951df995c9945446)) + +## [6.9.10](https://github.com/nodemailer/nodemailer/compare/v6.9.9...v6.9.10) (2024-02-22) + +### Bug Fixes + +- **data-uri:** Do not use regular expressions for parsing data URI schemes ([12e65e9](https://github.com/nodemailer/nodemailer/commit/12e65e975d80efe6bafe6de4590829b3b5ebb492)) +- **data-uri:** Moved all data-uri regexes to use the non-regex parseDataUri method ([edd5dfe](https://github.com/nodemailer/nodemailer/commit/edd5dfe5ce9b725f8b8ae2830797f65b2a2b0a33)) + +## [6.9.9](https://github.com/nodemailer/nodemailer/compare/v6.9.8...v6.9.9) (2024-02-01) + +### Bug Fixes + +- **security:** Fix issues described in GHSA-9h6g-pr28-7cqp. Do not use eternal matching pattern if only a few occurences are expected ([dd8f5e8](https://github.com/nodemailer/nodemailer/commit/dd8f5e8a4ddc99992e31df76bcff9c590035cd4a)) +- **tests:** Use native node test runner, added code coverage support, removed grunt ([#1604](https://github.com/nodemailer/nodemailer/issues/1604)) ([be45c1b](https://github.com/nodemailer/nodemailer/commit/be45c1b299d012358d69247019391a02734d70af)) + +## [6.9.8](https://github.com/nodemailer/nodemailer/compare/v6.9.7...v6.9.8) (2023-12-30) + +### Bug Fixes + +- **punycode:** do not use native punycode module ([b4d0e0c](https://github.com/nodemailer/nodemailer/commit/b4d0e0c7cc4b15bc4d9e287f91d1bcaca87508b0)) + +## [6.9.7](https://github.com/nodemailer/nodemailer/compare/v6.9.6...v6.9.7) (2023-10-22) + +### Bug Fixes + +- **customAuth:** Do not require user and pass to be set for custom authentication schemes (fixes [#1584](https://github.com/nodemailer/nodemailer/issues/1584)) ([41d482c](https://github.com/nodemailer/nodemailer/commit/41d482c3f01e26111b06f3e46351b193db3fb5cb)) + +## [6.9.6](https://github.com/nodemailer/nodemailer/compare/v6.9.5...v6.9.6) (2023-10-09) + +### Bug Fixes + +- **inline:** Use 'inline' as the default Content Dispostion value for embedded images ([db32c93](https://github.com/nodemailer/nodemailer/commit/db32c93fefee527bcc239f13056e5d9181a4d8af)) +- **tests:** Removed Node v12 from test matrix as it is not compatible with the test framework anymore ([7fe0a60](https://github.com/nodemailer/nodemailer/commit/7fe0a608ed6bcb70dc6b2de543ebfc3a30abf984)) + +## [6.9.5](https://github.com/nodemailer/nodemailer/compare/v6.9.4...v6.9.5) (2023-09-06) + +### Bug Fixes + +- **license:** Updated license year ([da4744e](https://github.com/nodemailer/nodemailer/commit/da4744e491f3a68f4f68e4073684370592630e01)) + +## 6.9.4 2023-07-19 + +- Renamed SendinBlue to Brevo + +## 6.9.3 2023-05-29 + +- Specified license identifier (was defined as MIT, actual value MIT-0) +- If SMTP server disconnects with a message, process it and include as part of the response error + +## 6.9.2 2023-05-11 + +- Fix uncaught exception on invalid attachment content payload + +## 6.9.1 2023-01-27 + +- Fix base64 encoding for emoji bytes in encoded words + +## 6.9.0 2023-01-12 + +- Do not throw if failed to resolve IPv4 addresses +- Include EHLO extensions in the send response +- fix sendMail function: callback should be optional + +## 6.8.0 2022-09-28 + +- Add DNS timeout (huksley) +- add dns.REFUSED (lucagianfelici) + +## 6.7.8 2022-08-11 + +- Allow to use multiple Reply-To addresses + +## 6.7.7 2022-07-06 + +- Resolver fixes + +## 6.7.5 2022-05-04 + +- No changes, pushing a new README to npmjs.org + +## 6.7.4 2022-04-29 + +- Ensure compatibility with Node 18 +- Replaced Travis with Github Actions + +## 6.7.3 2022-03-21 + +- Typo fixes +- Added stale issue automation fir Github +- Add Infomaniak config to well known service (popod) +- Update Outlook/Hotmail host in well known services (popod) +- fix: DSN recipient gets ignored (KornKalle) + +## 6.7.2 2021-11-26 + +- Fix proxies for account verification + +## 6.7.1 2021-11-15 + +- fix verify on ses-transport (stanofsky) + +## 6.7.0 2021-10-11 + +- Updated DNS resolving logic. If there are multiple responses for a A/AAAA record, then loop these randomly instead of only caching the first one + +## 6.6.5 2021-09-23 + +- Replaced Object.values() and Array.flat() with polyfills to allow using Nodemailer in Node v6+ + +## 6.6.4 2021-09-22 + +- Better compatibility with IPv6-only SMTP hosts (oxzi) +- Fix ses verify for sdk v3 (hannesvdvreken) +- Added SECURITY.txt for contact info + +## 6.6.3 2021-07-14 + +- Do not show passwords in SMTP transaction logs. All passwords used in logging are replaced by `"/* secret */"` + +## 6.6.1 2021-05-23 + +- Fixed address formatting issue where newlines in an email address, if provided via address object, were not properly removed. Reported by tmazeika (#1289) + +## 6.6.0 2021-04-28 + +- Added new option `newline` for MailComposer +- aws ses connection verification (Ognjen Jevremovic) + +## 6.5.0 2021-02-26 + +- Pass through textEncoding to subnodes +- Added support for AWS SES v3 SDK +- Fixed tests + +## 6.4.18 2021-02-11 + +- Updated README + +## 6.4.17 2020-12-11 + +- Allow mixing attachments with caendar alternatives + +## 6.4.16 2020-11-12 + +- Applied updated prettier formating rules + +## 6.4.15 2020-11-06 + +- Minor changes in header key casing + +## 6.4.14 2020-10-14 + +- Disabled postinstall script + +## 6.4.13 2020-10-02 + +- Fix normalizeHeaderKey method for single node messages + +## 6.4.12 2020-09-30 + +- Better handling of attachment filenames that include quote symbols +- Includes all information from the oath2 error response in the error message (Normal Gaussian) [1787f227] + +## 6.4.11 2020-07-29 + +- Fixed escape sequence handling in address parsing + +## 6.4.10 2020-06-17 + +- Fixed RFC822 output for MailComposer when using invalid content-type value. Mostly relevant if message attachments have stragne content-type values set. + +## 6.4.7 2020-05-28 + +- Always set charset=utf-8 for Content-Type headers +- Catch error when using invalid crypto.sign input + +## 6.4.6 2020-03-20 + +- fix: `requeueAttempts=n` should requeue `n` times (Patrick Malouin) [a27ed2f7] + +## 6.4.4 2020-03-01 + +- Add `options.forceAuth` for SMTP (Patrick Malouin) [a27ed2f7] + +## 6.4.3 2020-02-22 + +- Added an option to specify max number of requeues when connection closes unexpectedly (Igor Sechyn) [8a927f5a] + +## 6.4.2 2019-12-11 + +- Fixed bug where array item was used with a potentially empty array + +## 6.4.1 2019-12-07 + +- Fix processing server output with unterminated responses + +## 6.4.0 2019-12-04 + +- Do not use auth if server does not advertise AUTH support [f419b09d] +- add dns.CONNREFUSED (Hiroyuki Okada) [5c4c8ca8] + +## 6.3.1 2019-10-09 + +- Ignore "end" events because it might be "error" after it (dex4er) [72bade9] +- Set username and password on the connection proxy object correctly (UsamaAshraf) [250b1a8] +- Support more DNS errors (madarche) [2391aa4] + +## 6.3.0 2019-07-14 + +- Added new option to pass a set of httpHeaders to be sent when fetching attachments. See [PR #1034](https://github.com/nodemailer/nodemailer/pull/1034) + +## 6.2.1 2019-05-24 + +- No changes. It is the same as 6.2.0 that was accidentally published as 6.2.1 to npm + +## 6.2.0 2019-05-24 + +- Added new option for addressparser: `flatten`. If true then ignores group names and returns a single list of all addresses + +## 6.1.1 2019-04-20 + +- Fixed regression bug with missing smtp `authMethod` property + +## 6.1.0 2019-04-06 + +- Added new message property `amp` for providing AMP4EMAIL content + +## 6.0.0 2019-03-25 + +- SMTPConnection: use removeListener instead of removeAllListeners (xr0master) [ddc4af15] + Using removeListener should fix memory leak with Node.js streams + +## 5.1.1 2019-01-09 + +- Added missing option argument for custom auth + +## 5.1.0 2019-01-09 + +- Official support for custom authentication methods and examples (examples/custom-auth-async.js and examples/custom-auth-cb.js) + +## 5.0.1 2019-01-09 + +- Fixed regression error to support Node versions lower than 6.11 +- Added expiremental custom authentication support + +## 5.0.0 2018-12-28 + +- Start using dns.resolve() instead of dns.lookup() for resolving SMTP hostnames. Might be breaking change on some environments so upgrade with care +- Show more logs for renewing OAuth2 tokens, previously it was not possible to see what actually failed + +## 4.7.0 2018-11-19 + +- Cleaned up List-\* header generation +- Fixed 'full' return option for DSN (klaronix) [23b93a3b] +- Support promises `for mailcomposer.build()` + +## 4.6.8 2018-08-15 + +- Use first IP address from DNS resolution when using a proxy (Limbozz) [d4ca847c] +- Return raw email from SES transport (gabegorelick) [3aa08967] + +## 4.6.7 2018-06-15 + +- Added option `skipEncoding` to JSONTransport + +## 4.6.6 2018-06-10 + +- Fixes mime encoded-word compatibility issue with invalid clients like Zimbra + +## 4.6.5 2018-05-23 + +- Fixed broken DKIM stream in Node.js v10 +- Updated error messages for SMTP responses to not include a newline + +## 4.6.4 2018-03-31 + +- Readded logo author link to README that was accidentally removed a while ago + +## 4.6.3 2018-03-13 + +- Removed unneeded dependency + +## 4.6.2 2018-03-06 + +- When redirecting URL calls then do not include original POST content + +## 4.6.1 2018-03-06 + +- Fixed Smtp connection freezing, when trying to send after close / quit (twawszczak) [73d3911c] + +## 4.6.0 2018-02-22 + +- Support socks module v2 in addition to v1 [e228bcb2] +- Fixed invalid promise return value when using createTestAccount [5524e627] +- Allow using local addresses [8f6fa35f] + +## 4.5.0 2018-02-21 + +- Added new message transport option `normalizeHeaderKey(key)=>normalizedKey` for custom header formatting + +## 4.4.2 2018-01-20 + +- Added sponsors section to README +- enclose encodeURIComponent in try..catch to handle invalid urls + +## 4.4.1 2017-12-08 + +- Better handling of unexpectedly dropping connections + +## 4.4.0 2017-11-10 + +- Changed default behavior for attachment option contentTransferEncoding. If it is unset then base64 encoding is used for the attachment. If it is set to false then previous default applies (base64 for most, 7bit for text) + +## 4.3.1 2017-10-25 + +- Fixed a confict with Electron.js where timers do not have unref method + +## 4.3.0 2017-10-23 + +- Added new mail object method `mail.normalize(cb)` that should make creating HTTP API based transports much easier + +## 4.2.0 2017-10-13 + +- Expose streamed messages size and timers in info response + +## v4.1.3 2017-10-06 + +- Allow generating preview links without calling createTestAccount first + +## v4.1.2 2017-10-03 + +- No actual changes. Needed to push updated README to npmjs + +## v4.1.1 2017-09-25 + +- Fixed JSONTransport attachment handling + +## v4.1.0 2017-08-28 + +- Added new methods `createTestAccount` and `getTestMessageUrl` to use autogenerated email accounts from https://Ethereal.email + +## v4.0.1 2017-04-13 + +- Fixed issue with LMTP and STARTTLS + +## v4.0.0 2017-04-06 + +- License changed from EUPLv1.1 to MIT + +## v3.1.8 2017-03-21 + +- Fixed invalid List-\* header generation + +## v3.1.7 2017-03-14 + +- Emit an error if STARTTLS ends with connection being closed + +## v3.1.6 2017-03-14 + +- Expose last server response for smtpConnection + +## v3.1.5 2017-03-08 + +- Fixed SES transport, added missing `response` value + +## v3.1.4 2017-02-26 + +- Fixed DKIM calculation for empty body +- Ensure linebreak after message content. This fixes DKIM signatures for non-multipart messages where input did not end with a newline + +## v3.1.3 2017-02-17 + +- Fixed missing `transport.verify()` methods for SES transport + +## v3.1.2 2017-02-17 + +- Added missing error handlers for Sendmail, SES and Stream transports. If a messages contained an invalid URL as attachment then these transports threw an uncatched error + +## v3.1.1 2017-02-13 + +- Fixed missing `transport.on('idle')` and `transport.isIdle()` methods for SES transports + +## v3.1.0 2017-02-13 + +- Added built-in transport for AWS SES. [Docs](http://localhost:1313/transports/ses/) +- Updated stream transport to allow building JSON strings. [Docs](http://localhost:1313/transports/stream/#json-transport) +- Added new method _mail.resolveAll_ that fetches all attachments and such to be able to more easily build API-based transports + +## v3.0.2 2017-02-04 + +- Fixed a bug with OAuth2 login where error callback was fired twice if getToken was not available. + +## v3.0.1 2017-02-03 + +- Fixed a bug where Nodemailer threw an exception if `disableFileAccess` option was used +- Added FLOSS [exception declaration](FLOSS_EXCEPTIONS.md) + +## v3.0.0 2017-01-31 + +- Initial version of Nodemailer 3 + +This update brings a lot of breaking changes: + +- License changed from MIT to **EUPL-1.1**. This was possible as the new version of Nodemailer is a major rewrite. The features I don't have ownership for, were removed or reimplemented. If there's still some snippets in the code that have vague ownership then notify about the conflicting code and I'll fix it. +- Requires **Node.js v6+** +- All **templating is gone**. It was too confusing to use and to be really universal a huge list of different renderers would be required. Nodemailer is about email, not about parsing different template syntaxes +- **No NTLM authentication**. It was too difficult to re-implement. If you still need it then it would be possible to introduce a pluggable SASL interface where you could load the NTLM module in your own code and pass it to Nodemailer. Currently this is not possible. +- **OAuth2 authentication** is built in and has a different [configuration](https://nodemailer.com/smtp/oauth2/). You can use both user (3LO) and service (2LO) accounts to generate access tokens from Nodemailer. Additionally there's a new feature to authenticate differently for every message – useful if your application sends on behalf of different users instead of a single sender. +- **Improved Calendaring**. Provide an ical file to Nodemailer to send out [calendar events](https://nodemailer.com/message/calendar-events/). + +And also some non-breaking changes: + +- All **dependencies were dropped**. There is exactly 0 dependencies needed to use Nodemailer. This brings the installation time of Nodemailer from NPM down to less than 2 seconds +- **Delivery status notifications** added to Nodemailer +- Improved and built-in **DKIM** signing of messages. Previously you needed an external module for this and it did quite a lousy job with larger messages +- **Stream transport** to return a RFC822 formatted message as a stream. Useful if you want to use Nodemailer as a preprocessor and not for actual delivery. +- **Sendmail** transport built-in, no need for external transport plugin + +See [Nodemailer.com](https://nodemailer.com/) for full documentation + +## 2.7.0 2016-12-08 + +- Bumped mailcomposer that generates encoded-words differently which might break some tests + +## 2.6.0 2016-09-05 + +- Added new options disableFileAccess and disableUrlAccess +- Fixed envelope handling where cc/bcc fields were ignored in the envelope object + +## 2.4.2 2016-05-25 + +- Removed shrinkwrap file. Seemed to cause more trouble than help + +## 2.4.1 2016-05-12 + +- Fixed outdated shrinkwrap file + +## 2.4.0 2016-05-11 + +- Bumped mailcomposer module to allow using `false` as attachment filename (suppresses filename usage) +- Added NTLM authentication support + +## 2.3.2 2016-04-11 + +- Bumped smtp transport modules to get newest smtp-connection that fixes SMTPUTF8 support for internationalized email addresses + +## 2.3.1 2016-04-08 + +- Bumped mailcomposer to have better support for message/822 attachments + +## 2.3.0 2016-03-03 + +- Fixed a bug with attachment filename that contains mixed unicode and dashes +- Added built-in support for proxies by providing a new SMTP option `proxy` that takes a proxy configuration url as its value +- Added option `transport` to dynamically load transport plugins +- Do not require globally installed grunt-cli + +## 2.2.1 2016-02-20 + +- Fixed a bug in SMTP requireTLS option that was broken + +## 2.2.0 2016-02-18 + +- Removed the need to use `clone` dependency +- Added new method `verify` to check SMTP configuration +- Direct transport uses STARTTLS by default, fallbacks to plaintext if STARTTLS fails +- Added new message option `list` for setting List-\* headers +- Add simple proxy support with `getSocket` method +- Added new message option `textEncoding`. If `textEncoding` is not set then detect best encoding automatically +- Added new message option `icalEvent` to embed iCalendar events. Example [here](examples/ical-event.js) +- Added new attachment option `raw` to use prepared MIME contents instead of generating a new one. This might be useful when you want to handcraft some parts of the message yourself, for example if you want to inject a PGP encrypted message as the contents of a MIME node +- Added new message option `raw` to use an existing MIME message instead of generating a new one + +## 2.1.0 2016-02-01 + +Republishing 2.1.0-rc.1 as stable. To recap, here's the notable changes between v2.0 and v2.1: + +- Implemented templating support. You can either use a simple built-in renderer or some external advanced renderer, eg. [node-email-templates](https://github.com/niftylettuce/node-email-templates). Templating [docs](http://nodemailer.com/2-0-0-beta/templating/). +- Updated smtp-pool to emit 'idle' events in order to handle message queue more effectively +- Updated custom header handling, works everywhere the same now, no differences between adding custom headers to the message or to an attachment + +## 2.1.0-rc.1 2016-01-25 + +Sneaked in some new features even though it is already rc + +- If a SMTP pool is closed while there are still messages in a queue, the message callbacks are invoked with an error +- In case of SMTP pool the transporter emits 'idle' when there is a free connection slot available +- Added method `isIdle()` that checks if a pool has still some free connection slots available + +## 2.1.0-rc.0 2016-01-20 + +- Bumped dependency versions + +## 2.1.0-beta.3 2016-01-20 + +- Added support for node-email-templates templating in addition to the built-in renderer + +## 2.1.0-beta.2 2016-01-20 + +- Implemented simple templating feature + +## 2.1.0-beta.1 2016-01-20 + +- Allow using prepared header values that are not folded or encoded by Nodemailer + +## 2.1.0-beta.0 2016-01-20 + +- Use the same header custom structure for message root, attachments and alternatives +- Ensure that Message-Id exists when accessing message +- Allow using array values for custom headers (inserts every value in its own row) + +## 2.0.0 2016-01-11 + +- Released rc.2 as stable + +## 2.0.0-rc.2 2016-01-04 + +- Locked dependencies + +## 2.0.0-beta.2 2016-01-04 + +- Updated documentation to reflect changes with SMTP handling +- Use beta versions for smtp/pool/direct transports +- Updated logging + +## 2.0.0-beta.1 2016-01-03 + +- Use bunyan compatible logger instead of the emit('log') style +- Outsourced some reusable methods to nodemailer-shared +- Support setting direct/smtp/pool with the default configuration + +## 2.0.0-beta.0 2015-12-31 + +- Stream errors are not silently swallowed +- Do not use format=flowed +- Use nodemailer-fetch to fetch URL streams +- jshint replaced by eslint + +## v1.11.0 2015-12-28 + +Allow connection url based SMTP configurations + +## v1.10.0 2015-11-13 + +Added `defaults` argument for `createTransport` to predefine commonn values (eg. `from` address) + +## v1.9.0 2015-11-09 + +Returns a Promise for `sendMail` if callback is not defined + +## v1.8.0 2015-10-08 + +Added priority option (high, normal, low) for setting Importance header + +## v1.7.0 2015-10-06 + +Replaced hyperquest with needle. Fixes issues with compressed data and redirects + +## v1.6.0 2015-10-05 + +Maintenance release. Bumped dependencies to get support for unicode filenames for QQ webmail and to support emoji in filenames + +## v1.5.0 2015-09-24 + +Use mailcomposer instead of built in solution to generate message sources. Bumped libmime gives better quoted-printable handling. + +## v1.4.0 2015-06-27 + +Added new message option `watchHtml` to specify Apple Watch specific HTML part of the message. See [this post](https://litmus.com/blog/how-to-send-hidden-version-email-apple-watch) for details + +## v1.3.4 2015-04-25 + +Maintenance release, bumped buildmail version to get fixed format=flowed handling + +## v1.3.3 2015-04-25 + +Maintenance release, bumped dependencies + +## v1.3.2 2015-03-09 + +Maintenance release, upgraded dependencies. Replaced simplesmtp based tests with smtp-server based ones. + +## v1.3.0 2014-09-12 + +Maintenance release, upgrades buildmail and libmime. Allows using functions as transform plugins and fixes issue with unicode filenames in Gmail. + +## v1.2.2 2014-09-05 + +Proper handling of data uris as attachments. Attachment `path` property can also be defined as a data uri, not just regular url or file path. + +## v1.2.1 2014-08-21 + +Bumped libmime and mailbuild versions to properly handle filenames with spaces (short ascii only filenames with spaces were left unquoted). + +## v1.2.0 2014-08-18 + +Allow using encoded strings as attachments. Added new property `encoding` which defines the encoding used for a `content` string. If encoding is set, the content value is converted to a Buffer value using the defined encoding before usage. Useful for including binary attachemnts in JSON formatted email objects. + +## v1.1.2 2014-08-18 + +Return deprecatin error for v0.x style configuration + +## v1.1.1 2014-07-30 + +Bumped nodemailer-direct-transport dependency. Updated version includes a bugfix for Stream nodes handling. Important only if use direct-transport with Streams (not file paths or urls) as attachment content. + +## v1.1.0 2014-07-29 + +Added new method `resolveContent()` to get the html/text/attachment content as a String or Buffer. + +## v1.0.4 2014-07-23 + +Bugfix release. HTML node was instered twice if the message consisted of a HTML content (but no text content) + at least one attachment with CID + at least one attachment without CID. In this case the HTML node was inserted both to the root level multipart/mixed section and to the multipart/related sub section + +## v1.0.3 2014-07-16 + +Fixed a bug where Nodemailer crashed if the message content type was multipart/related + +## v1.0.2 2014-07-16 + +Upgraded nodemailer-smtp-transport to 0.1.11\. The docs state that for SSL you should use 'secure' option but the underlying smtp-connection module used 'secureConnection' for this purpose. Fixed smpt-connection to match the docs. + +## v1.0.1 2014-07-15 + +Implemented missing #close method that is passed to the underlying transport object. Required by the smtp pool. + +## v1.0.0 2014-07-15 + +Total rewrite. See migration guide here: + +## v0.7.1 2014-07-09 + +- Upgraded aws-sdk to 2.0.5 + +## v0.7.0 2014-06-17 + +- Bumped version to v0.7.0 +- Fix AWS-SES usage [5b6bc144] +- Replace current SES with new SES using AWS-SDK (Elanorr) [c79d797a] +- Updated README.md about Node Email Templates (niftylettuce) [e52bef81] + +## v0.6.5 2014-05-15 + +- Bumped version to v0.6.5 +- Use tildes instead of carets for dependency listing [5296ce41] +- Allow clients to set a custom identityString (venables) [5373287d] +- bugfix (adding "-i" to sendmail command line for each new mail) by copying this.args (vrodic) [05a8a9a3] +- update copyright (gdi2290) [3a6cba3a] + +## v0.6.4 2014-05-13 + +- Bumped version to v0.6.4 +- added npmignore, bumped dependencies [21bddcd9] +- Add AOL to well-known services (msouce) [da7dd3b7] + +## v0.6.3 2014-04-16 + +- Bumped version to v0.6.3 +- Upgraded simplesmtp dependency [dd367f59] + +## v0.6.2 2014-04-09 + +- Bumped version to v0.6.2 +- Added error option to Stub transport [c423acad] +- Use SVG npm badge (t3chnoboy) [677117b7] +- add SendCloud to well known services (haio) [43c358e0] +- High-res build-passing and NPM module badges (sahat) [9fdc37cd] + +## v0.6.1 2014-01-26 + +- Bumped version to v0.6.1 +- Do not throw on multiple errors from sendmail command [c6e2cd12] +- Do not require callback for pickup, fixes #238 [93eb3214] +- Added AWSSecurityToken information to README, fixes #235 [58e921d1] +- Added Nodemailer logo [06b7d1a8] + +## v0.6.0 2013-12-30 + +- Bumped version to v0.6.0 +- Allow defining custom transport methods [ec5b48ce] +- Return messageId with responseObject for all built in transport methods [74445cec] +- Bumped dependency versions for mailcomposer and readable-stream [9a034c34] +- Changed pickup argument name to 'directory' [01c3ea53] +- Added support for IIS pickup directory with PICKUP transport (philipproplesch) [36940b59..360a2878] +- Applied common styles [9e93a409] +- Updated readme [c78075e7] + +## v0.5.15 2013-12-13 + +- bumped version to v0.5.15 +- Updated README, added global options info for setting uo transports [554bb0e5] +- Resolve public hostname, if resolveHostname property for a transport object is set to `true` [9023a6e1..4c66b819] + +## v0.5.14 2013-12-05 + +- bumped version to v0.5.14 +- Expose status for direct messages [f0312df6] +- Allow to skip the X-Mailer header if xMailer value is set to 'false' [f2c20a68] + +## v0.5.13 2013-12-03 + +- bumped version to v0.5.13 +- Use the name property from the transport object to use for the domain part of message-id values (1598eee9) + +## v0.5.12 2013-12-02 + +- bumped version to v0.5.12 +- Expose transport method and transport module version if available [a495106e] +- Added 'he' module instead of using custom html entity decoding [c197d102] +- Added xMailer property for transport configuration object to override X-Mailer value [e8733a61] +- Updated README, added description for 'mail' method [e1f5f3a6] + +## v0.5.11 2013-11-28 + +- bumped version to v0.5.11 +- Updated mailcomposer version. Replaces ent with he [6a45b790e] + +## v0.5.10 2013-11-26 + +- bumped version to v0.5.10 +- added shorthand function mail() for direct transport type [88129bd7] +- minor tweaks and typo fixes [f797409e..ceac0ca4] + +## v0.5.9 2013-11-25 + +- bumped version to v0.5.9 +- Update for 'direct' handling [77b84e2f] +- do not require callback to be provided for 'direct' type [ec51c79f] + +## v0.5.8 2013-11-22 + +- bumped version to v0.5.8 +- Added support for 'direct' transport [826f226d..0dbbcbbc] + +## v0.5.7 2013-11-18 + +- bumped version to v0.5.7 +- Replace \r\n by \n in Sendmail transport (rolftimmermans) [fed2089e..616ec90c] A lot of sendmail implementations choke on \r\n newlines and require \n This commit addresses this by transforming all \r\n sequences passed to the sendmail command with \n + +## v0.5.6 2013-11-15 + +- bumped version to v0.5.6 +- Upgraded mailcomposer dependency to 0.2.4 [e5ff9c40] +- Removed noCR option [e810d1b8] +- Update wellknown.js, added FastMail (k-j-kleist) [cf930f6d] + +## v0.5.5 2013-10-30 + +- bumped version to v0.5.5 +- Updated mailcomposer dependnecy version to 0.2.3 +- Remove legacy code - node v0.4 is not supported anymore anyway +- Use hostname (autodetected or from the options.name property) for Message-Id instead of "Nodemailer" (helps a bit when messages are identified as spam) +- Added maxMessages info to README + +## v0.5.4 2013-10-29 + +- bumped version to v0.5.4 +- added "use strict" statements +- Added DSN info to README +- add support for QQ enterprise email (coderhaoxin) +- Add a Bitdeli Badge to README +- DSN options Passthrought into simplesmtp. (irvinzz) + +## v0.5.3 2013-10-03 + +- bumped version v0.5.3 +- Using a stub transport to prevent sendmail from being called during a test. (jsdevel) +- closes #78: sendmail transport does not work correctly on Unix machines. (jsdevel) +- Updated PaaS Support list to include Modulus. (fiveisprime) +- Translate self closing break tags to newline (kosmasgiannis) +- fix typos (aeosynth) + +## v0.5.2 2013-07-25 + +- bumped version v0.5.2 +- Merge pull request #177 from MrSwitch/master Fixing Amazon SES, fatal error caused by bad connection diff --git a/node_modules/nodemailer/CLAUDE.md b/node_modules/nodemailer/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..c0f6d6cd63625538f16f732e2929455c5f0a6d3f --- /dev/null +++ b/node_modules/nodemailer/CLAUDE.md @@ -0,0 +1,56 @@ +# Nodemailer + +E-mail sending library for Node.js. Zero runtime dependencies. Entry point is `lib/nodemailer.js`, which exposes `createTransport(transporter, defaults)` and routes to one of the bundled transports based on the options object. + +## Layout + +- `lib/nodemailer.js` — public entry, transport dispatch (`createTransport`). +- `lib/mailer/` — `Mail` class: the user-facing transport wrapper that normalizes messages, runs the DKIM signer, and hands off to the underlying transport's `.send()`. +- `lib/mail-composer/` + `lib/mime-node/` — message → MIME tree → raw RFC822 stream. +- `lib/smtp-connection/` — low-level SMTP/LMTP/ESMTP client. Hot path; security-sensitive. Used by `smtp-transport` and `smtp-pool`. +- `lib/smtp-transport/` — single-shot SMTP transport. +- `lib/smtp-pool/` — pooled SMTP transport with rate limiting. +- `lib/sendmail-transport/`, `lib/ses-transport/`, `lib/stream-transport/`, `lib/json-transport/` — alternate transports. +- `lib/dkim/`, `lib/addressparser/`, `lib/mime-funcs/`, `lib/base64/`, `lib/qp/`, `lib/punycode/`, `lib/well-known/`, `lib/xoauth2/`, `lib/fetch/`, `lib/shared/` — supporting modules. +- `test/` — mirrors `lib/` structure. Most suites spin up real `smtp-server` instances on ephemeral ports; raw `net` servers are used when byte-exact reply control is needed (e.g. injecting non-ASCII or invalid UTF-8). + +Each transport must implement `name`, `version`, and `send(mail, callback)`. `Mail` discovers them via duck typing. + +## Engine target + +`engines.node = ">=6.0.0"`. The library is shipped as ES2017 script-mode CommonJS — no `import`, no top-level `await`, no optional chaining, no nullish coalescing, no class fields. ESLint enforces `ecmaVersion: 2017` and `sourceType: 'script'`. There is a Node 6 syntax-compat check (`npm run test:syntax`, runs `test/syntax-compat.js` inside `node:6-alpine`) that must keep passing — do not introduce syntax that breaks it. `'use strict';` directive at the top of every file. + +## Conventions + +- CommonJS only: `const x = require('...')`, `module.exports = ...`. +- Callback-first style throughout the public API. Many internals are still callback-based — match the style of the file you are editing rather than introducing promises mid-module. +- Prettier handles formatting; ESLint handles correctness. Run `npm run format` and `npm run lint` before sending changes. The lint config disables Prettier-overlapping rules. +- Snake_case is not used; camelCase for variables and methods, PascalCase for classes. +- Prefer small, surgical diffs. The codebase is mature and load-bearing — avoid drive-by refactors, comment churn, or "improvements" outside the scope of the change. +- Every change to security-sensitive code (anything in `lib/smtp-connection/`, address parsing, header generation, DKIM) needs tests that exercise the failure mode, not just the happy path. + +## Testing + +- `npm test` — full suite via `node --test` (~150s, 480+ tests, runs serially). +- `npm run test:coverage` — same suite under `c8`. +- `npm run test:syntax` — Node 6 syntax compatibility check in Docker. +- `npm run lint` / `npm run lint:fix`. +- `npm run format` / `npm run format:check`. + +Always run `npm test` and `npm run lint` before considering a change done. Tests are required to pass on every commit because release-please cuts releases directly from `master`. + +## Releases + +Releases, version numbers, the `version` field in `package.json`, git tags, `CHANGELOG.md` entries, and npm publication are all managed automatically by the release-please GitHub Action (`.github/workflows/release.yaml`, configured by `.release-please-config.json`). **Never edit any of these manually and never propose manual edits to them.** + +Release-please derives the next version and changelog from Conventional Commit messages on `master`, opens a release PR (`chore: release X.Y.Z [skip-ci]`), and publishes to npm with provenance when that PR is merged. The only thing that should land on `master` between releases is normal commits with Conventional Commit prefixes — release-please takes care of the rest. + +Conventional Commit prefixes used in this repo: `fix:`, `feat:`, `chore:`, `docs:`, `refactor:`, `test:`. Use `fix:` for anything users would benefit from seeing in the changelog, including security fixes (reference the GHSA in the body). + +## Security + +This is a widely-deployed library — security-sensitive changes get extra scrutiny: + +- SMTP command injection: any user-controllable value that flows into a written SMTP command (envelope addresses, sizes, the `name`/EHLO option, headers) must be CRLF-stripped or rejected at the boundary. Sanitize at the assignment, not at every call site. +- Server reply parsing in `lib/smtp-connection/index.js` uses a `'binary'` byte-container intermediate to reassemble multi-byte UTF-8 across socket chunks; the actual decode happens at line boundaries via `decodeServerResponse`. Don't change the chunk-buffering encoding without understanding why. +- Reference the GHSA ID in commit messages for advisories. diff --git a/node_modules/nodemailer/CODE_OF_CONDUCT.md b/node_modules/nodemailer/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..176705796260d1e82a0f0cbd1c865c2337fc3502 --- /dev/null +++ b/node_modules/nodemailer/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or + advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic + address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at info@nodemailer.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/node_modules/nodemailer/LICENSE b/node_modules/nodemailer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..fdfc9676bf9f4363b1292847d61f94a17a47618e --- /dev/null +++ b/node_modules/nodemailer/LICENSE @@ -0,0 +1,16 @@ +Copyright (c) 2011-2023 Andris Reinman + +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 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. diff --git a/node_modules/nodemailer/README.md b/node_modules/nodemailer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..519ec15f098622edcab7568bb3fe2fc4aa1b91af --- /dev/null +++ b/node_modules/nodemailer/README.md @@ -0,0 +1,86 @@ +# Nodemailer + +[![Nodemailer](https://raw.githubusercontent.com/nodemailer/nodemailer/master/assets/nm_logo_200x136.png)](https://nodemailer.com/about/) + +Send emails from Node.js – easy as cake! 🍰✉️ + +[![NPM](https://nodei.co/npm/nodemailer.png?downloads=true&downloadRank=true&stars=true)](https://nodemailer.com/about/) + +See [nodemailer.com](https://nodemailer.com/) for documentation and terms. + +> [!TIP] +> Check out **[EmailEngine](https://emailengine.app/?utm_source=github-nodemailer&utm_campaign=nodemailer&utm_medium=readme-link)** – a self-hosted email gateway that allows making **REST requests against IMAP and SMTP servers**. EmailEngine also sends webhooks whenever something changes on the registered accounts.\ +> \ +> Using the email accounts registered with EmailEngine, you can receive and [send emails](https://emailengine.app/sending-emails?utm_source=github-nodemailer&utm_campaign=nodemailer&utm_medium=readme-link). EmailEngine supports OAuth2, delayed sends, opens and clicks tracking, bounce detection, etc. All on top of regular email accounts without an external MTA service. + +## Having an issue? + +#### First review the docs + +Documentation for Nodemailer can be found at [nodemailer.com](https://nodemailer.com/about/). + +#### Nodemailer throws a SyntaxError for "..." + +You are using an older Node.js version than v6.0. Upgrade Node.js to get support for the spread operator. Nodemailer supports all Node.js versions starting from Node.js@v6.0.0. + +#### I'm having issues with Gmail + +Gmail either works well, or it does not work at all. It is probably easier to switch to an alternative service instead of fixing issues with Gmail. If Gmail does not work for you, then don't use it. Read more about it [here](https://nodemailer.com/usage/using-gmail/). + +#### I get ETIMEDOUT errors + +Check your firewall settings. Timeout usually occurs when you try to open a connection to a firewalled port either on the server or on your machine. Some ISPs also block email ports to prevent spamming. + +#### Nodemailer works on one machine but not in another + +It's either a firewall issue, or your SMTP server blocks authentication attempts from some servers. + +#### I get TLS errors + +- If you are running the code on your machine, check your antivirus settings. Antiviruses often mess around with email ports usage. Node.js might not recognize the MITM cert your antivirus is using. +- Latest Node versions allow only TLS versions 1.2 and higher. Some servers might still use TLS 1.1 or lower. Check Node.js docs on how to get correct TLS support for your app. You can change this with [tls.minVersion](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#tls_tls_createsecurecontext_options) option +- You might have the wrong value for the `secure` option. This should be set to `true` only for port 465. For every other port, it should be `false`. Setting it to `false` does not mean that Nodemailer would not use TLS. Nodemailer would still try to upgrade the connection to use TLS if the server supports it. +- Older Node versions do not fully support the certificate chain of the newest Let's Encrypt certificates. Either set [tls.rejectUnauthorized](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#tlsconnectoptions-callback) to `false` to skip chain verification or upgrade your Node version + +```js +let configOptions = { + host: 'smtp.example.com', + port: 587, + tls: { + rejectUnauthorized: true, + minVersion: 'TLSv1.2' + } +}; +``` + +#### I have issues with DNS / hosts file + +Node.js uses [c-ares](https://nodejs.org/en/docs/meta/topics/dependencies/#c-ares) to resolve domain names, not the DNS library provided by the system, so if you have some custom DNS routing set up, it might be ignored. Nodemailer runs [dns.resolve4()](https://nodejs.org/dist/latest-v16.x/docs/api/dns.html#dnsresolve4hostname-options-callback) and [dns.resolve6()](https://nodejs.org/dist/latest-v16.x/docs/api/dns.html#dnsresolve6hostname-options-callback) to resolve hostname into an IP address. If both calls fail, then Nodemailer will fall back to [dns.lookup()](https://nodejs.org/dist/latest-v16.x/docs/api/dns.html#dnslookuphostname-options-callback). If this does not work for you, you can hard code the IP address into the configuration like shown below. In that case, Nodemailer would not perform any DNS lookups. + +```js +let configOptions = { + host: '1.2.3.4', + port: 465, + secure: true, + tls: { + // must provide server name, otherwise TLS certificate check will fail + servername: 'example.com' + } +}; +``` + +#### I have an issue with TypeScript types + +Nodemailer has official support for Node.js only. For anything related to TypeScript, you need to directly contact the authors of the [type definitions](https://www.npmjs.com/package/@types/nodemailer). + +#### I have a different problem + +If you are having issues with Nodemailer, then the best way to find help would be [Stack Overflow](https://stackoverflow.com/search?q=nodemailer) or revisit the [docs](https://nodemailer.com/about/). + +### License + +Nodemailer is licensed under the **MIT No Attribution license** + +--- + +The Nodemailer logo was designed by [Sven Kristjansen](https://www.behance.net/kristjansen). diff --git a/node_modules/nodemailer/SECURITY.md b/node_modules/nodemailer/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..2243c06fa7818a6fc37fbc05bb718cd1d214895d --- /dev/null +++ b/node_modules/nodemailer/SECURITY.md @@ -0,0 +1,65 @@ +# Security Policy + +Nodemailer is a widely deployed, zero-dependency e-mail library. We take security +reports seriously and aim to respond quickly. + +## Supported Versions + +Security fixes are released only against the latest major version. We do not +backport patches to older majors — upgrading to the current release line is the +supported way to receive security updates. + +| Version | Supported | +| ------- | ------------------ | +| 8.x | :white_check_mark: | +| < 8.0 | :x: | + +If you are on an older major, please upgrade. See the migration notes at + before updating. + +## Reporting a Vulnerability + +**Please do not report security vulnerabilities through public GitHub issues, +pull requests, or discussions.** + +Report privately through one of the following channels: + +1. **GitHub Security Advisories (preferred).** Open a private report at + . This keeps + the discussion private until a fix is published and lets us credit you. +2. **Email.** Send details to **andris@reinman.eu** (the contact listed in + [`SECURITY.txt`](SECURITY.txt)). Encrypt sensitive details if possible. + +When reporting, please include as much of the following as you can: + +- The affected version(s) and environment (Node.js version, OS). +- The component involved (e.g. SMTP connection, address parsing, MIME/header + generation, DKIM). +- A clear description of the issue and its impact (e.g. header/SMTP command + injection, information disclosure, DoS). +- A minimal proof of concept or reproduction steps. +- Any suggested remediation, if you have one. + +Nodemailer is maintained by a single person, so there is no guaranteed response +time — sometimes reports are handled within hours, sometimes they take longer. +Accepted issues are fixed in a new release and coordinated through a GitHub +Security Advisory, and reporters who wish to be named are credited. + +## CVEs + +We track and disclose vulnerabilities through GitHub Security Advisories. We do +not request or manage CVE identifiers ourselves. If you need a CVE assigned for a +reported issue, please request one yourself — for example, through GitHub's own +CVE request flow on the published advisory, or another CNA. + +## Scope + +In scope: the `nodemailer` package source in this repository — message and MIME +generation, SMTP/LMTP client behaviour, address parsing, header handling, DKIM +signing, and the bundled transports. + +Out of scope: vulnerabilities in your own application code, misconfiguration of +your mail server or credentials, social-engineering reports, and issues in +third-party services Nodemailer connects to. + +Thank you for helping keep Nodemailer and its users safe. diff --git a/node_modules/nodemailer/SECURITY.txt b/node_modules/nodemailer/SECURITY.txt new file mode 100644 index 0000000000000000000000000000000000000000..27a54d3423b4b58a7016b6bb587359f1866da871 --- /dev/null +++ b/node_modules/nodemailer/SECURITY.txt @@ -0,0 +1,22 @@ +-----BEGIN PGP SIGNED MESSAGE----- +Hash: SHA256 + +Contact: mailto:andris@reinman.eu +Encryption: https://keys.openpgp.org/vks/v1/by-fingerprint/5D952A46E1D8C931F6364E01DC6C83F4D584D364 +Preferred-Languages: en, et +-----BEGIN PGP SIGNATURE----- + +iQIzBAEBCAAdFiEEXZUqRuHYyTH2Nk4B3GyD9NWE02QFAmFDnUgACgkQ3GyD9NWE +02RqUA/+MM3afmRYq874C7wp+uN6dTMCvUX5g5zqBZ2yKpFr46L+PYvM7o8TMm5h +hmLT2I1zZmi+xezOL3zHFizaw0tKkZIz9cWl3Jrgs0FLp0zOsSz1xucp9Q2tYM/Q +vbiP6ys0gbim4tkDGRmZOEiO23s0BuRnmHt7vZg210O+D105Yd8/Ohzbj6PSLBO5 +W1tA7Xw5t0FQ14NNH5+MKyDIKoCX12n0FmrC6qLTXeojf291UgKhCUPda3LIGTmx +mTXz0y68149Mw+JikRCYP8HfGRY9eA4XZrYXF7Bl2T9OJpKD3JAH+69P3xBw19Gn +Csaw3twu8P1bxoVGjY4KRrBOp68W8TwZYjWVWbqY6oV8hb/JfrMxa+kaSxRuloFs +oL6+phrDSPTWdOj2LlEDBJbPOMeDFzIlsBBcJ/JHCEHTvlHl7LoWr3YuWce9PUwl +4r3JUovvaeuJxLgC0vu3WCB3Jeocsl3SreqNkrVc1IjvkSomn3YGm5nCNAd/2F0V +exCGRk/8wbkSjAY38GwQ8K/VuFsefWN3L9sVwIMAMu88KFCAN+GzVFiwvyIXehF5 +eogP9mIXzdQ5YReQjUjApOzGz54XnDyv9RJ3sdvMHosLP+IOg+0q5t9agWv6aqSR +2HzCpiQnH/gmM5NS0AU4Koq/L7IBeLu1B8+61/+BiHgZJJmPdgU= +=BUZr +-----END PGP SIGNATURE----- diff --git a/node_modules/nodemailer/eslint.config.js b/node_modules/nodemailer/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..fde05949b0870df0aa4670ab3ef83ff1dde1977a --- /dev/null +++ b/node_modules/nodemailer/eslint.config.js @@ -0,0 +1,88 @@ +'use strict'; + +const globals = require('globals'); + +module.exports = [ + { + ignores: ['node_modules/**', 'coverage/**', 'dist/**', 'build/**', '.nyc_output/**'] + }, + { + files: ['**/*.js'], + languageOptions: { + ecmaVersion: 2017, + sourceType: 'script', + globals: Object.assign({}, globals.node, globals.es2017, { + it: true, + describe: true, + beforeEach: true, + afterEach: true + }) + }, + rules: { + // Error detection + 'for-direction': 'error', + 'no-await-in-loop': 'error', + 'no-div-regex': 'error', + eqeqeq: 'error', + 'dot-notation': 'error', + curly: 'error', + 'no-fallthrough': 'error', + 'no-unused-expressions': [ + 'error', + { + allowShortCircuit: true + } + ], + 'no-unused-vars': [ + 'error', + { + varsIgnorePattern: '^_', + argsIgnorePattern: '^_', + caughtErrorsIgnorePattern: '^_' + } + ], + 'handle-callback-err': 'error', + 'no-new': 'error', + 'new-cap': 'error', + 'no-eval': 'error', + 'no-invalid-this': 'error', + radix: ['error', 'always'], + 'no-use-before-define': ['error', 'nofunc'], + 'callback-return': ['error', ['callback', 'cb', 'done']], + 'no-regex-spaces': 'error', + 'no-empty': 'error', + 'no-duplicate-case': 'error', + 'no-empty-character-class': 'error', + 'no-redeclare': 'off', // Disabled per project preference + 'block-scoped-var': 'error', + 'no-sequences': 'error', + 'no-throw-literal': 'error', + 'no-useless-call': 'error', + 'no-useless-concat': 'error', + 'no-void': 'error', + yoda: 'error', + 'no-undef': 'error', + 'global-require': 'error', + 'no-var': 'error', + 'no-bitwise': 'error', + 'no-lonely-if': 'error', + 'no-mixed-spaces-and-tabs': 'error', + 'arrow-body-style': ['error', 'as-needed'], + 'arrow-parens': ['error', 'as-needed'], + 'prefer-arrow-callback': 'error', + 'object-shorthand': 'error', + 'prefer-spread': 'error', + 'no-prototype-builtins': 'off', // Disabled per project preference + strict: ['error', 'global'], + + // Disable all formatting rules (handled by Prettier) + indent: 'off', + quotes: 'off', + 'linebreak-style': 'off', + semi: 'off', + 'quote-props': 'off', + 'comma-dangle': 'off', + 'comma-style': 'off' + } + } +]; diff --git a/node_modules/nodemailer/lib/addressparser/index.js b/node_modules/nodemailer/lib/addressparser/index.js new file mode 100644 index 0000000000000000000000000000000000000000..08b3c3651ce45777400741865426a1b298b46c98 --- /dev/null +++ b/node_modules/nodemailer/lib/addressparser/index.js @@ -0,0 +1,382 @@ +'use strict'; + +/** + * Converts tokens for a single address into an address object + * + * @param {Array} tokens Tokens object + * @param {Number} depth Current recursion depth for nested group protection + * @return {Object} Address object + */ +function _handleAddress(tokens, depth) { + let isGroup = false; + let state = 'text'; + const addresses = []; + const data = { + address: [], + comment: [], + group: [], + text: [], + textWasQuoted: [] + }; + let insideQuotes = false; + + // Filter out , (comments) and regular text + for (let i = 0, len = tokens.length; i < len; i++) { + const token = tokens[i]; + const prevToken = i ? tokens[i - 1] : null; + if (token.type === 'operator') { + switch (token.value) { + case '<': + state = 'address'; + insideQuotes = false; + break; + case '(': + state = 'comment'; + insideQuotes = false; + break; + case ':': + state = 'group'; + isGroup = true; + insideQuotes = false; + break; + case '"': + insideQuotes = !insideQuotes; + state = 'text'; + break; + default: + state = 'text'; + insideQuotes = false; + break; + } + } else if (token.value) { + if (state === 'address') { + // Handle unquoted name that includes a "<". + // Apple Mail truncates everything between an unexpected < and an address. + token.value = token.value.replace(/^[^<]*<\s*/, ''); + } + + if (prevToken && prevToken.noBreak && data[state].length) { + data[state][data[state].length - 1] += token.value; + if (state === 'text' && insideQuotes) { + data.textWasQuoted[data.textWasQuoted.length - 1] = true; + } + } else { + data[state].push(token.value); + if (state === 'text') { + data.textWasQuoted.push(insideQuotes); + } + } + } + } + + // If there is no text but a comment, replace the two + if (!data.text.length && data.comment.length) { + data.text = data.comment; + data.comment = []; + } + + if (isGroup) { + // http://tools.ietf.org/html/rfc2822#appendix-A.1.3 + data.text = data.text.join(' '); + + // Parse group members, but flatten any nested groups (RFC 5322 doesn't allow nesting) + let groupMembers = []; + if (data.group.length) { + const parsedGroup = addressparser(data.group.join(','), { _depth: depth + 1 }); + parsedGroup.forEach(member => { + if (member.group) { + groupMembers = groupMembers.concat(member.group); + } else { + groupMembers.push(member); + } + }); + } + + addresses.push({ + name: data.text || '', + group: groupMembers + }); + } else { + // If no address was found, try to detect one from regular text + if (!data.address.length && data.text.length) { + for (let i = data.text.length - 1; i >= 0; i--) { + // Security: Do not extract email addresses from quoted strings. + // RFC 5321 allows @ inside quoted local-parts like "user@domain"@example.com. + // Extracting emails from quoted text leads to misrouting vulnerabilities. + if (!data.textWasQuoted[i] && /^[^@\s]+@[^@\s]+$/.test(data.text[i])) { + data.address = data.text.splice(i, 1); + data.textWasQuoted.splice(i, 1); + break; + } + } + + // Try a looser regex match if strict match found nothing + if (!data.address.length) { + let extracted = false; + for (let i = data.text.length - 1; i >= 0; i--) { + // Security: Do not extract email addresses from quoted strings + if (!data.textWasQuoted[i]) { + data.text[i] = data.text[i] + .replace(/\s*\b[^@\s]+@[^\s]+\b\s*/, match => { + if (!extracted) { + data.address = [match.trim()]; + extracted = true; + return ' '; + } + return match; + }) + .trim(); + if (extracted) { + break; + } + } + } + } + } + + // If there's still no text but a comment exists, replace the two + if (!data.text.length && data.comment.length) { + data.text = data.comment; + data.comment = []; + } + + // Keep only the first address occurrence, push others to regular text + if (data.address.length > 1) { + data.text = data.text.concat(data.address.splice(1)); + } + + // Join values with spaces + data.text = data.text.join(' '); + data.address = data.address.join(' '); + + const address = { + address: data.address || data.text || '', + name: data.text || data.address || '' + }; + + if (address.address === address.name) { + if (/@/.test(address.address || '')) { + address.name = ''; + } else { + address.address = ''; + } + } + + addresses.push(address); + } + + return addresses; +} + +/** + * Creates a Tokenizer object for tokenizing address field strings + * + * @constructor + * @param {String} str Address field string + */ +class Tokenizer { + constructor(str) { + this.str = (str || '').toString(); + this.operatorCurrent = ''; + this.operatorExpecting = ''; + this.node = null; + this.escaped = false; + + this.list = []; + /** + * Operator tokens and which tokens are expected to end the sequence + */ + this.operators = { + '"': '"', + '(': ')', + '<': '>', + ',': '', + ':': ';', + // Semicolons are not a legal delimiter per the RFC2822 grammar other + // than for terminating a group, but they are also not valid for any + // other use in this context. Given that some mail clients have + // historically allowed the semicolon as a delimiter equivalent to the + // comma in their UI, it makes sense to treat them the same as a comma + // when used outside of a group. + ';': '' + }; + } + + /** + * Tokenizes the original input string + * + * @return {Array} An array of operator|text tokens + */ + tokenize() { + const list = []; + + for (let i = 0, len = this.str.length; i < len; i++) { + const chr = this.str.charAt(i); + const nextChr = i < len - 1 ? this.str.charAt(i + 1) : null; + this.checkChar(chr, nextChr); + } + + this.list.forEach(node => { + node.value = (node.value || '').toString().trim(); + if (node.value) { + list.push(node); + } + }); + + return list; + } + + /** + * Checks if a character is an operator or text and acts accordingly + * + * @param {String} chr Character from the address field + */ + checkChar(chr, nextChr) { + if (this.escaped) { + // ignore next condition blocks + } else if (chr === this.operatorExpecting) { + this.node = { + type: 'operator', + value: chr + }; + + if (nextChr && ![' ', '\t', '\r', '\n', ',', ';'].includes(nextChr)) { + this.node.noBreak = true; + } + + this.list.push(this.node); + this.node = null; + this.operatorExpecting = ''; + this.escaped = false; + + return; + } else if (!this.operatorExpecting && chr in this.operators) { + this.node = { + type: 'operator', + value: chr + }; + this.list.push(this.node); + this.node = null; + this.operatorExpecting = this.operators[chr]; + this.escaped = false; + return; + } else if (['"', "'"].includes(this.operatorExpecting) && chr === '\\') { + this.escaped = true; + return; + } + + if (!this.node) { + this.node = { + type: 'text', + value: '' + }; + this.list.push(this.node); + } + + if (chr === '\n') { + // Convert newlines to spaces. Carriage return is ignored as \r and \n usually + // go together anyway and there already is a WS for \n. Lone \r means something is fishy. + chr = ' '; + } + + if (chr.charCodeAt(0) >= 0x21 || [' ', '\t'].includes(chr)) { + // skip command bytes + this.node.value += chr; + } + + this.escaped = false; + } +} + +/** + * Maximum recursion depth for parsing nested groups. + * RFC 5322 doesn't allow nested groups, so this is a safeguard against + * malicious input that could cause stack overflow. + */ +const MAX_NESTED_GROUP_DEPTH = 50; + +/** + * Parses structured e-mail addresses from an address field + * + * Example: + * + * 'Name ' + * + * will be converted to + * + * [{name: 'Name', address: 'address@domain'}] + * + * @param {String} str Address field + * @param {Object} options Optional options object + * @param {Number} options._depth Internal recursion depth counter (do not set manually) + * @return {Array} An array of address objects + */ +function addressparser(str, options) { + options = options || {}; + const depth = options._depth || 0; + + // Prevent stack overflow from deeply nested groups (DoS protection) + if (depth > MAX_NESTED_GROUP_DEPTH) { + return []; + } + + const tokenizer = new Tokenizer(str); + const tokens = tokenizer.tokenize(); + + const addresses = []; + let address = []; + let parsedAddresses = []; + + tokens.forEach(token => { + if (token.type === 'operator' && (token.value === ',' || token.value === ';')) { + if (address.length) { + addresses.push(address); + } + address = []; + } else { + address.push(token); + } + }); + + if (address.length) { + addresses.push(address); + } + + addresses.forEach(addr => { + const handled = _handleAddress(addr, depth); + if (handled.length) { + parsedAddresses = parsedAddresses.concat(handled); + } + }); + + // Merge fragments produced when unquoted display names contain commas. + // "Joe Foo, PhD " is split on the comma into + // [{name:"Joe Foo", address:""}, {name:"PhD", address:"joe@example.com"}]. + // Recombine: a name-only entry followed by an entry with both name and address. + for (let i = parsedAddresses.length - 2; i >= 0; i--) { + const current = parsedAddresses[i]; + const next = parsedAddresses[i + 1]; + if (current.address === '' && current.name && !current.group && next.address && next.name) { + next.name = current.name + ', ' + next.name; + parsedAddresses.splice(i, 1); + } + } + + if (options.flatten) { + const flatAddresses = []; + const walkAddressList = list => { + list.forEach(entry => { + if (entry.group) { + return walkAddressList(entry.group); + } + flatAddresses.push(entry); + }); + }; + walkAddressList(parsedAddresses); + return flatAddresses; + } + + return parsedAddresses; +} + +module.exports = addressparser; diff --git a/node_modules/nodemailer/lib/base64/index.js b/node_modules/nodemailer/lib/base64/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7baf7a5cda35898f3b7b72540370df774b8d04f3 --- /dev/null +++ b/node_modules/nodemailer/lib/base64/index.js @@ -0,0 +1,138 @@ +'use strict'; + +const { Transform } = require('stream'); + +/** + * Encodes a Buffer into a base64 encoded string + * + * @param {Buffer} buffer Buffer to convert + * @returns {String} base64 encoded string + */ +function encode(buffer) { + if (typeof buffer === 'string') { + buffer = Buffer.from(buffer, 'utf-8'); + } + + return buffer.toString('base64'); +} + +/** + * Adds soft line breaks to a base64 string + * + * @param {String} str base64 encoded string that might need line wrapping + * @param {Number} [lineLength=76] Maximum allowed length for a line + * @returns {String} Soft-wrapped base64 encoded string + */ +function wrap(str, lineLength) { + str = (str || '').toString(); + lineLength = lineLength || 76; + + if (str.length <= lineLength) { + return str; + } + + const result = []; + let pos = 0; + const chunkLength = lineLength * 1024; + const wrapRegex = new RegExp('.{' + lineLength + '}', 'g'); + while (pos < str.length) { + const wrappedLines = str.substr(pos, chunkLength).replace(wrapRegex, '$&\r\n').trim(); + result.push(wrappedLines); + pos += chunkLength; + } + + return result.join('\r\n').trim(); +} + +/** + * Creates a transform stream for encoding data to base64 encoding + * + * @constructor + * @param {Object} options Stream options + * @param {Number} [options.lineLength=76] Maximum length for lines, set to false to disable wrapping + */ +class Encoder extends Transform { + constructor(options) { + super(); + this.options = options || {}; + + if (this.options.lineLength !== false) { + this.options.lineLength = this.options.lineLength || 76; + } + + this._curLine = ''; + this._remainingBytes = false; + + this.inputBytes = 0; + this.outputBytes = 0; + } + + _transform(chunk, encoding, done) { + if (encoding !== 'buffer') { + chunk = Buffer.from(chunk, encoding); + } + + if (!chunk || !chunk.length) { + return setImmediate(done); + } + + this.inputBytes += chunk.length; + + if (this._remainingBytes && this._remainingBytes.length) { + chunk = Buffer.concat([this._remainingBytes, chunk], this._remainingBytes.length + chunk.length); + this._remainingBytes = false; + } + + if (chunk.length % 3) { + this._remainingBytes = chunk.slice(chunk.length - (chunk.length % 3)); + chunk = chunk.slice(0, chunk.length - (chunk.length % 3)); + } else { + this._remainingBytes = false; + } + + let b64 = this._curLine + encode(chunk); + + if (this.options.lineLength) { + b64 = wrap(b64, this.options.lineLength); + + // remove last line as it is still most probably incomplete + const lastLF = b64.lastIndexOf('\n'); + if (lastLF < 0) { + this._curLine = b64; + b64 = ''; + } else if (lastLF === b64.length - 1) { + this._curLine = ''; + } else { + this._curLine = b64.substring(lastLF + 1); + b64 = b64.substring(0, lastLF + 1); + } + } + + if (b64) { + this.outputBytes += b64.length; + this.push(Buffer.from(b64, 'ascii')); + } + + setImmediate(done); + } + + _flush(done) { + if (this._remainingBytes && this._remainingBytes.length) { + this._curLine += encode(this._remainingBytes); + } + + if (this._curLine) { + this._curLine = wrap(this._curLine, this.options.lineLength); + this.outputBytes += this._curLine.length; + this.push(Buffer.from(this._curLine, 'ascii')); + this._curLine = ''; + } + done(); + } +} + +module.exports = { + encode, + wrap, + Encoder +}; diff --git a/node_modules/nodemailer/lib/dkim/index.js b/node_modules/nodemailer/lib/dkim/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3f5c0d8f0c8dc2b9bbeb1047e37e9788f8ce6fd9 --- /dev/null +++ b/node_modules/nodemailer/lib/dkim/index.js @@ -0,0 +1,245 @@ +'use strict'; + +// FIXME: +// replace this Transform mess with a method that pipes input argument to output argument + +const MessageParser = require('./message-parser'); +const RelaxedBody = require('./relaxed-body'); +const sign = require('./sign'); +const { PassThrough } = require('stream'); +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +const DKIM_ALGO = 'sha256'; +const MAX_MESSAGE_SIZE = 2 * 1024 * 1024; // buffer messages larger than this to disk + +/* +// Usage: + +let dkim = new DKIM({ + domainName: 'example.com', + keySelector: 'key-selector', + privateKey, + cacheDir: '/tmp' +}); +dkim.sign(input).pipe(process.stdout); + +// Where inputStream is a rfc822 message (either a stream, string or Buffer) +// and outputStream is a DKIM signed rfc822 message +*/ + +class DKIMSigner { + constructor(options, keys, input, output) { + this.options = options || {}; + this.keys = keys; + + this.cacheTreshold = Number(this.options.cacheTreshold) || MAX_MESSAGE_SIZE; + this.hashAlgo = this.options.hashAlgo || DKIM_ALGO; + + this.cacheDir = this.options.cacheDir || false; + + this.chunks = []; + this.chunklen = 0; + this.readPos = 0; + this.cachePath = this.cacheDir + ? path.join(this.cacheDir, 'message.' + Date.now() + '-' + crypto.randomBytes(14).toString('hex')) + : false; + this.cache = false; + + this.headers = false; + this.bodyHash = false; + this.parser = false; + this.relaxedBody = false; + + this.input = input; + this.output = output; + this.output.usingCache = false; + + this.hasErrored = false; + + this.input.on('error', err => { + this.hasErrored = true; + this.cleanup(); + output.emit('error', err); + }); + } + + cleanup() { + if (!this.cache || !this.cachePath) { + return; + } + fs.unlink(this.cachePath, () => false); + } + + createReadCache() { + // pipe remainings to cache file + this.cache = fs.createReadStream(this.cachePath); + this.cache.once('error', err => { + this.cleanup(); + this.output.emit('error', err); + }); + this.cache.once('close', () => { + this.cleanup(); + }); + this.cache.pipe(this.output); + } + + sendNextChunk() { + if (this.hasErrored) { + return; + } + + if (this.readPos >= this.chunks.length) { + if (!this.cache) { + return this.output.end(); + } + return this.createReadCache(); + } + const chunk = this.chunks[this.readPos++]; + if (this.output.write(chunk) === false) { + return this.output.once('drain', () => { + this.sendNextChunk(); + }); + } + setImmediate(() => this.sendNextChunk()); + } + + sendSignedOutput() { + let keyPos = 0; + const signNextKey = () => { + if (keyPos >= this.keys.length) { + this.output.write(this.parser.rawHeaders); + return setImmediate(() => this.sendNextChunk()); + } + const key = this.keys[keyPos++]; + const dkimField = sign(this.headers, this.hashAlgo, this.bodyHash, { + domainName: key.domainName, + keySelector: key.keySelector, + privateKey: key.privateKey, + headerFieldNames: this.options.headerFieldNames, + skipFields: this.options.skipFields + }); + if (dkimField) { + this.output.write(Buffer.from(dkimField + '\r\n')); + } + return setImmediate(signNextKey); + }; + + if (this.bodyHash && this.headers) { + return signNextKey(); + } + + this.output.write(this.parser.rawHeaders); + this.sendNextChunk(); + } + + createWriteCache() { + this.output.usingCache = true; + // pipe remainings to cache file + this.cache = fs.createWriteStream(this.cachePath); + this.cache.once('error', err => { + this.cleanup(); + // drain input + this.relaxedBody.unpipe(this.cache); + this.relaxedBody.on('readable', () => { + while (this.relaxedBody.read() !== null) { + // do nothing + } + }); + this.hasErrored = true; + // emit error + this.output.emit('error', err); + }); + this.cache.once('close', () => { + this.sendSignedOutput(); + }); + this.relaxedBody.removeAllListeners('readable'); + this.relaxedBody.pipe(this.cache); + } + + signStream() { + this.parser = new MessageParser(); + this.relaxedBody = new RelaxedBody({ + hashAlgo: this.hashAlgo + }); + + this.parser.on('headers', value => { + this.headers = value; + }); + + this.relaxedBody.on('hash', value => { + this.bodyHash = value; + }); + + this.relaxedBody.on('readable', () => { + let chunk; + if (this.cache) { + return; + } + while ((chunk = this.relaxedBody.read()) !== null) { + this.chunks.push(chunk); + this.chunklen += chunk.length; + if (this.chunklen >= this.cacheTreshold && this.cachePath) { + return this.createWriteCache(); + } + } + }); + + this.relaxedBody.on('end', () => { + if (this.cache) { + return; + } + this.sendSignedOutput(); + }); + + this.parser.pipe(this.relaxedBody); + setImmediate(() => this.input.pipe(this.parser)); + } +} + +class DKIM { + constructor(options) { + this.options = options || {}; + this.keys = [].concat( + this.options.keys || { + domainName: options.domainName, + keySelector: options.keySelector, + privateKey: options.privateKey + } + ); + } + + sign(input, extraOptions) { + const output = new PassThrough(); + let inputStream = input; + let writeValue = false; + + if (Buffer.isBuffer(input)) { + writeValue = input; + inputStream = new PassThrough(); + } else if (typeof input === 'string') { + writeValue = Buffer.from(input); + inputStream = new PassThrough(); + } + + let options = this.options; + if (extraOptions && Object.keys(extraOptions).length) { + options = Object.assign({}, extraOptions, this.options); + } + + const signer = new DKIMSigner(options, this.keys, inputStream, output); + setImmediate(() => { + signer.signStream(); + if (writeValue) { + setImmediate(() => { + inputStream.end(writeValue); + }); + } + }); + + return output; + } +} + +module.exports = DKIM; diff --git a/node_modules/nodemailer/lib/dkim/message-parser.js b/node_modules/nodemailer/lib/dkim/message-parser.js new file mode 100644 index 0000000000000000000000000000000000000000..126057e25dcd9b06ccabb675e0005a2ecd669713 --- /dev/null +++ b/node_modules/nodemailer/lib/dkim/message-parser.js @@ -0,0 +1,154 @@ +'use strict'; + +const { Transform } = require('stream'); + +/** + * MessageParser instance is a transform stream that separates message headers + * from the rest of the body. Headers are emitted with the 'headers' event. Message + * body is passed on as the resulting stream. + */ +class MessageParser extends Transform { + constructor(options) { + super(options); + this.lastBytes = Buffer.alloc(4); + this.headersParsed = false; + this.headerBytes = 0; + this.headerChunks = []; + this.rawHeaders = false; + this.bodySize = 0; + } + + /** + * Keeps count of the last 4 bytes in order to detect line breaks on chunk boundaries + * + * @param {Buffer} data Next data chunk from the stream + */ + updateLastBytes(data) { + const lblen = this.lastBytes.length; + const nblen = Math.min(data.length, lblen); + + // shift existing bytes + for (let i = 0, len = lblen - nblen; i < len; i++) { + this.lastBytes[i] = this.lastBytes[i + nblen]; + } + + // add new bytes + for (let i = 1; i <= nblen; i++) { + this.lastBytes[lblen - i] = data[data.length - i]; + } + } + + /** + * Finds and removes message headers from the remaining body. We want to keep + * headers separated until final delivery to be able to modify these + * + * @param {Buffer} data Next chunk of data + * @return {Boolean} Returns true if headers are already found or false otherwise + */ + checkHeaders(data) { + if (this.headersParsed) { + return true; + } + + const lblen = this.lastBytes.length; + let headerPos = 0; + for (let i = 0, len = this.lastBytes.length + data.length; i < len; i++) { + let chr; + if (i < lblen) { + chr = this.lastBytes[i]; + } else { + chr = data[i - lblen]; + } + if (chr === 0x0a && i) { + const pr1 = i - 1 < lblen ? this.lastBytes[i - 1] : data[i - 1 - lblen]; + const pr2 = i > 1 ? (i - 2 < lblen ? this.lastBytes[i - 2] : data[i - 2 - lblen]) : false; + if (pr1 === 0x0a) { + this.headersParsed = true; + headerPos = i - lblen + 1; + this.headerBytes += headerPos; + break; + } else if (pr1 === 0x0d && pr2 === 0x0a) { + this.headersParsed = true; + headerPos = i - lblen + 1; + this.headerBytes += headerPos; + break; + } + } + } + + if (this.headersParsed) { + this.headerChunks.push(data.slice(0, headerPos)); + this.rawHeaders = Buffer.concat(this.headerChunks, this.headerBytes); + this.headerChunks = null; + this.emit('headers', this.parseHeaders()); + if (data.length - 1 > headerPos) { + const chunk = data.slice(headerPos); + this.bodySize += chunk.length; + // this would be the first chunk of data sent downstream + setImmediate(() => this.push(chunk)); + } + return false; + } + + this.headerBytes += data.length; + this.headerChunks.push(data); + + // store last 4 bytes to catch header break + this.updateLastBytes(data); + + return false; + } + + _transform(chunk, encoding, callback) { + if (!chunk || !chunk.length) { + return callback(); + } + + if (typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + + let headersFound; + + try { + headersFound = this.checkHeaders(chunk); + } catch (E) { + return callback(E); + } + + if (headersFound) { + this.bodySize += chunk.length; + this.push(chunk); + } + + setImmediate(callback); + } + + _flush(callback) { + if (this.headerChunks) { + const chunk = Buffer.concat(this.headerChunks, this.headerBytes); + this.bodySize += chunk.length; + this.push(chunk); + this.headerChunks = null; + } + callback(); + } + + parseHeaders() { + const lines = (this.rawHeaders || '').toString().split(/\r?\n/); + for (let i = lines.length - 1; i > 0; i--) { + if (/^\s/.test(lines[i])) { + lines[i - 1] += '\n' + lines[i]; + lines.splice(i, 1); + } + } + return lines + .filter(line => line.trim()) + .map(line => ({ + key: line.substr(0, line.indexOf(':')).trim().toLowerCase(), + line + })); + } +} + +module.exports = MessageParser; diff --git a/node_modules/nodemailer/lib/dkim/relaxed-body.js b/node_modules/nodemailer/lib/dkim/relaxed-body.js new file mode 100644 index 0000000000000000000000000000000000000000..3ac5cf5e1f0f9697e6abe86ce1af021db5f74e2d --- /dev/null +++ b/node_modules/nodemailer/lib/dkim/relaxed-body.js @@ -0,0 +1,154 @@ +'use strict'; + +// streams through a message body and calculates relaxed body hash + +const { Transform } = require('stream'); +const crypto = require('crypto'); + +class RelaxedBody extends Transform { + constructor(options) { + super(); + options = options || {}; + this.chunkBuffer = []; + this.chunkBufferLen = 0; + this.bodyHash = crypto.createHash(options.hashAlgo || 'sha1'); + this.remainder = ''; + this.byteLength = 0; + + this.debug = options.debug; + this._debugBody = options.debug ? [] : false; + } + + updateHash(chunk) { + let bodyStr; + + // find next remainder + let nextRemainder = ''; + + // This crux finds and removes the spaces from the last line and the newline characters after the last non-empty line + // If we get another chunk that does not match this description then we can restore the previously processed data + let state = 'file'; + for (let i = chunk.length - 1; i >= 0; i--) { + const c = chunk[i]; + + if (state === 'file' && (c === 0x0a || c === 0x0d)) { + // do nothing, found \n or \r at the end of chunk, stil end of file + } else if (state === 'file' && (c === 0x09 || c === 0x20)) { + // switch to line ending mode, this is the last non-empty line + state = 'line'; + } else if (state === 'line' && (c === 0x09 || c === 0x20)) { + // do nothing, found ' ' or \t at the end of line, keep processing the last non-empty line + } else if (state === 'file' || state === 'line') { + // non line/file ending character found, switch to body mode + state = 'body'; + if (i === chunk.length - 1) { + // final char is not part of line end or file end, so do nothing + break; + } + } + + if (i === 0) { + // reached to the beginning of the chunk, check if it is still about the ending + // and if the remainder also matches + if ( + (state === 'file' && (!this.remainder || /[\r\n]$/.test(this.remainder))) || + (state === 'line' && (!this.remainder || /[ \t]$/.test(this.remainder))) + ) { + // keep everything + this.remainder += chunk.toString('binary'); + return; + } else if (state === 'line' || state === 'file') { + // process existing remainder as normal line but store the current chunk + nextRemainder = chunk.toString('binary'); + chunk = false; + break; + } + } + + if (state !== 'body') { + continue; + } + + // reached first non ending byte + nextRemainder = chunk.slice(i + 1).toString('binary'); + chunk = chunk.slice(0, i + 1); + break; + } + + let needsFixing = !!this.remainder; + if (chunk && !needsFixing) { + // check if we even need to change anything + for (let i = 0, len = chunk.length; i < len; i++) { + if (i && chunk[i] === 0x0a && chunk[i - 1] !== 0x0d) { + // missing \r before \n + needsFixing = true; + break; + } else if (i && chunk[i] === 0x0d && chunk[i - 1] === 0x20) { + // trailing WSP found + needsFixing = true; + break; + } else if (i && chunk[i] === 0x20 && chunk[i - 1] === 0x20) { + // multiple spaces found, needs to be replaced with just one + needsFixing = true; + break; + } else if (chunk[i] === 0x09) { + // TAB found, needs to be replaced with a space + needsFixing = true; + break; + } + } + } + + if (needsFixing) { + bodyStr = this.remainder + (chunk ? chunk.toString('binary') : ''); + this.remainder = nextRemainder; + bodyStr = bodyStr + .replace(/\r?\n/g, '\n') // use js line endings + .replace(/[ \t]*$/gm, '') // remove line endings, rtrim + .replace(/[ \t]+/gm, ' ') // single spaces + .replace(/\n/g, '\r\n'); // restore rfc822 line endings + chunk = Buffer.from(bodyStr, 'binary'); + } else if (nextRemainder) { + this.remainder = nextRemainder; + } + + if (this.debug) { + this._debugBody.push(chunk); + } + this.bodyHash.update(chunk); + } + + _transform(chunk, encoding, callback) { + if (!chunk || !chunk.length) { + return callback(); + } + + if (typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + + this.updateHash(chunk); + + this.byteLength += chunk.length; + this.push(chunk); + callback(); + } + + _flush(callback) { + // generate final hash and emit it + if (/[\r\n]$/.test(this.remainder) && this.byteLength > 2) { + // add terminating line end + this.bodyHash.update(Buffer.from('\r\n')); + } + if (!this.byteLength) { + // emit empty line buffer to keep the stream flowing + this.push(Buffer.from('\r\n')); + // this.bodyHash.update(Buffer.from('\r\n')); + } + + this.emit('hash', this.bodyHash.digest('base64'), this.debug ? Buffer.concat(this._debugBody) : false); + callback(); + } +} + +module.exports = RelaxedBody; diff --git a/node_modules/nodemailer/lib/dkim/sign.js b/node_modules/nodemailer/lib/dkim/sign.js new file mode 100644 index 0000000000000000000000000000000000000000..39409d8490104a413b4a1073a963c0188e3137ef --- /dev/null +++ b/node_modules/nodemailer/lib/dkim/sign.js @@ -0,0 +1,116 @@ +'use strict'; + +const punycode = require('../punycode'); +const mimeFuncs = require('../mime-funcs'); +const crypto = require('crypto'); + +/** + * Returns DKIM signature header line + * + * @param {Object} headers Parsed headers object from MessageParser + * @param {String} bodyHash Base64 encoded hash of the message + * @param {Object} options DKIM options + * @param {String} options.domainName Domain name to be signed for + * @param {String} options.keySelector DKIM key selector to use + * @param {String} options.privateKey DKIM private key to use + * @return {String} Complete header line + */ + +module.exports = (headers, hashAlgo, bodyHash, options) => { + options = options || {}; + + // all listed fields from RFC4871 #5.5 + const defaultFieldNames = + 'From:Sender:Reply-To:Subject:Date:Message-ID:To:' + + 'Cc:MIME-Version:Content-Type:Content-Transfer-Encoding:Content-ID:' + + 'Content-Description:Resent-Date:Resent-From:Resent-Sender:' + + 'Resent-To:Resent-Cc:Resent-Message-ID:In-Reply-To:References:' + + 'List-Id:List-Help:List-Unsubscribe:List-Subscribe:List-Post:' + + 'List-Owner:List-Archive'; + + const fieldNames = options.headerFieldNames || defaultFieldNames; + + const canonicalizedHeaderData = relaxedHeaders(headers, fieldNames, options.skipFields); + const dkimHeader = generateDKIMHeader(options.domainName, options.keySelector, canonicalizedHeaderData.fieldNames, hashAlgo, bodyHash); + + canonicalizedHeaderData.headers += 'dkim-signature:' + relaxedHeaderLine(dkimHeader); + + const signer = crypto.createSign(('rsa-' + hashAlgo).toUpperCase()); + signer.update(canonicalizedHeaderData.headers); + let signature; + try { + signature = signer.sign(options.privateKey, 'base64'); + } catch (_E) { + return false; + } + + return dkimHeader + signature.replace(/(^.{73}|.{75}(?!\r?\n|\r))/g, '$&\r\n ').trim(); +}; + +module.exports.relaxedHeaders = relaxedHeaders; + +function generateDKIMHeader(domainName, keySelector, fieldNames, hashAlgo, bodyHash) { + const dkim = [ + 'v=1', + 'a=rsa-' + hashAlgo, + 'c=relaxed/relaxed', + 'd=' + punycode.toASCII(domainName), + 'q=dns/txt', + 's=' + keySelector, + 'bh=' + bodyHash, + 'h=' + fieldNames + ].join('; '); + + return mimeFuncs.foldLines('DKIM-Signature: ' + dkim, 76) + ';\r\n b='; +} + +function relaxedHeaders(headers, fieldNames, skipFields) { + const includedFields = new Set(); + const skip = new Set(); + const headerFields = new Map(); + + (skipFields || '') + .toLowerCase() + .split(':') + .forEach(field => { + skip.add(field.trim()); + }); + + (fieldNames || '') + .toLowerCase() + .split(':') + .filter(field => !skip.has(field.trim())) + .forEach(field => { + includedFields.add(field.trim()); + }); + + for (let i = headers.length - 1; i >= 0; i--) { + const line = headers[i]; + // only include the first value from bottom to top + if (includedFields.has(line.key) && !headerFields.has(line.key)) { + headerFields.set(line.key, relaxedHeaderLine(line.line)); + } + } + + const headersList = []; + const fields = []; + includedFields.forEach(field => { + if (headerFields.has(field)) { + fields.push(field); + headersList.push(field + ':' + headerFields.get(field)); + } + }); + + return { + headers: headersList.join('\r\n') + '\r\n', + fieldNames: fields.join(':') + }; +} + +function relaxedHeaderLine(line) { + return line + .substr(line.indexOf(':') + 1) + .replace(/\r?\n/g, '') + .replace(/\s+/g, ' ') + .trim(); +} diff --git a/node_modules/nodemailer/lib/errors.js b/node_modules/nodemailer/lib/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..c43363b1dc1f03e4bb1e41daa7d52ceab9a70b5b --- /dev/null +++ b/node_modules/nodemailer/lib/errors.js @@ -0,0 +1,58 @@ +'use strict'; + +/** + * Nodemailer Error Codes + * + * Centralized error code definitions for consistent error handling. + * + * Usage: + * const errors = require('./errors'); + * let err = new Error('Connection closed'); + * err.code = errors.ECONNECTION; + */ + +/** + * Error code descriptions for documentation and debugging + */ +const ERROR_CODES = { + // Connection errors + ECONNECTION: 'Connection closed unexpectedly', + ETIMEDOUT: 'Connection or operation timed out', + ESOCKET: 'Socket-level error', + EDNS: 'DNS resolution failed', + + // TLS/Security errors + ETLS: 'TLS handshake or STARTTLS failed', + EREQUIRETLS: 'REQUIRETLS not supported by server (RFC 8689)', + + // Protocol errors + EPROTOCOL: 'Invalid SMTP server response', + EENVELOPE: 'Invalid mail envelope (sender or recipients)', + EMESSAGE: 'Message delivery error', + ESTREAM: 'Stream processing error', + + // Authentication errors + EAUTH: 'Authentication failed', + ENOAUTH: 'Authentication credentials not provided', + EOAUTH2: 'OAuth2 token generation or refresh error', + + // Resource errors + EMAXLIMIT: 'Pool resource limit reached (max messages per connection)', + + // Transport-specific errors + ESENDMAIL: 'Sendmail command error', + ESES: 'AWS SES transport error', + + // Configuration and access errors + ECONFIG: 'Invalid configuration', + EPROXY: 'Proxy connection error', + EFILEACCESS: 'File access rejected (disableFileAccess is set)', + EURLACCESS: 'URL access rejected (disableUrlAccess is set)', + EFETCH: 'HTTP fetch error' +}; + +// Export error codes as string constants and the full definitions object +module.exports = { ERROR_CODES }; +for (const code of Object.keys(ERROR_CODES)) { + module.exports[code] = code; +} diff --git a/node_modules/nodemailer/lib/fetch/cookies.js b/node_modules/nodemailer/lib/fetch/cookies.js new file mode 100644 index 0000000000000000000000000000000000000000..bd1c328ee79430a10ac3684f3aa52b5ddeabe3c8 --- /dev/null +++ b/node_modules/nodemailer/lib/fetch/cookies.js @@ -0,0 +1,276 @@ +'use strict'; + +// module to handle cookies + +const urllib = require('url'); + +const SESSION_TIMEOUT = 1800; // 30 min + +/** + * Creates a biskviit cookie jar for managing cookie values in memory + * + * @constructor + * @param {Object} [options] Optional options object + */ +class Cookies { + constructor(options) { + this.options = options || {}; + this.cookies = []; + } + + /** + * Stores a cookie string to the cookie storage + * + * @param {String} cookieStr Value from the 'Set-Cookie:' header + * @param {String} url Current URL + */ + set(cookieStr, url) { + const urlparts = urllib.parse(url || ''); + const cookie = this.parse(cookieStr); + let domain; + + if (cookie.domain) { + domain = cookie.domain.replace(/^\./, ''); + + // do not allow cross origin cookies + if ( + // can't be valid if the requested domain is shorter than current hostname + urlparts.hostname.length < domain.length || + // prefix domains with dot to be sure that partial matches are not used + ('.' + urlparts.hostname).substr(-domain.length + 1) !== '.' + domain + ) { + cookie.domain = urlparts.hostname; + } + } else { + cookie.domain = urlparts.hostname; + } + + if (!cookie.path) { + cookie.path = this.getPath(urlparts.pathname); + } + + // if no expire date, then use sessionTimeout value + if (!cookie.expires) { + cookie.expires = new Date(Date.now() + (Number(this.options.sessionTimeout || SESSION_TIMEOUT) || SESSION_TIMEOUT) * 1000); + } + + return this.add(cookie); + } + + /** + * Returns cookie string for the 'Cookie:' header. + * + * @param {String} url URL to check for + * @returns {String} Cookie header or empty string if no matches were found + */ + get(url) { + return this.list(url) + .map(cookie => cookie.name + '=' + cookie.value) + .join('; '); + } + + /** + * Lists all valied cookie objects for the specified URL + * + * @param {String} url URL to check for + * @returns {Array} An array of cookie objects + */ + list(url) { + const result = []; + + for (let i = this.cookies.length - 1; i >= 0; i--) { + const cookie = this.cookies[i]; + + if (this.isExpired(cookie)) { + this.cookies.splice(i, 1); + continue; + } + + if (this.match(cookie, url)) { + result.unshift(cookie); + } + } + + return result; + } + + /** + * Parses cookie string from the 'Set-Cookie:' header + * + * @param {String} cookieStr String from the 'Set-Cookie:' header + * @returns {Object} Cookie object + */ + parse(cookieStr) { + const cookie = {}; + + (cookieStr || '') + .toString() + .split(';') + .forEach(cookiePart => { + const valueParts = cookiePart.split('='); + const key = valueParts.shift().trim().toLowerCase(); + let value = valueParts.join('=').trim(); + let domain; + + if (!key) { + // skip empty parts + return; + } + + switch (key) { + case 'expires': + value = new Date(value); + // ignore date if can not parse it + if (value.toString() !== 'Invalid Date') { + cookie.expires = value; + } + break; + + case 'path': + cookie.path = value; + break; + + case 'domain': + domain = value.toLowerCase(); + if (domain.length && domain.charAt(0) !== '.') { + domain = '.' + domain; // ensure preceeding dot for user set domains + } + cookie.domain = domain; + break; + + case 'max-age': + cookie.expires = new Date(Date.now() + (Number(value) || 0) * 1000); + break; + + case 'secure': + cookie.secure = true; + break; + + case 'httponly': + cookie.httponly = true; + break; + + default: + if (!cookie.name) { + cookie.name = key; + cookie.value = value; + } + } + }); + + return cookie; + } + + /** + * Checks if a cookie object is valid for a specified URL + * + * @param {Object} cookie Cookie object + * @param {String} url URL to check for + * @returns {Boolean} true if cookie is valid for specifiec URL + */ + match(cookie, url) { + const urlparts = urllib.parse(url || ''); + + // check if hostname matches + // .foo.com also matches subdomains, foo.com does not + if ( + urlparts.hostname !== cookie.domain && + (cookie.domain.charAt(0) !== '.' || ('.' + urlparts.hostname).substr(-cookie.domain.length) !== cookie.domain) + ) { + return false; + } + + // check if path matches + const path = this.getPath(urlparts.pathname); + if (path.substr(0, cookie.path.length) !== cookie.path) { + return false; + } + + // check secure argument + if (cookie.secure && urlparts.protocol !== 'https:') { + return false; + } + + return true; + } + + /** + * Adds (or updates/removes if needed) a cookie object to the cookie storage + * + * @param {Object} cookie Cookie value to be stored + */ + add(cookie) { + // nothing to do here + if (!cookie || !cookie.name) { + return false; + } + + // overwrite if has same params + for (let i = 0, len = this.cookies.length; i < len; i++) { + if (this.compare(this.cookies[i], cookie)) { + // check if the cookie needs to be removed instead + if (this.isExpired(cookie)) { + this.cookies.splice(i, 1); // remove expired/unset cookie + return false; + } + + this.cookies[i] = cookie; + return true; + } + } + + // add as new if not already expired + if (!this.isExpired(cookie)) { + this.cookies.push(cookie); + } + + return true; + } + + /** + * Checks if two cookie objects are the same + * + * @param {Object} a Cookie to check against + * @param {Object} b Cookie to check against + * @returns {Boolean} True, if the cookies are the same + */ + compare(a, b) { + return a.name === b.name && a.path === b.path && a.domain === b.domain && a.secure === b.secure && a.httponly === b.httponly; + } + + /** + * Checks if a cookie is expired + * + * @param {Object} cookie Cookie object to check against + * @returns {Boolean} True, if the cookie is expired + */ + isExpired(cookie) { + return (cookie.expires && cookie.expires < new Date()) || !cookie.value; + } + + /** + * Returns normalized cookie path for an URL path argument + * + * @param {String} pathname + * @returns {String} Normalized path + */ + getPath(pathname) { + let path = (pathname || '/').split('/'); + path.pop(); // remove filename part + path = path.join('/').trim(); + + // ensure path prefix / + if (path.charAt(0) !== '/') { + path = '/' + path; + } + + // ensure path suffix / + if (path.substr(-1) !== '/') { + path += '/'; + } + + return path; + } +} + +module.exports = Cookies; diff --git a/node_modules/nodemailer/lib/fetch/index.js b/node_modules/nodemailer/lib/fetch/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6c838365793e8be5c19d2db4f0dadb69fe6dafe1 --- /dev/null +++ b/node_modules/nodemailer/lib/fetch/index.js @@ -0,0 +1,278 @@ +'use strict'; + +const http = require('http'); +const https = require('https'); +const urllib = require('url'); +const zlib = require('zlib'); +const { PassThrough } = require('stream'); +const Cookies = require('./cookies'); +const packageData = require('../../package.json'); +const net = require('net'); +const errors = require('../errors'); + +const MAX_REDIRECTS = 5; + +module.exports = function (url, options) { + return nmfetch(url, options); +}; + +module.exports.Cookies = Cookies; + +function nmfetch(url, options) { + options = options || {}; + + options.fetchRes = options.fetchRes || new PassThrough(); + options.cookies = options.cookies || new Cookies(); + options.redirects = options.redirects || 0; + options.maxRedirects = isNaN(options.maxRedirects) ? MAX_REDIRECTS : options.maxRedirects; + + if (options.cookie) { + [].concat(options.cookie || []).forEach(cookie => { + options.cookies.set(cookie, url); + }); + options.cookie = false; + } + + const fetchRes = options.fetchRes; + const parsed = urllib.parse(url); + let method = (options.method || '').toString().trim().toUpperCase() || 'GET'; + let finished = false; + let cookies; + let body; + + const handler = parsed.protocol === 'https:' ? https : http; + + const headers = { + 'accept-encoding': 'gzip,deflate', + 'user-agent': 'nodemailer/' + packageData.version + }; + + Object.keys(options.headers || {}).forEach(key => { + headers[key.toLowerCase().trim()] = options.headers[key]; + }); + + if (options.userAgent) { + headers['user-agent'] = options.userAgent; + } + + if (parsed.auth) { + headers.Authorization = 'Basic ' + Buffer.from(parsed.auth).toString('base64'); + } + + if ((cookies = options.cookies.get(url))) { + headers.cookie = cookies; + } + + if (options.body) { + if (options.contentType !== false) { + headers['Content-Type'] = options.contentType || 'application/x-www-form-urlencoded'; + } + + if (typeof options.body.pipe === 'function') { + // it's a stream + headers['Transfer-Encoding'] = 'chunked'; + body = options.body; + body.on('error', err => { + if (finished) { + return; + } + finished = true; + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit('error', err); + }); + } else { + if (options.body instanceof Buffer) { + body = options.body; + } else if (typeof options.body === 'object') { + try { + // encodeURIComponent can fail on invalid input (partial emoji etc.) + body = Buffer.from( + Object.keys(options.body) + .map(key => { + const value = options.body[key].toString().trim(); + return encodeURIComponent(key) + '=' + encodeURIComponent(value); + }) + .join('&') + ); + } catch (E) { + if (finished) { + return; + } + finished = true; + E.code = errors.EFETCH; + E.sourceUrl = url; + fetchRes.emit('error', E); + return; + } + } else { + body = Buffer.from(options.body.toString().trim()); + } + + headers['Content-Type'] = options.contentType || 'application/x-www-form-urlencoded'; + headers['Content-Length'] = body.length; + } + // if method is not provided, use POST instead of GET + method = (options.method || '').toString().trim().toUpperCase() || 'POST'; + } + + let req; + const reqOptions = { + method, + host: parsed.hostname, + path: parsed.path, + port: parsed.port ? parsed.port : parsed.protocol === 'https:' ? 443 : 80, + headers, + rejectUnauthorized: false, + agent: false + }; + + if (options.tls) { + Object.assign(reqOptions, options.tls); + } + + if ( + parsed.protocol === 'https:' && + parsed.hostname && + parsed.hostname !== reqOptions.host && + !net.isIP(parsed.hostname) && + !reqOptions.servername + ) { + reqOptions.servername = parsed.hostname; + } + + try { + req = handler.request(reqOptions); + } catch (E) { + finished = true; + setImmediate(() => { + E.code = errors.EFETCH; + E.sourceUrl = url; + fetchRes.emit('error', E); + }); + return fetchRes; + } + + if (options.timeout) { + req.setTimeout(options.timeout, () => { + if (finished) { + return; + } + finished = true; + req.abort(); + const err = new Error('Request Timeout'); + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit('error', err); + }); + } + + req.on('error', err => { + if (finished) { + return; + } + finished = true; + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit('error', err); + }); + + req.on('response', res => { + let inflate; + + if (finished) { + return; + } + + switch (res.headers['content-encoding']) { + case 'gzip': + case 'deflate': + inflate = zlib.createUnzip(); + break; + } + + if (res.headers['set-cookie']) { + [].concat(res.headers['set-cookie'] || []).forEach(cookie => { + options.cookies.set(cookie, url); + }); + } + + if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location) { + // redirect + options.redirects++; + if (options.redirects > options.maxRedirects) { + finished = true; + const err = new Error('Maximum redirect count exceeded'); + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit('error', err); + req.abort(); + return; + } + // redirect does not include POST body + options.method = 'GET'; + options.body = false; + return nmfetch(urllib.resolve(url, res.headers.location), options); + } + + fetchRes.statusCode = res.statusCode; + fetchRes.headers = res.headers; + + if (res.statusCode >= 300 && !options.allowErrorResponse) { + finished = true; + const err = new Error('Invalid status code ' + res.statusCode); + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit('error', err); + req.abort(); + return; + } + + res.on('error', err => { + if (finished) { + return; + } + finished = true; + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit('error', err); + req.abort(); + }); + + if (inflate) { + res.pipe(inflate).pipe(fetchRes); + inflate.on('error', err => { + if (finished) { + return; + } + finished = true; + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit('error', err); + req.abort(); + }); + } else { + res.pipe(fetchRes); + } + }); + + setImmediate(() => { + if (body) { + try { + if (typeof body.pipe === 'function') { + return body.pipe(req); + } + req.write(body); + } catch (err) { + finished = true; + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit('error', err); + return; + } + } + req.end(); + }); + + return fetchRes; +} diff --git a/node_modules/nodemailer/lib/json-transport/index.js b/node_modules/nodemailer/lib/json-transport/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e8b28ed99b2d5e4d96e812ebb53e4825ca6ed905 --- /dev/null +++ b/node_modules/nodemailer/lib/json-transport/index.js @@ -0,0 +1,82 @@ +'use strict'; + +const packageData = require('../../package.json'); +const shared = require('../shared'); + +/** + * Generates a Transport object to generate JSON output + * + * @constructor + * @param {Object} optional config parameter + */ +class JSONTransport { + constructor(options) { + options = options || {}; + + this.options = options; + + this.name = 'JSONTransport'; + this.version = packageData.version; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'json-transport' + }); + } + + /** + *

Compiles a mailcomposer message and forwards it to handler that sends it.

+ * + * @param {Object} emailMessage MailComposer object + * @param {Function} callback Callback function to run when the sending is completed + */ + send(mail, done) { + // Sendmail strips this header line by itself + mail.message.keepBcc = true; + + const envelope = mail.data.envelope || mail.message.getEnvelope(); + const messageId = mail.message.messageId(); + + const recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + this.logger.info( + { + tnx: 'send', + messageId + }, + 'Composing JSON structure of %s to <%s>', + messageId, + recipients.join(', ') + ); + + setImmediate(() => { + mail.normalize((err, data) => { + if (err) { + this.logger.error( + { + err, + tnx: 'send', + messageId + }, + 'Failed building JSON structure for %s. %s', + messageId, + err.message + ); + return done(err); + } + + delete data.envelope; + delete data.normalizedHeaders; + + return done(null, { + envelope, + messageId, + message: this.options.skipEncoding ? data : JSON.stringify(data) + }); + }); + }); + } +} + +module.exports = JSONTransport; diff --git a/node_modules/nodemailer/lib/mail-composer/index.js b/node_modules/nodemailer/lib/mail-composer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..dc180e2d97f856748cb10bd52aa5472069b15d6b --- /dev/null +++ b/node_modules/nodemailer/lib/mail-composer/index.js @@ -0,0 +1,632 @@ +/* eslint no-undefined: 0 */ + +'use strict'; + +const MimeNode = require('../mime-node'); +const mimeFuncs = require('../mime-funcs'); +const { parseDataURI } = require('../shared'); + +/** + * Creates the object for composing a MimeNode instance out from the mail options + * + * @constructor + * @param {Object} mail Mail options + */ +class MailComposer { + constructor(mail) { + this.mail = mail || {}; + this.message = false; + } + + /** + * Builds MimeNode instance + */ + compile() { + this._alternatives = this.getAlternatives(); + this._htmlNode = this._alternatives.filter(alternative => /^text\/html\b/i.test(alternative.contentType)).pop(); + this._attachments = this.getAttachments(!!this._htmlNode); + + this._useRelated = !!(this._htmlNode && this._attachments.related.length); + this._useAlternative = this._alternatives.length > 1; + this._useMixed = this._attachments.attached.length > 1 || (this._alternatives.length && this._attachments.attached.length === 1); + + // Compose MIME tree + if (this.mail.raw) { + this.message = new MimeNode('message/rfc822', { newline: this.mail.newline }).setRaw(this.mail.raw); + } else if (this._useMixed) { + this.message = this._createMixed(); + } else if (this._useAlternative) { + this.message = this._createAlternative(); + } else if (this._useRelated) { + this.message = this._createRelated(); + } else { + this.message = this._createContentNode( + false, + [] + .concat(this._alternatives || []) + .concat(this._attachments.attached || []) + .shift() || { + contentType: 'text/plain', + content: '' + } + ); + } + + // Add custom headers + if (this.mail.headers) { + this.message.addHeader(this.mail.headers); + } + + // Add headers to the root node, always overrides custom headers + ['from', 'sender', 'to', 'cc', 'bcc', 'reply-to', 'in-reply-to', 'references', 'subject', 'message-id', 'date'].forEach(header => { + const key = header.replace(/-(\w)/g, (o, c) => c.toUpperCase()); + if (this.mail[key]) { + this.message.setHeader(header, this.mail[key]); + } + }); + + // Sets custom envelope + if (this.mail.envelope) { + this.message.setEnvelope(this.mail.envelope); + } + + // ensure Message-Id value + this.message.messageId(); + + return this.message; + } + + /** + * List all attachments. Resulting attachment objects can be used as input for MimeNode nodes + * + * @param {Boolean} findRelated If true separate related attachments from attached ones + * @returns {Object} An object of arrays (`related` and `attached`) + */ + getAttachments(findRelated) { + let eventObject; + const attachments = [].concat(this.mail.attachments || []).map((attachment, i) => { + if (/^data:/i.test(attachment.path || attachment.href)) { + attachment = this._processDataUrl(attachment); + } + + const contentType = + attachment.contentType || mimeFuncs.detectMimeType(attachment.filename || attachment.path || attachment.href || 'bin'); + + const isImage = /^image\//i.test(contentType); + const isMessageNode = /^message\//i.test(contentType); + + const contentDisposition = + attachment.contentDisposition || (isMessageNode || (isImage && attachment.cid) ? 'inline' : 'attachment'); + + let contentTransferEncoding; + if ('contentTransferEncoding' in attachment) { + // also contains `false`, to set + contentTransferEncoding = attachment.contentTransferEncoding; + } else if (isMessageNode) { + // the content might include non-ASCII bytes but at this point we do not know it yet + contentTransferEncoding = '8bit'; + } else { + contentTransferEncoding = 'base64'; // the default + } + + const data = { + contentType, + contentDisposition, + contentTransferEncoding + }; + + if (attachment.filename) { + data.filename = attachment.filename; + } else if (!isMessageNode && attachment.filename !== false) { + data.filename = (attachment.path || attachment.href || '').split('/').pop().split('?').shift() || 'attachment-' + (i + 1); + if (data.filename.indexOf('.') < 0) { + data.filename += '.' + mimeFuncs.detectExtension(data.contentType); + } + } + + if (/^https?:\/\//i.test(attachment.path)) { + attachment.href = attachment.path; + attachment.path = undefined; + } + + if (attachment.cid) { + data.cid = attachment.cid; + } + + if (attachment.raw) { + data.raw = attachment.raw; + } else if (attachment.path) { + data.content = { + path: attachment.path + }; + } else if (attachment.href) { + data.content = { + href: attachment.href, + httpHeaders: attachment.httpHeaders + }; + } else { + data.content = attachment.content || ''; + } + + if (attachment.encoding) { + data.encoding = attachment.encoding; + } + + if (attachment.headers) { + data.headers = attachment.headers; + } + + return data; + }); + + if (this.mail.icalEvent) { + eventObject = Object.assign({}, this._getIcalEvent()); + + eventObject.contentType = 'application/ics'; + if (!eventObject.headers) { + eventObject.headers = {}; + } + eventObject.filename = eventObject.filename || 'invite.ics'; + eventObject.headers['Content-Disposition'] = 'attachment'; + eventObject.headers['Content-Transfer-Encoding'] = 'base64'; + } + + if (!findRelated) { + return { + attached: attachments.concat(eventObject || []), + related: [] + }; + } + + return { + attached: attachments.filter(attachment => !attachment.cid).concat(eventObject || []), + related: attachments.filter(attachment => !!attachment.cid) + }; + } + + /** + * Returns the icalEvent value with `path`/`href`/data uri input normalized into + * a `content` entry, the same way as for regular attachments. The same event is + * included twice (as a text/calendar alternative and as an application/ics + * attachment), so the shared content object is marked to be resolved just once + * and the buffered result is reused by the second node. + * + * @returns {Object} Normalized icalEvent data + */ + _getIcalEvent() { + if (!this._icalEvent) { + let icalEvent; + if ( + typeof this.mail.icalEvent === 'object' && + (this.mail.icalEvent.content || this.mail.icalEvent.path || this.mail.icalEvent.href || this.mail.icalEvent.raw) + ) { + icalEvent = Object.assign({}, this.mail.icalEvent); + } else { + icalEvent = { + content: this.mail.icalEvent + }; + } + + if (/^data:/i.test(icalEvent.path || icalEvent.href)) { + icalEvent = this._processDataUrl(icalEvent); + } + + if (/^https?:\/\//i.test(icalEvent.path)) { + icalEvent.href = icalEvent.path; + icalEvent.path = undefined; + } + + if (!icalEvent.raw) { + // map file path and URL values into `content`, otherwise the content + // nodes would render an empty body + if (icalEvent.path) { + icalEvent.content = { + path: icalEvent.path + }; + icalEvent.path = undefined; + } else if (icalEvent.href) { + icalEvent.content = { + href: icalEvent.href, + httpHeaders: icalEvent.httpHeaders + }; + icalEvent.href = undefined; + } + } + + if (icalEvent.content && typeof icalEvent.content === 'object') { + // we are going to have the same attachment twice, so mark this to be + // resolved just once + icalEvent.content._resolve = true; + } + + this._icalEvent = icalEvent; + } + + return this._icalEvent; + } + + /** + * List alternatives. Resulting objects can be used as input for MimeNode nodes + * + * @returns {Array} An array of alternative elements. Includes the `text` and `html` values as well + */ + getAlternatives() { + const alternatives = []; + let text, html, watchHtml, amp, eventObject; + + if (this.mail.text) { + if ( + typeof this.mail.text === 'object' && + (this.mail.text.content || this.mail.text.path || this.mail.text.href || this.mail.text.raw) + ) { + text = this.mail.text; + } else { + text = { + content: this.mail.text + }; + } + text.contentType = 'text/plain; charset=utf-8'; + } + + if (this.mail.watchHtml) { + if ( + typeof this.mail.watchHtml === 'object' && + (this.mail.watchHtml.content || this.mail.watchHtml.path || this.mail.watchHtml.href || this.mail.watchHtml.raw) + ) { + watchHtml = this.mail.watchHtml; + } else { + watchHtml = { + content: this.mail.watchHtml + }; + } + watchHtml.contentType = 'text/watch-html; charset=utf-8'; + } + + if (this.mail.amp) { + if ( + typeof this.mail.amp === 'object' && + (this.mail.amp.content || this.mail.amp.path || this.mail.amp.href || this.mail.amp.raw) + ) { + amp = this.mail.amp; + } else { + amp = { + content: this.mail.amp + }; + } + amp.contentType = 'text/x-amp-html; charset=utf-8'; + } + + // NB! when including attachments with a calendar alternative you might end up in a blank screen on some clients + if (this.mail.icalEvent) { + eventObject = Object.assign({}, this._getIcalEvent()); + + eventObject.filename = false; + eventObject.contentType = + 'text/calendar; charset=utf-8; method=' + (eventObject.method || 'PUBLISH').toString().trim().toUpperCase(); + if (!eventObject.headers) { + eventObject.headers = {}; + } + } + + if (this.mail.html) { + if ( + typeof this.mail.html === 'object' && + (this.mail.html.content || this.mail.html.path || this.mail.html.href || this.mail.html.raw) + ) { + html = this.mail.html; + } else { + html = { + content: this.mail.html + }; + } + html.contentType = 'text/html; charset=utf-8'; + } + + [] + .concat(text || []) + .concat(watchHtml || []) + .concat(amp || []) + .concat(html || []) + .concat(eventObject || []) + .concat(this.mail.alternatives || []) + .forEach(alternative => { + if (/^data:/i.test(alternative.path || alternative.href)) { + alternative = this._processDataUrl(alternative); + } + + const data = { + contentType: + alternative.contentType || + mimeFuncs.detectMimeType(alternative.filename || alternative.path || alternative.href || 'txt'), + contentTransferEncoding: alternative.contentTransferEncoding + }; + + if (alternative.filename) { + data.filename = alternative.filename; + } + + if (/^https?:\/\//i.test(alternative.path)) { + alternative.href = alternative.path; + alternative.path = undefined; + } + + if (alternative.raw) { + data.raw = alternative.raw; + } else if (alternative.path) { + data.content = { + path: alternative.path + }; + } else if (alternative.href) { + data.content = { + href: alternative.href + }; + } else { + data.content = alternative.content || ''; + } + + if (alternative.encoding) { + data.encoding = alternative.encoding; + } + + if (alternative.headers) { + data.headers = alternative.headers; + } + + alternatives.push(data); + }); + + return alternatives; + } + + /** + * Builds multipart/mixed node. It should always contain different type of elements on the same level + * eg. text + attachments + * + * @param {Object} parentNode Parent for this note. If it does not exist, a root node is created + * @returns {Object} MimeNode node element + */ + _createMixed(parentNode) { + const node = parentNode + ? parentNode.createChild('multipart/mixed', { + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }) + : new MimeNode('multipart/mixed', { + baseBoundary: this.mail.baseBoundary, + textEncoding: this.mail.textEncoding, + boundaryPrefix: this.mail.boundaryPrefix, + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }); + + if (this._useAlternative) { + this._createAlternative(node); + } else if (this._useRelated) { + this._createRelated(node); + } + + [] + .concat((!this._useAlternative && this._alternatives) || []) + .concat(this._attachments.attached || []) + .forEach(element => { + // if the element is a html node from related subpart then ignore it + if (!this._useRelated || element !== this._htmlNode) { + this._createContentNode(node, element); + } + }); + + return node; + } + + /** + * Builds multipart/alternative node. It should always contain same type of elements on the same level + * eg. text + html view of the same data + * + * @param {Object} parentNode Parent for this note. If it does not exist, a root node is created + * @returns {Object} MimeNode node element + */ + _createAlternative(parentNode) { + const node = parentNode + ? parentNode.createChild('multipart/alternative', { + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }) + : new MimeNode('multipart/alternative', { + baseBoundary: this.mail.baseBoundary, + textEncoding: this.mail.textEncoding, + boundaryPrefix: this.mail.boundaryPrefix, + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }); + + this._alternatives.forEach(alternative => { + if (this._useRelated && this._htmlNode === alternative) { + this._createRelated(node); + } else { + this._createContentNode(node, alternative); + } + }); + + return node; + } + + /** + * Builds multipart/related node. It should always contain html node with related attachments + * + * @param {Object} parentNode Parent for this note. If it does not exist, a root node is created + * @returns {Object} MimeNode node element + */ + _createRelated(parentNode) { + const node = parentNode + ? parentNode.createChild('multipart/related; type="text/html"', { + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }) + : new MimeNode('multipart/related; type="text/html"', { + baseBoundary: this.mail.baseBoundary, + textEncoding: this.mail.textEncoding, + boundaryPrefix: this.mail.boundaryPrefix, + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }); + + this._createContentNode(node, this._htmlNode); + + this._attachments.related.forEach(alternative => this._createContentNode(node, alternative)); + + return node; + } + + /** + * Creates a regular node with contents + * + * @param {Object} parentNode Parent for this note. If it does not exist, a root node is created + * @param {Object} element Node data + * @returns {Object} MimeNode node element + */ + _createContentNode(parentNode, element) { + element = element || {}; + element.content = element.content || ''; + + const encoding = (element.encoding || 'utf8') + .toString() + .toLowerCase() + .replace(/[-_\s]/g, ''); + + const node = parentNode + ? parentNode.createChild(element.contentType, { + filename: element.filename, + textEncoding: this.mail.textEncoding, + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }) + : new MimeNode(element.contentType, { + filename: element.filename, + baseBoundary: this.mail.baseBoundary, + textEncoding: this.mail.textEncoding, + boundaryPrefix: this.mail.boundaryPrefix, + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }); + + // add custom headers + if (element.headers) { + node.addHeader(element.headers); + } + + if (element.cid) { + node.setHeader('Content-Id', '<' + element.cid.replace(/[<>]/g, '') + '>'); + } + + if (element.contentTransferEncoding) { + node.setHeader('Content-Transfer-Encoding', element.contentTransferEncoding); + } else if (this.mail.encoding && /^text\//i.test(element.contentType)) { + node.setHeader('Content-Transfer-Encoding', this.mail.encoding); + } + + if (!/^text\//i.test(element.contentType) || element.contentDisposition) { + node.setHeader( + 'Content-Disposition', + element.contentDisposition || (element.cid && /^image\//i.test(element.contentType) ? 'inline' : 'attachment') + ); + } + + if (typeof element.content === 'string' && !['utf8', 'usascii', 'ascii'].includes(encoding)) { + element.content = Buffer.from(element.content, encoding); + } + + // prefer pregenerated raw content + if (element.raw) { + node.setRaw(element.raw); + } else { + node.setContent(element.content); + } + + return node; + } + + /** + * Parses data uri and converts it to a Buffer + * + * @param {Object} element Content element + * @return {Object} Parsed element + */ + _processDataUrl(element) { + const dataUrl = element.path || element.href; + + // Early validation to prevent ReDoS + if (!dataUrl || typeof dataUrl !== 'string') { + return element; + } + + if (!dataUrl.startsWith('data:')) { + return element; + } + + if (dataUrl.length > 52428800) { + // 52428800 chars = 50MB limit for data URL string (~37.5MB decoded image) + // Extract content type before rejecting to preserve MIME type + let detectedType = 'application/octet-stream'; + const commaPos = dataUrl.indexOf(','); + + if (commaPos > 0 && commaPos < 200) { + // Parse header safely with size limit + const header = dataUrl.substring(5, commaPos); // skip 'data:' + const parts = header.split(';'); + if (parts[0] && parts[0].includes('/')) { + detectedType = parts[0].trim(); + } + } + + // Return empty content for excessively long data URLs + return Object.assign({}, element, { + path: false, + href: false, + content: Buffer.alloc(0), + contentType: element.contentType || detectedType + }); + } + + let parsedDataUri; + try { + parsedDataUri = parseDataURI(dataUrl); + } catch (_err) { + return element; + } + + if (!parsedDataUri) { + return element; + } + + element.content = parsedDataUri.data; + element.contentType = element.contentType || parsedDataUri.contentType; + + if ('path' in element) { + element.path = false; + } + + if ('href' in element) { + element.href = false; + } + + return element; + } +} + +module.exports = MailComposer; diff --git a/node_modules/nodemailer/lib/mailer/index.js b/node_modules/nodemailer/lib/mailer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..34fc3f2323c2ad0418699f972b4eb5cc299fa1e7 --- /dev/null +++ b/node_modules/nodemailer/lib/mailer/index.js @@ -0,0 +1,454 @@ +'use strict'; + +const EventEmitter = require('events'); +const shared = require('../shared'); +const mimeTypes = require('../mime-funcs/mime-types'); +const MailComposer = require('../mail-composer'); +const DKIM = require('../dkim'); +const httpProxyClient = require('../smtp-connection/http-proxy-client'); +const errors = require('../errors'); +const util = require('util'); +const urllib = require('url'); +const packageData = require('../../package.json'); +const MailMessage = require('./mail-message'); +const net = require('net'); +const dns = require('dns'); +const crypto = require('crypto'); + +/** + * Creates an object for exposing the Mail API + * + * @constructor + * @param {Object} transporter Transport object instance to pass the mails to + */ +class Mail extends EventEmitter { + constructor(transporter, options, defaults) { + super(); + + this.options = options || {}; + this._defaults = defaults || {}; + + this._defaultPlugins = { + compile: [(...args) => this._convertDataImages(...args)], + stream: [] + }; + + this._userPlugins = { + compile: [], + stream: [] + }; + + this.meta = new Map(); + + this.dkim = this.options.dkim ? new DKIM(this.options.dkim) : false; + + this.transporter = transporter; + this.transporter.mailer = this; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'mail' + }); + + this.logger.debug( + { + tnx: 'create' + }, + 'Creating transport: %s', + this.getVersionString() + ); + + // setup emit handlers for the transporter + if (typeof this.transporter.on === 'function') { + // deprecated log interface + this.transporter.on('log', log => { + this.logger.debug( + { + tnx: 'transport' + }, + '%s: %s', + log.type, + log.message + ); + }); + + // transporter errors + this.transporter.on('error', err => { + this.logger.error( + { + err, + tnx: 'transport' + }, + 'Transport Error: %s', + err.message + ); + this.emit('error', err); + }); + + // indicates if the sender has became idle + this.transporter.on('idle', (...args) => { + this.emit('idle', ...args); + }); + + // indicates if the sender has became idle and all connections are terminated + this.transporter.on('clear', (...args) => { + this.emit('clear', ...args); + }); + } + + /** + * Optional methods passed to the underlying transport object + */ + ['close', 'isIdle', 'verify'].forEach(method => { + this[method] = (...args) => { + if (typeof this.transporter[method] === 'function') { + if (method === 'verify' && typeof this.getSocket === 'function') { + this.transporter.getSocket = this.getSocket; + this.getSocket = false; + } + return this.transporter[method](...args); + } + + this.logger.warn( + { + tnx: 'transport', + methodName: method + }, + 'Non existing method %s called for transport', + method + ); + return false; + }; + }); + + // setup proxy handling + if (this.options.proxy && typeof this.options.proxy === 'string') { + this.setupProxy(this.options.proxy); + } + } + + use(step, plugin) { + step = (step || '').toString(); + if (!this._userPlugins.hasOwnProperty(step)) { + this._userPlugins[step] = [plugin]; + } else { + this._userPlugins[step].push(plugin); + } + + return this; + } + + /** + * Sends an email using the preselected transport object + * + * @param {Object} data E-data description + * @param {Function?} callback Callback to run once the sending succeeded or failed + */ + sendMail(data, callback = null) { + let promise; + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = shared.callbackPromise(resolve, reject); + }); + } + + if (typeof this.getSocket === 'function') { + this.transporter.getSocket = this.getSocket; + this.getSocket = false; + } + + const mail = new MailMessage(this, data); + + this.logger.debug( + { + tnx: 'transport', + name: this.transporter.name, + version: this.transporter.version, + action: 'send' + }, + 'Sending mail using %s/%s', + this.transporter.name, + this.transporter.version + ); + + this._processPlugins('compile', mail, err => { + if (err) { + this.logger.error( + { + err, + tnx: 'plugin', + action: 'compile' + }, + 'PluginCompile Error: %s', + err.message + ); + return callback(err); + } + + mail.message = new MailComposer(mail.data).compile(); + + mail.setMailerHeader(); + mail.setPriorityHeaders(); + mail.setListHeaders(); + + this._processPlugins('stream', mail, err => { + if (err) { + this.logger.error( + { + err, + tnx: 'plugin', + action: 'stream' + }, + 'PluginStream Error: %s', + err.message + ); + return callback(err); + } + + if (mail.data.dkim || this.dkim) { + mail.message.processFunc(input => { + const dkim = mail.data.dkim ? new DKIM(mail.data.dkim) : this.dkim; + this.logger.debug( + { + tnx: 'DKIM', + messageId: mail.message.messageId(), + dkimDomains: dkim.keys.map(key => key.keySelector + '.' + key.domainName).join(', ') + }, + 'Signing outgoing message with %s keys', + dkim.keys.length + ); + return dkim.sign(input, mail.data._dkim); + }); + } + + this.transporter.send(mail, (...args) => { + if (args[0]) { + this.logger.error( + { + err: args[0], + tnx: 'transport', + action: 'send' + }, + 'Send Error: %s', + args[0].message + ); + } + callback(...args); + }); + }); + }); + + return promise; + } + + getVersionString() { + return util.format( + '%s (%s; +%s; %s/%s)', + packageData.name, + packageData.version, + packageData.homepage, + this.transporter.name, + this.transporter.version + ); + } + + _processPlugins(step, mail, callback) { + step = (step || '').toString(); + + if (!this._userPlugins.hasOwnProperty(step)) { + return callback(); + } + + const userPlugins = this._userPlugins[step] || []; + const defaultPlugins = this._defaultPlugins[step] || []; + + if (userPlugins.length) { + this.logger.debug( + { + tnx: 'transaction', + pluginCount: userPlugins.length, + step + }, + 'Using %s plugins for %s', + userPlugins.length, + step + ); + } + + if (userPlugins.length + defaultPlugins.length === 0) { + return callback(); + } + + let pos = 0; + let block = 'default'; + const processPlugins = () => { + let curplugins = block === 'default' ? defaultPlugins : userPlugins; + if (pos >= curplugins.length) { + if (block === 'default' && userPlugins.length) { + block = 'user'; + pos = 0; + curplugins = userPlugins; + } else { + return callback(); + } + } + const plugin = curplugins[pos++]; + plugin(mail, err => { + if (err) { + return callback(err); + } + processPlugins(); + }); + }; + + processPlugins(); + } + + /** + * Sets up proxy handler for a Nodemailer object + * + * @param {String} proxyUrl Proxy configuration url + */ + setupProxy(proxyUrl) { + const proxy = urllib.parse(proxyUrl); + + // setup socket handler for the mailer object + this.getSocket = (options, callback) => { + const protocol = proxy.protocol.replace(/:$/, '').toLowerCase(); + + if (this.meta.has('proxy_handler_' + protocol)) { + return this.meta.get('proxy_handler_' + protocol)(proxy, options, callback); + } + + switch (protocol) { + // Connect using a HTTP CONNECT method + case 'http': + case 'https': + httpProxyClient(proxy.href, options.port, options.host, (err, socket) => { + if (err) { + return callback(err); + } + return callback(null, { + connection: socket + }); + }); + return; + case 'socks': + case 'socks5': + case 'socks4': + case 'socks4a': { + if (!this.meta.has('proxy_socks_module')) { + let err = new Error('Socks module not loaded'); + err.code = errors.EPROXY; + return callback(err); + } + const connect = ipaddress => { + const proxyV2 = !!this.meta.get('proxy_socks_module').SocksClient; + const socksClient = proxyV2 ? this.meta.get('proxy_socks_module').SocksClient : this.meta.get('proxy_socks_module'); + const proxyType = Number(proxy.protocol.replace(/\D/g, '')) || 5; + const connectionOpts = { + proxy: { + ipaddress, + port: Number(proxy.port), + type: proxyType + }, + [proxyV2 ? 'destination' : 'target']: { + host: options.host, + port: options.port + }, + command: 'connect' + }; + + if (proxy.auth) { + const username = decodeURIComponent(proxy.auth.split(':').shift()); + const password = decodeURIComponent(proxy.auth.split(':').pop()); + if (proxyV2) { + connectionOpts.proxy.userId = username; + connectionOpts.proxy.password = password; + } else if (proxyType === 4) { + connectionOpts.userid = username; + } else { + connectionOpts.authentication = { + username, + password + }; + } + } + + socksClient.createConnection(connectionOpts, (err, info) => { + if (err) { + return callback(err); + } + return callback(null, { + connection: info.socket || info + }); + }); + }; + + if (net.isIP(proxy.hostname)) { + return connect(proxy.hostname); + } + + return dns.resolve(proxy.hostname, (err, address) => { + if (err) { + return callback(err); + } + connect(Array.isArray(address) ? address[0] : address); + }); + } + } + let err = new Error('Unknown proxy configuration'); + err.code = errors.EPROXY; + callback(err); + }; + } + + _convertDataImages(mail, callback) { + if ((!this.options.attachDataUrls && !mail.data.attachDataUrls) || !mail.data.html) { + return callback(); + } + mail.resolveContent( + mail.data, + 'html', + { disableFileAccess: mail.data.disableFileAccess, disableUrlAccess: mail.data.disableUrlAccess }, + (err, html) => { + if (err) { + return callback(err); + } + let cidCounter = 0; + html = (html || '') + .toString() + .replace( + /(]{0,1024} src\s{0,20}=[\s"']{0,20})(data:([^;]+);[^"'>\s]+)/gi, + (match, prefix, dataUri, mimeType) => { + const cid = crypto.randomBytes(10).toString('hex') + '@localhost'; + if (!mail.data.attachments) { + mail.data.attachments = []; + } + if (!Array.isArray(mail.data.attachments)) { + mail.data.attachments = [].concat(mail.data.attachments || []); + } + mail.data.attachments.push({ + path: dataUri, + cid, + filename: 'image-' + ++cidCounter + '.' + mimeTypes.detectExtension(mimeType) + }); + return prefix + 'cid:' + cid; + } + ); + mail.data.html = html; + callback(); + } + ); + } + + set(key, value) { + return this.meta.set(key, value); + } + + get(key) { + return this.meta.get(key); + } +} + +module.exports = Mail; diff --git a/node_modules/nodemailer/lib/mailer/mail-message.js b/node_modules/nodemailer/lib/mailer/mail-message.js new file mode 100644 index 0000000000000000000000000000000000000000..83544d9d63ec37307b6d902d4293bb7c05acccfc --- /dev/null +++ b/node_modules/nodemailer/lib/mailer/mail-message.js @@ -0,0 +1,322 @@ +'use strict'; + +const shared = require('../shared'); +const MimeNode = require('../mime-node'); +const mimeFuncs = require('../mime-funcs'); + +class MailMessage { + constructor(mailer, data) { + this.mailer = mailer; + this.data = {}; + this.message = null; + + data = data || {}; + const options = mailer.options || {}; + const defaults = mailer._defaults || {}; + + Object.assign(this.data, data); + + this.data.headers = this.data.headers || {}; + + // apply defaults + Object.keys(defaults).forEach(key => { + if (!(key in this.data)) { + this.data[key] = defaults[key]; + } else if (key === 'headers') { + // headers is a special case. Allow setting individual default headers + Object.keys(defaults.headers).forEach(key => { + if (!(key in this.data.headers)) { + this.data.headers[key] = defaults.headers[key]; + } + }); + } + }); + + // force specific keys from transporter options + ['disableFileAccess', 'disableUrlAccess', 'normalizeHeaderKey'].forEach(key => { + if (key in options) { + this.data[key] = options[key]; + } + }); + } + + resolveContent(...args) { + return shared.resolveContent(...args); + } + + resolveAll(callback) { + const keys = [ + [this.data, 'html'], + [this.data, 'text'], + [this.data, 'watchHtml'], + [this.data, 'amp'], + [this.data, 'icalEvent'] + ]; + + if (this.data.alternatives && this.data.alternatives.length) { + this.data.alternatives.forEach((alternative, i) => { + keys.push([this.data.alternatives, i]); + }); + } + + if (this.data.attachments && this.data.attachments.length) { + this.data.attachments.forEach((attachment, i) => { + if (!attachment.filename) { + attachment.filename = + (attachment.path || attachment.href || '').split('/').pop().split('?').shift() || 'attachment-' + (i + 1); + if (attachment.filename.indexOf('.') < 0) { + attachment.filename += '.' + mimeFuncs.detectExtension(attachment.contentType); + } + } + + if (!attachment.contentType) { + attachment.contentType = mimeFuncs.detectMimeType(attachment.filename || attachment.path || attachment.href || 'bin'); + } + + keys.push([this.data.attachments, i]); + }); + } + + const mimeNode = new MimeNode(); + + const addressKeys = ['from', 'to', 'cc', 'bcc', 'sender', 'replyTo']; + + addressKeys.forEach(address => { + let value; + if (this.message) { + value = [].concat(mimeNode._parseAddresses(this.message.getHeader(address === 'replyTo' ? 'reply-to' : address)) || []); + } else if (this.data[address]) { + value = [].concat(mimeNode._parseAddresses(this.data[address]) || []); + } + if (value && value.length) { + this.data[address] = value; + } else if (address in this.data) { + this.data[address] = null; + } + }); + + const singleKeys = ['from', 'sender']; + singleKeys.forEach(address => { + if (this.data[address]) { + this.data[address] = this.data[address].shift(); + } + }); + + let pos = 0; + const resolveNext = () => { + if (pos >= keys.length) { + return callback(null, this.data); + } + const args = keys[pos++]; + if (!args[0] || !args[0][args[1]]) { + return resolveNext(); + } + shared.resolveContent( + ...args, + { disableFileAccess: this.data.disableFileAccess, disableUrlAccess: this.data.disableUrlAccess }, + (err, value) => { + if (err) { + return callback(err); + } + + const node = { + content: value + }; + if (args[0][args[1]] && typeof args[0][args[1]] === 'object' && !Buffer.isBuffer(args[0][args[1]])) { + Object.keys(args[0][args[1]]).forEach(key => { + if (!(key in node) && !['content', 'path', 'href', 'raw'].includes(key)) { + node[key] = args[0][args[1]][key]; + } + }); + } + + args[0][args[1]] = node; + resolveNext(); + } + ); + }; + + setImmediate(() => resolveNext()); + } + + normalize(callback) { + const envelope = this.data.envelope || this.message.getEnvelope(); + const messageId = this.message.messageId(); + + this.resolveAll((err, data) => { + if (err) { + return callback(err); + } + + data.envelope = envelope; + data.messageId = messageId; + + ['html', 'text', 'watchHtml', 'amp'].forEach(key => { + if (data[key] && data[key].content) { + if (typeof data[key].content === 'string') { + data[key] = data[key].content; + } else if (Buffer.isBuffer(data[key].content)) { + data[key] = data[key].content.toString(); + } + } + }); + + if (data.icalEvent && Buffer.isBuffer(data.icalEvent.content)) { + data.icalEvent.content = data.icalEvent.content.toString('base64'); + data.icalEvent.encoding = 'base64'; + } + + if (data.alternatives && data.alternatives.length) { + data.alternatives.forEach(alternative => { + if (alternative && alternative.content && Buffer.isBuffer(alternative.content)) { + alternative.content = alternative.content.toString('base64'); + alternative.encoding = 'base64'; + } + }); + } + + if (data.attachments && data.attachments.length) { + data.attachments.forEach(attachment => { + if (attachment && attachment.content && Buffer.isBuffer(attachment.content)) { + attachment.content = attachment.content.toString('base64'); + attachment.encoding = 'base64'; + } + }); + } + + data.normalizedHeaders = {}; + Object.keys(data.headers || {}).forEach(key => { + let value = [].concat(data.headers[key] || []).shift(); + value = (value && value.value) || value; + if (value) { + if (['references', 'in-reply-to', 'message-id', 'content-id'].includes(key)) { + value = this.message._encodeHeaderValue(key, value); + } + data.normalizedHeaders[key] = value; + } + }); + + if (data.list && typeof data.list === 'object') { + const listHeaders = this._getListHeaders(data.list); + listHeaders.forEach(entry => { + data.normalizedHeaders[entry.key] = entry.value.map(val => (val && val.value) || val).join(', '); + }); + } + + if (data.references) { + data.normalizedHeaders.references = this.message._encodeHeaderValue('references', data.references); + } + + if (data.inReplyTo) { + data.normalizedHeaders['in-reply-to'] = this.message._encodeHeaderValue('in-reply-to', data.inReplyTo); + } + + return callback(null, data); + }); + } + + setMailerHeader() { + if (!this.message || !this.data.xMailer) { + return; + } + this.message.setHeader('X-Mailer', this.data.xMailer); + } + + setPriorityHeaders() { + if (!this.message || !this.data.priority) { + return; + } + switch ((this.data.priority || '').toString().toLowerCase()) { + case 'high': + this.message.setHeader('X-Priority', '1 (Highest)'); + this.message.setHeader('X-MSMail-Priority', 'High'); + this.message.setHeader('Importance', 'High'); + break; + case 'low': + this.message.setHeader('X-Priority', '5 (Lowest)'); + this.message.setHeader('X-MSMail-Priority', 'Low'); + this.message.setHeader('Importance', 'Low'); + break; + default: + // do not add anything, since all messages are 'Normal' by default + } + } + + setListHeaders() { + if (!this.message || !this.data.list || typeof this.data.list !== 'object') { + return; + } + // add optional List-* headers + this._getListHeaders(this.data.list).forEach(listHeader => { + listHeader.value.forEach(value => { + this.message.addHeader(listHeader.key, value); + }); + }); + } + + _getListHeaders(listData) { + // make sure an url looks like + return Object.keys(listData).map(key => ({ + key: 'list-' + key.toLowerCase().trim(), + value: [].concat(listData[key] || []).map(value => ({ + prepared: true, + foldLines: true, + value: [] + .concat(value || []) + .map(value => { + if (typeof value === 'string') { + value = { + url: value + }; + } + + if (value && value.url) { + if (key.toLowerCase().trim() === 'id') { + // List-ID: "comment" + // strip CR/LF so a comment can't inject extra header lines + let comment = (value.comment || '').toString().replace(/\r?\n|\r/g, ' '); + if (mimeFuncs.isPlainText(comment)) { + comment = '"' + comment + '"'; + } else { + comment = mimeFuncs.encodeWord(comment); + } + + // List-ID expects a bare domain-like identifier, so strip the + // scheme prefix that _formatListUrl adds or passes through + return ( + (value.comment ? comment + ' ' : '') + this._formatListUrl(value.url).replace(/^<[^:]+:\/{0,2}/, '<') + ); + } + + // List-*: (comment) + // strip CR/LF so a comment can't inject extra header lines + let comment = (value.comment || '').toString().replace(/\r?\n|\r/g, ' '); + if (!mimeFuncs.isPlainText(comment)) { + comment = mimeFuncs.encodeWord(comment); + } + + return this._formatListUrl(value.url) + (value.comment ? ' (' + comment + ')' : ''); + } + + return ''; + }) + .filter(value => value) + .join(', ') + })) + })); + } + + _formatListUrl(url) { + url = url.replace(/[\s<]+|[\s>]+/g, ''); + if (/^(https?|mailto|ftp):/.test(url)) { + return '<' + url + '>'; + } + if (/^[^@]+@[^@]+$/.test(url)) { + return ''; + } + + return ''; + } +} + +module.exports = MailMessage; diff --git a/node_modules/nodemailer/lib/mime-funcs/index.js b/node_modules/nodemailer/lib/mime-funcs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fed4363ea72e6fa5b20fe774dae878bb422cc142 --- /dev/null +++ b/node_modules/nodemailer/lib/mime-funcs/index.js @@ -0,0 +1,610 @@ +/* eslint no-control-regex:0 */ + +'use strict'; + +const base64 = require('../base64'); +const qp = require('../qp'); +const mimeTypes = require('./mime-types'); + +module.exports = { + /** + * Checks if a value is plaintext string (uses only printable 7bit chars) + * + * @param {String} value String to be tested + * @returns {Boolean} true if it is a plaintext string + */ + isPlainText(value, isParam) { + const re = isParam ? /[\x00-\x08\x0b\x0c\x0e-\x1f"\u0080-\uFFFF]/ : /[\x00-\x08\x0b\x0c\x0e-\x1f\u0080-\uFFFF]/; + return typeof value === 'string' && !re.test(value); + }, + + /** + * Checks if a multi line string containes lines longer than the selected value. + * + * Useful when detecting if a mail message needs any processing at all – + * if only plaintext characters are used and lines are short, then there is + * no need to encode the values in any way. If the value is plaintext but has + * longer lines then allowed, then use format=flowed + * + * @param {Number} lineLength Max line length to check for + * @returns {Boolean} Returns true if there is at least one line longer than lineLength chars + */ + hasLongerLines(str, lineLength) { + if (str.length > 128 * 1024) { + // do not test strings longer than 128kB + return true; + } + return new RegExp('^.{' + (lineLength + 1) + ',}', 'm').test(str); + }, + + /** + * Encodes a string or an Buffer to an UTF-8 MIME Word (rfc2047) + * + * @param {String|Buffer} data String to be encoded + * @param {String} mimeWordEncoding='Q' Encoding for the mime word, either Q or B + * @param {Number} [maxLength=0] If set, split mime words into several chunks if needed + * @return {String} Single or several mime words joined together + */ + encodeWord(data, mimeWordEncoding, maxLength) { + mimeWordEncoding = (mimeWordEncoding || 'Q').toString().toUpperCase().trim().charAt(0); + maxLength = maxLength || 0; + + let encodedStr; + const toCharset = 'UTF-8'; + + if (maxLength && maxLength > 7 + toCharset.length) { + maxLength -= 7 + toCharset.length; + } + + if (mimeWordEncoding === 'Q') { + // https://tools.ietf.org/html/rfc2047#section-5 rule (3) + encodedStr = qp.encode(data).replace(/[^a-z0-9!*+\-/=]/gi, chr => { + const ord = chr.charCodeAt(0).toString(16).toUpperCase(); + if (chr === ' ') { + return '_'; + } + return '=' + (ord.length === 1 ? '0' + ord : ord); + }); + } else if (mimeWordEncoding === 'B') { + encodedStr = typeof data === 'string' ? data : base64.encode(data); + maxLength = maxLength ? Math.max(3, ((maxLength - (maxLength % 4)) / 4) * 3) : 0; + } + + if (maxLength && (mimeWordEncoding !== 'B' ? encodedStr : base64.encode(data)).length > maxLength) { + if (mimeWordEncoding === 'Q') { + encodedStr = this.splitMimeEncodedString(encodedStr, maxLength).join('?= =?' + toCharset + '?' + mimeWordEncoding + '?'); + } else { + // RFC2047 6.3 (2) states that encoded-word must include an integral number of characters, so no chopping unicode sequences + const parts = []; + let lpart = ''; + for (let i = 0, len = encodedStr.length; i < len; i++) { + let chr = encodedStr.charAt(i); + + if (/[\ud83c\ud83d\ud83e]/.test(chr) && i < len - 1) { + // composite emoji byte, so add the next byte as well + chr += encodedStr.charAt(++i); + } + + // check if we can add this character to the existing string + // without breaking byte length limit + if (Buffer.byteLength(lpart + chr) <= maxLength || i === 0) { + lpart += chr; + } else { + // we hit the length limit, so push the existing string and start over + parts.push(base64.encode(lpart)); + lpart = chr; + } + } + if (lpart) { + parts.push(base64.encode(lpart)); + } + + if (parts.length > 1) { + encodedStr = parts.join('?= =?' + toCharset + '?' + mimeWordEncoding + '?'); + } else { + encodedStr = parts.join(''); + } + } + } else if (mimeWordEncoding === 'B') { + encodedStr = base64.encode(data); + } + + return '=?' + toCharset + '?' + mimeWordEncoding + '?' + encodedStr + (encodedStr.substr(-2) === '?=' ? '' : '?='); + }, + + /** + * Finds word sequences with non ascii text and converts these to mime words + * + * @param {String} value String to be encoded + * @param {String} mimeWordEncoding='Q' Encoding for the mime word, either Q or B + * @param {Number} [maxLength=0] If set, split mime words into several chunks if needed + * @param {Boolean} [encodeAll=false] If true and the value needs encoding then encodes entire string, not just the smallest match + * @return {String} String with possible mime words + */ + encodeWords(value, mimeWordEncoding, maxLength, encodeAll) { + maxLength = maxLength || 0; + + // find first word with a non-printable ascii or special symbol in it + const firstMatch = value.match(/(?:^|\s)([^\s]*["\u0080-\uFFFF])/); + if (!firstMatch) { + return value; + } + + if (encodeAll) { + // if it is requested to encode everything or the string contains something that resebles encoded word, then encode everything + return this.encodeWord(value, mimeWordEncoding, maxLength); + } + + // find the last word with a non-printable ascii in it + const lastMatch = value.match(/(["\u0080-\uFFFF][^\s]*)[^"\u0080-\uFFFF]*$/); + if (!lastMatch) { + // should not happen + return value; + } + + const startIndex = + firstMatch.index + + ( + firstMatch[0].match(/[^\s]/) || { + index: 0 + } + ).index; + const endIndex = lastMatch.index + (lastMatch[1] || '').length; + + return ( + (startIndex ? value.substr(0, startIndex) : '') + + this.encodeWord(value.substring(startIndex, endIndex), mimeWordEncoding || 'Q', maxLength) + + (endIndex < value.length ? value.substr(endIndex) : '') + ); + }, + + /** + * Joins parsed header value together as 'value; param1=value1; param2=value2' + * PS: We are following RFC 822 for the list of special characters that we need to keep in quotes. + * Refer: https://www.w3.org/Protocols/rfc1341/4_Content-Type.html + * @param {Object} structured Parsed header value + * @return {String} joined header value + */ + buildHeaderValue(structured) { + const paramsArray = []; + + Object.keys(structured.params || {}).forEach(param => { + // filename might include unicode characters so it is a special case + // other values probably do not + const value = structured.params[param]; + if (!this.isPlainText(value, true) || value.length >= 75) { + this.buildHeaderParam(param, value, 50).forEach(encodedParam => { + if (!/[\s"\\;:/=(),<>@[\]?]|^[-']|'$/.test(encodedParam.value) || encodedParam.key.substr(-1) === '*') { + paramsArray.push(encodedParam.key + '=' + encodedParam.value); + } else { + paramsArray.push(encodedParam.key + '=' + JSON.stringify(encodedParam.value)); + } + }); + } else if (/[\s'"\\;:/=(),<>@[\]?]|^-/.test(value)) { + paramsArray.push(param + '=' + JSON.stringify(value)); + } else { + paramsArray.push(param + '=' + value); + } + }); + + return structured.value + (paramsArray.length ? '; ' + paramsArray.join('; ') : ''); + }, + + /** + * Encodes a string or an Buffer to an UTF-8 Parameter Value Continuation encoding (rfc2231) + * Useful for splitting long parameter values. + * + * For example + * title="unicode string" + * becomes + * title*0*=utf-8''unicode + * title*1*=%20string + * + * @param {String|Buffer} data String to be encoded + * @param {Number} [maxLength=50] Max length for generated chunks + * @param {String} [fromCharset='UTF-8'] Source sharacter set + * @return {Array} A list of encoded keys and headers + */ + buildHeaderParam(key, data, maxLength) { + const list = []; + let encodedStr = typeof data === 'string' ? data : (data || '').toString(); + let chr, ord; + let line; + let startPos = 0; + let i, len; + + maxLength = maxLength || 50; + + // process ascii only text + if (this.isPlainText(data, true)) { + // check if conversion is even needed + if (encodedStr.length <= maxLength) { + return [ + { + key, + value: encodedStr + } + ]; + } + + encodedStr = encodedStr.replace(new RegExp('.{' + maxLength + '}', 'g'), str => { + list.push({ + line: str + }); + return ''; + }); + + if (encodedStr) { + list.push({ + line: encodedStr + }); + } + } else { + if (/[\uD800-\uDBFF]/.test(encodedStr)) { + // string containts surrogate pairs, so normalize it to an array of bytes + const encodedStrArr = []; + for (i = 0, len = encodedStr.length; i < len; i++) { + chr = encodedStr.charAt(i); + ord = chr.charCodeAt(0); + if (ord >= 0xd800 && ord <= 0xdbff && i < len - 1) { + chr += encodedStr.charAt(i + 1); + encodedStrArr.push(chr); + i++; + } else { + encodedStrArr.push(chr); + } + } + encodedStr = encodedStrArr; + } + + // first line includes the charset and language info and needs to be encoded + // even if it does not contain any unicode characters + line = "utf-8''"; + let encoded = true; + startPos = 0; + + // process text with unicode or special chars + for (i = 0, len = encodedStr.length; i < len; i++) { + chr = encodedStr[i]; + + if (encoded) { + chr = this.safeEncodeURIComponent(chr); + } else { + // try to urlencode current char + chr = chr === ' ' ? chr : this.safeEncodeURIComponent(chr); + // By default it is not required to encode a line, the need + // only appears when the string contains unicode or special chars + // in this case we start processing the line over and encode all chars + if (chr !== encodedStr[i]) { + // Check if it is even possible to add the encoded char to the line + // If not, there is no reason to use this line, just push it to the list + // and start a new line with the char that needs encoding + if ((this.safeEncodeURIComponent(line) + chr).length >= maxLength) { + list.push({ + line, + encoded + }); + line = ''; + startPos = i - 1; + } else { + encoded = true; + i = startPos; + line = ''; + continue; + } + } + } + + // if the line is already too long, push it to the list and start a new one + if ((line + chr).length >= maxLength) { + list.push({ + line, + encoded + }); + line = chr = encodedStr[i] === ' ' ? ' ' : this.safeEncodeURIComponent(encodedStr[i]); + if (chr === encodedStr[i]) { + encoded = false; + startPos = i - 1; + } else { + encoded = true; + } + } else { + line += chr; + } + } + + if (line) { + list.push({ + line, + encoded + }); + } + } + + return list.map((item, i) => ({ + // encoded lines: {name}*{part}* + // unencoded lines: {name}*{part} + // if any line needs to be encoded then the first line (part==0) is always encoded + key: key + '*' + i + (item.encoded ? '*' : ''), + value: item.line + })); + }, + + /** + * Parses a header value with key=value arguments into a structured + * object. + * + * parseHeaderValue('content-type: text/plain; CHARSET='UTF-8'') -> + * { + * 'value': 'text/plain', + * 'params': { + * 'charset': 'UTF-8' + * } + * } + * + * @param {String} str Header value + * @return {Object} Header value as a parsed structure + */ + parseHeaderValue(str) { + const response = { + value: false, + params: {} + }; + let key = false; + let value = ''; + let type = 'value'; + let quote = false; + let escaped = false; + let chr; + + for (let i = 0, len = str.length; i < len; i++) { + chr = str.charAt(i); + if (type === 'key') { + if (chr === '=') { + key = value.trim().toLowerCase(); + type = 'value'; + value = ''; + continue; + } + value += chr; + } else { + if (escaped) { + value += chr; + } else if (chr === '\\') { + escaped = true; + continue; + } else if (quote && chr === quote) { + quote = false; + } else if (!quote && chr === '"') { + quote = chr; + } else if (!quote && chr === ';') { + if (key === false) { + response.value = value.trim(); + } else { + response.params[key] = value.trim(); + } + type = 'key'; + value = ''; + } else { + value += chr; + } + escaped = false; + } + } + + if (type === 'value') { + if (key === false) { + response.value = value.trim(); + } else { + response.params[key] = value.trim(); + } + } else if (value.trim()) { + response.params[value.trim().toLowerCase()] = ''; + } + + // handle parameter value continuations + // https://tools.ietf.org/html/rfc2231#section-3 + + // preprocess values + Object.keys(response.params).forEach(key => { + let actualKey, nr, match, value; + if ((match = key.match(/(\*(\d+)|\*(\d+)\*|\*)$/))) { + actualKey = key.substr(0, match.index); + nr = Number(match[2] || match[3]) || 0; + + if (!response.params[actualKey] || typeof response.params[actualKey] !== 'object') { + response.params[actualKey] = { + charset: false, + values: [] + }; + } + + value = response.params[key]; + + if (nr === 0 && match[0].substr(-1) === '*' && (match = value.match(/^([^']*)'[^']*'(.*)$/))) { + response.params[actualKey].charset = match[1] || 'iso-8859-1'; + value = match[2]; + } + + response.params[actualKey].values[nr] = value; + + // remove the old reference + delete response.params[key]; + } + }); + + // concatenate split rfc2231 strings and convert encoded strings to mime encoded words + Object.keys(response.params).forEach(key => { + let value; + if (response.params[key] && Array.isArray(response.params[key].values)) { + value = response.params[key].values.map(val => val || '').join(''); + + if (response.params[key].charset) { + // convert "%AB" to "=?charset?Q?=AB?=" + response.params[key] = + '=?' + + response.params[key].charset + + '?Q?' + + value + // fix invalidly encoded chars + .replace(/[=?_\s]/g, s => { + const c = s.charCodeAt(0).toString(16); + if (s === ' ') { + return '_'; + } + return '%' + (c.length < 2 ? '0' : '') + c; + }) + // change from urlencoding to percent encoding + .replace(/%/g, '=') + + '?='; + } else { + response.params[key] = value; + } + } + }); + + return response; + }, + + /** + * Returns file extension for a content type string. If no suitable extensions + * are found, 'bin' is used as the default extension + * + * @param {String} mimeType Content type to be checked for + * @return {String} File extension + */ + detectExtension: mimeType => mimeTypes.detectExtension(mimeType), + + /** + * Returns content type for a file extension. If no suitable content types + * are found, 'application/octet-stream' is used as the default content type + * + * @param {String} extension Extension to be checked for + * @return {String} File extension + */ + detectMimeType: extension => mimeTypes.detectMimeType(extension), + + /** + * Folds long lines, useful for folding header lines (afterSpace=false) and + * flowed text (afterSpace=true) + * + * @param {String} str String to be folded + * @param {Number} [lineLength=76] Maximum length of a line + * @param {Boolean} afterSpace If true, leave a space in th end of a line + * @return {String} String with folded lines + */ + foldLines(str, lineLength, afterSpace) { + str = (str || '').toString(); + lineLength = lineLength || 76; + + let pos = 0; + const len = str.length; + let result = ''; + let line, match; + + while (pos < len) { + line = str.substr(pos, lineLength); + if (line.length < lineLength) { + result += line; + break; + } + if ((match = line.match(/^[^\n\r]*(\r?\n|\r)/))) { + line = match[0]; + result += line; + pos += line.length; + continue; + } else if ((match = line.match(/(\s+)[^\s]*$/)) && match[0].length - (afterSpace ? (match[1] || '').length : 0) < line.length) { + line = line.substr(0, line.length - (match[0].length - (afterSpace ? (match[1] || '').length : 0))); + } else if ((match = str.substr(pos + line.length).match(/^[^\s]+(\s*)/))) { + line = line + match[0].substr(0, match[0].length - (!afterSpace ? (match[1] || '').length : 0)); + } + + result += line; + pos += line.length; + if (pos < len) { + result += '\r\n'; + } + } + + return result; + }, + + /** + * Splits a mime encoded string. Needed for dividing mime words into smaller chunks + * + * @param {String} str Mime encoded string to be split up + * @param {Number} maxlen Maximum length of characters for one part (minimum 12) + * @return {Array} Split string + */ + splitMimeEncodedString: (str, maxlen) => { + const lines = []; + let curLine, match, chr, done; + + // require at least 12 symbols to fit possible 4 octet UTF-8 sequences + maxlen = Math.max(maxlen || 0, 12); + + while (str.length) { + curLine = str.substr(0, maxlen); + + // move incomplete escaped char back to main + if ((match = curLine.match(/[=][0-9A-F]?$/i))) { + curLine = curLine.substr(0, match.index); + } + + done = false; + while (!done) { + done = true; + // check if not middle of a unicode char sequence + if ((match = str.substr(curLine.length).match(/^[=]([0-9A-F]{2})/i))) { + chr = parseInt(match[1], 16); + // invalid sequence, move one char back anc recheck + if (chr < 0xc2 && chr > 0x7f) { + curLine = curLine.substr(0, curLine.length - 3); + done = false; + } + } + } + + if (curLine.length) { + lines.push(curLine); + } + str = str.substr(curLine.length); + } + + return lines; + }, + + encodeURICharComponent: chr => { + let res = ''; + let ord = chr.charCodeAt(0).toString(16).toUpperCase(); + + if (ord.length % 2) { + ord = '0' + ord; + } + + if (ord.length > 2) { + for (let i = 0, len = ord.length / 2; i < len; i++) { + res += '%' + ord.substr(i, 2); + } + } else { + res += '%' + ord; + } + + return res; + }, + + safeEncodeURIComponent(str) { + str = (str || '').toString(); + + try { + // might throw if we try to encode invalid sequences, eg. partial emoji + str = encodeURIComponent(str); + } catch (_E) { + // should never run + return str.replace(/[^\x00-\x1F *'()<>@,;:\\"[\]?=\u007F-\uFFFF]+/g, ''); + } + + // ensure chars that are not handled by encodeURICompent are converted as well + return str.replace(/[\x00-\x1F *'()<>@,;:\\"[\]?=\u007F-\uFFFF]/g, chr => this.encodeURICharComponent(chr)); + } +}; diff --git a/node_modules/nodemailer/lib/mime-funcs/mime-types.js b/node_modules/nodemailer/lib/mime-funcs/mime-types.js new file mode 100644 index 0000000000000000000000000000000000000000..11096430250e1778cf7202b8571ea1524ca9ecaa --- /dev/null +++ b/node_modules/nodemailer/lib/mime-funcs/mime-types.js @@ -0,0 +1,2109 @@ +/* eslint quote-props: 0 */ + +'use strict'; + +const path = require('path'); + +const defaultMimeType = 'application/octet-stream'; +const defaultExtension = 'bin'; + +const mimeTypes = new Map([ + ['application/acad', 'dwg'], + ['application/applixware', 'aw'], + ['application/arj', 'arj'], + ['application/atom+xml', 'xml'], + ['application/atomcat+xml', 'atomcat'], + ['application/atomsvc+xml', 'atomsvc'], + ['application/base64', ['mm', 'mme']], + ['application/binhex', 'hqx'], + ['application/binhex4', 'hqx'], + ['application/book', ['book', 'boo']], + ['application/ccxml+xml,', 'ccxml'], + ['application/cdf', 'cdf'], + ['application/cdmi-capability', 'cdmia'], + ['application/cdmi-container', 'cdmic'], + ['application/cdmi-domain', 'cdmid'], + ['application/cdmi-object', 'cdmio'], + ['application/cdmi-queue', 'cdmiq'], + ['application/clariscad', 'ccad'], + ['application/commonground', 'dp'], + ['application/cu-seeme', 'cu'], + ['application/davmount+xml', 'davmount'], + ['application/drafting', 'drw'], + ['application/dsptype', 'tsp'], + ['application/dssc+der', 'dssc'], + ['application/dssc+xml', 'xdssc'], + ['application/dxf', 'dxf'], + ['application/ecmascript', ['js', 'es']], + ['application/emma+xml', 'emma'], + ['application/envoy', 'evy'], + ['application/epub+zip', 'epub'], + ['application/excel', ['xls', 'xl', 'xla', 'xlb', 'xlc', 'xld', 'xlk', 'xll', 'xlm', 'xlt', 'xlv', 'xlw']], + ['application/exi', 'exi'], + ['application/font-tdpfr', 'pfr'], + ['application/fractals', 'fif'], + ['application/freeloader', 'frl'], + ['application/futuresplash', 'spl'], + ['application/geo+json', 'geojson'], + ['application/gnutar', 'tgz'], + ['application/groupwise', 'vew'], + ['application/hlp', 'hlp'], + ['application/hta', 'hta'], + ['application/hyperstudio', 'stk'], + ['application/i-deas', 'unv'], + ['application/iges', ['iges', 'igs']], + ['application/inf', 'inf'], + ['application/internet-property-stream', 'acx'], + ['application/ipfix', 'ipfix'], + ['application/java', 'class'], + ['application/java-archive', 'jar'], + ['application/java-byte-code', 'class'], + ['application/java-serialized-object', 'ser'], + ['application/java-vm', 'class'], + ['application/javascript', 'js'], + ['application/json', 'json'], + ['application/lha', 'lha'], + ['application/lzx', 'lzx'], + ['application/mac-binary', 'bin'], + ['application/mac-binhex', 'hqx'], + ['application/mac-binhex40', 'hqx'], + ['application/mac-compactpro', 'cpt'], + ['application/macbinary', 'bin'], + ['application/mads+xml', 'mads'], + ['application/marc', 'mrc'], + ['application/marcxml+xml', 'mrcx'], + ['application/mathematica', 'ma'], + ['application/mathml+xml', 'mathml'], + ['application/mbedlet', 'mbd'], + ['application/mbox', 'mbox'], + ['application/mcad', 'mcd'], + ['application/mediaservercontrol+xml', 'mscml'], + ['application/metalink4+xml', 'meta4'], + ['application/mets+xml', 'mets'], + ['application/mime', 'aps'], + ['application/mods+xml', 'mods'], + ['application/mp21', 'm21'], + ['application/mp4', 'mp4'], + ['application/mspowerpoint', ['ppt', 'pot', 'pps', 'ppz']], + ['application/msword', ['doc', 'dot', 'w6w', 'wiz', 'word']], + ['application/mswrite', 'wri'], + ['application/mxf', 'mxf'], + ['application/netmc', 'mcp'], + ['application/octet-stream', ['*']], + ['application/oda', 'oda'], + ['application/oebps-package+xml', 'opf'], + ['application/ogg', 'ogx'], + ['application/olescript', 'axs'], + ['application/onenote', 'onetoc'], + ['application/patch-ops-error+xml', 'xer'], + ['application/pdf', 'pdf'], + ['application/pgp-encrypted', 'asc'], + ['application/pgp-signature', 'pgp'], + ['application/pics-rules', 'prf'], + ['application/pkcs-12', 'p12'], + ['application/pkcs-crl', 'crl'], + ['application/pkcs10', 'p10'], + ['application/pkcs7-mime', ['p7c', 'p7m']], + ['application/pkcs7-signature', 'p7s'], + ['application/pkcs8', 'p8'], + ['application/pkix-attr-cert', 'ac'], + ['application/pkix-cert', ['cer', 'crt']], + ['application/pkix-crl', 'crl'], + ['application/pkix-pkipath', 'pkipath'], + ['application/pkixcmp', 'pki'], + ['application/plain', 'text'], + ['application/pls+xml', 'pls'], + ['application/postscript', ['ps', 'ai', 'eps']], + ['application/powerpoint', 'ppt'], + ['application/pro_eng', ['part', 'prt']], + ['application/prs.cww', 'cww'], + ['application/pskc+xml', 'pskcxml'], + ['application/rdf+xml', 'rdf'], + ['application/reginfo+xml', 'rif'], + ['application/relax-ng-compact-syntax', 'rnc'], + ['application/resource-lists+xml', 'rl'], + ['application/resource-lists-diff+xml', 'rld'], + ['application/ringing-tones', 'rng'], + ['application/rls-services+xml', 'rs'], + ['application/rsd+xml', 'rsd'], + ['application/rss+xml', 'xml'], + ['application/rtf', ['rtf', 'rtx']], + ['application/sbml+xml', 'sbml'], + ['application/scvp-cv-request', 'scq'], + ['application/scvp-cv-response', 'scs'], + ['application/scvp-vp-request', 'spq'], + ['application/scvp-vp-response', 'spp'], + ['application/sdp', 'sdp'], + ['application/sea', 'sea'], + ['application/set', 'set'], + ['application/set-payment-initiation', 'setpay'], + ['application/set-registration-initiation', 'setreg'], + ['application/shf+xml', 'shf'], + ['application/sla', 'stl'], + ['application/smil', ['smi', 'smil']], + ['application/smil+xml', 'smi'], + ['application/solids', 'sol'], + ['application/sounder', 'sdr'], + ['application/sparql-query', 'rq'], + ['application/sparql-results+xml', 'srx'], + ['application/srgs', 'gram'], + ['application/srgs+xml', 'grxml'], + ['application/sru+xml', 'sru'], + ['application/ssml+xml', 'ssml'], + ['application/step', ['step', 'stp']], + ['application/streamingmedia', 'ssm'], + ['application/tei+xml', 'tei'], + ['application/thraud+xml', 'tfi'], + ['application/timestamped-data', 'tsd'], + ['application/toolbook', 'tbk'], + ['application/vda', 'vda'], + ['application/vnd.3gpp.pic-bw-large', 'plb'], + ['application/vnd.3gpp.pic-bw-small', 'psb'], + ['application/vnd.3gpp.pic-bw-var', 'pvb'], + ['application/vnd.3gpp2.tcap', 'tcap'], + ['application/vnd.3m.post-it-notes', 'pwn'], + ['application/vnd.accpac.simply.aso', 'aso'], + ['application/vnd.accpac.simply.imp', 'imp'], + ['application/vnd.acucobol', 'acu'], + ['application/vnd.acucorp', 'atc'], + ['application/vnd.adobe.air-application-installer-package+zip', 'air'], + ['application/vnd.adobe.fxp', 'fxp'], + ['application/vnd.adobe.xdp+xml', 'xdp'], + ['application/vnd.adobe.xfdf', 'xfdf'], + ['application/vnd.ahead.space', 'ahead'], + ['application/vnd.airzip.filesecure.azf', 'azf'], + ['application/vnd.airzip.filesecure.azs', 'azs'], + ['application/vnd.amazon.ebook', 'azw'], + ['application/vnd.americandynamics.acc', 'acc'], + ['application/vnd.amiga.ami', 'ami'], + ['application/vnd.android.package-archive', 'apk'], + ['application/vnd.anser-web-certificate-issue-initiation', 'cii'], + ['application/vnd.anser-web-funds-transfer-initiation', 'fti'], + ['application/vnd.antix.game-component', 'atx'], + ['application/vnd.apple.installer+xml', 'mpkg'], + ['application/vnd.apple.mpegurl', 'm3u8'], + ['application/vnd.aristanetworks.swi', 'swi'], + ['application/vnd.audiograph', 'aep'], + ['application/vnd.blueice.multipass', 'mpm'], + ['application/vnd.bmi', 'bmi'], + ['application/vnd.businessobjects', 'rep'], + ['application/vnd.chemdraw+xml', 'cdxml'], + ['application/vnd.chipnuts.karaoke-mmd', 'mmd'], + ['application/vnd.cinderella', 'cdy'], + ['application/vnd.claymore', 'cla'], + ['application/vnd.cloanto.rp9', 'rp9'], + ['application/vnd.clonk.c4group', 'c4g'], + ['application/vnd.cluetrust.cartomobile-config', 'c11amc'], + ['application/vnd.cluetrust.cartomobile-config-pkg', 'c11amz'], + ['application/vnd.commonspace', 'csp'], + ['application/vnd.contact.cmsg', 'cdbcmsg'], + ['application/vnd.cosmocaller', 'cmc'], + ['application/vnd.crick.clicker', 'clkx'], + ['application/vnd.crick.clicker.keyboard', 'clkk'], + ['application/vnd.crick.clicker.palette', 'clkp'], + ['application/vnd.crick.clicker.template', 'clkt'], + ['application/vnd.crick.clicker.wordbank', 'clkw'], + ['application/vnd.criticaltools.wbs+xml', 'wbs'], + ['application/vnd.ctc-posml', 'pml'], + ['application/vnd.cups-ppd', 'ppd'], + ['application/vnd.curl.car', 'car'], + ['application/vnd.curl.pcurl', 'pcurl'], + ['application/vnd.data-vision.rdz', 'rdz'], + ['application/vnd.denovo.fcselayout-link', 'fe_launch'], + ['application/vnd.dna', 'dna'], + ['application/vnd.dolby.mlp', 'mlp'], + ['application/vnd.dpgraph', 'dpg'], + ['application/vnd.dreamfactory', 'dfac'], + ['application/vnd.dvb.ait', 'ait'], + ['application/vnd.dvb.service', 'svc'], + ['application/vnd.dynageo', 'geo'], + ['application/vnd.ecowin.chart', 'mag'], + ['application/vnd.enliven', 'nml'], + ['application/vnd.epson.esf', 'esf'], + ['application/vnd.epson.msf', 'msf'], + ['application/vnd.epson.quickanime', 'qam'], + ['application/vnd.epson.salt', 'slt'], + ['application/vnd.epson.ssf', 'ssf'], + ['application/vnd.eszigno3+xml', 'es3'], + ['application/vnd.ezpix-album', 'ez2'], + ['application/vnd.ezpix-package', 'ez3'], + ['application/vnd.fdf', 'fdf'], + ['application/vnd.fdsn.seed', 'seed'], + ['application/vnd.flographit', 'gph'], + ['application/vnd.fluxtime.clip', 'ftc'], + ['application/vnd.framemaker', 'fm'], + ['application/vnd.frogans.fnc', 'fnc'], + ['application/vnd.frogans.ltf', 'ltf'], + ['application/vnd.fsc.weblaunch', 'fsc'], + ['application/vnd.fujitsu.oasys', 'oas'], + ['application/vnd.fujitsu.oasys2', 'oa2'], + ['application/vnd.fujitsu.oasys3', 'oa3'], + ['application/vnd.fujitsu.oasysgp', 'fg5'], + ['application/vnd.fujitsu.oasysprs', 'bh2'], + ['application/vnd.fujixerox.ddd', 'ddd'], + ['application/vnd.fujixerox.docuworks', 'xdw'], + ['application/vnd.fujixerox.docuworks.binder', 'xbd'], + ['application/vnd.fuzzysheet', 'fzs'], + ['application/vnd.genomatix.tuxedo', 'txd'], + ['application/vnd.geogebra.file', 'ggb'], + ['application/vnd.geogebra.tool', 'ggt'], + ['application/vnd.geometry-explorer', 'gex'], + ['application/vnd.geonext', 'gxt'], + ['application/vnd.geoplan', 'g2w'], + ['application/vnd.geospace', 'g3w'], + ['application/vnd.gmx', 'gmx'], + ['application/vnd.google-earth.kml+xml', 'kml'], + ['application/vnd.google-earth.kmz', 'kmz'], + ['application/vnd.grafeq', 'gqf'], + ['application/vnd.groove-account', 'gac'], + ['application/vnd.groove-help', 'ghf'], + ['application/vnd.groove-identity-message', 'gim'], + ['application/vnd.groove-injector', 'grv'], + ['application/vnd.groove-tool-message', 'gtm'], + ['application/vnd.groove-tool-template', 'tpl'], + ['application/vnd.groove-vcard', 'vcg'], + ['application/vnd.hal+xml', 'hal'], + ['application/vnd.handheld-entertainment+xml', 'zmm'], + ['application/vnd.hbci', 'hbci'], + ['application/vnd.hhe.lesson-player', 'les'], + ['application/vnd.hp-hpgl', ['hgl', 'hpg', 'hpgl']], + ['application/vnd.hp-hpid', 'hpid'], + ['application/vnd.hp-hps', 'hps'], + ['application/vnd.hp-jlyt', 'jlt'], + ['application/vnd.hp-pcl', 'pcl'], + ['application/vnd.hp-pclxl', 'pclxl'], + ['application/vnd.hydrostatix.sof-data', 'sfd-hdstx'], + ['application/vnd.hzn-3d-crossword', 'x3d'], + ['application/vnd.ibm.minipay', 'mpy'], + ['application/vnd.ibm.modcap', 'afp'], + ['application/vnd.ibm.rights-management', 'irm'], + ['application/vnd.ibm.secure-container', 'sc'], + ['application/vnd.iccprofile', 'icc'], + ['application/vnd.igloader', 'igl'], + ['application/vnd.immervision-ivp', 'ivp'], + ['application/vnd.immervision-ivu', 'ivu'], + ['application/vnd.insors.igm', 'igm'], + ['application/vnd.intercon.formnet', 'xpw'], + ['application/vnd.intergeo', 'i2g'], + ['application/vnd.intu.qbo', 'qbo'], + ['application/vnd.intu.qfx', 'qfx'], + ['application/vnd.ipunplugged.rcprofile', 'rcprofile'], + ['application/vnd.irepository.package+xml', 'irp'], + ['application/vnd.is-xpr', 'xpr'], + ['application/vnd.isac.fcs', 'fcs'], + ['application/vnd.jam', 'jam'], + ['application/vnd.jcp.javame.midlet-rms', 'rms'], + ['application/vnd.jisp', 'jisp'], + ['application/vnd.joost.joda-archive', 'joda'], + ['application/vnd.kahootz', 'ktz'], + ['application/vnd.kde.karbon', 'karbon'], + ['application/vnd.kde.kchart', 'chrt'], + ['application/vnd.kde.kformula', 'kfo'], + ['application/vnd.kde.kivio', 'flw'], + ['application/vnd.kde.kontour', 'kon'], + ['application/vnd.kde.kpresenter', 'kpr'], + ['application/vnd.kde.kspread', 'ksp'], + ['application/vnd.kde.kword', 'kwd'], + ['application/vnd.kenameaapp', 'htke'], + ['application/vnd.kidspiration', 'kia'], + ['application/vnd.kinar', 'kne'], + ['application/vnd.koan', 'skp'], + ['application/vnd.kodak-descriptor', 'sse'], + ['application/vnd.las.las+xml', 'lasxml'], + ['application/vnd.llamagraphics.life-balance.desktop', 'lbd'], + ['application/vnd.llamagraphics.life-balance.exchange+xml', 'lbe'], + ['application/vnd.lotus-1-2-3', '123'], + ['application/vnd.lotus-approach', 'apr'], + ['application/vnd.lotus-freelance', 'pre'], + ['application/vnd.lotus-notes', 'nsf'], + ['application/vnd.lotus-organizer', 'org'], + ['application/vnd.lotus-screencam', 'scm'], + ['application/vnd.lotus-wordpro', 'lwp'], + ['application/vnd.macports.portpkg', 'portpkg'], + ['application/vnd.mcd', 'mcd'], + ['application/vnd.medcalcdata', 'mc1'], + ['application/vnd.mediastation.cdkey', 'cdkey'], + ['application/vnd.mfer', 'mwf'], + ['application/vnd.mfmp', 'mfm'], + ['application/vnd.micrografx.flo', 'flo'], + ['application/vnd.micrografx.igx', 'igx'], + ['application/vnd.mif', 'mif'], + ['application/vnd.mobius.daf', 'daf'], + ['application/vnd.mobius.dis', 'dis'], + ['application/vnd.mobius.mbk', 'mbk'], + ['application/vnd.mobius.mqy', 'mqy'], + ['application/vnd.mobius.msl', 'msl'], + ['application/vnd.mobius.plc', 'plc'], + ['application/vnd.mobius.txf', 'txf'], + ['application/vnd.mophun.application', 'mpn'], + ['application/vnd.mophun.certificate', 'mpc'], + ['application/vnd.mozilla.xul+xml', 'xul'], + ['application/vnd.ms-artgalry', 'cil'], + ['application/vnd.ms-cab-compressed', 'cab'], + ['application/vnd.ms-excel', ['xls', 'xla', 'xlc', 'xlm', 'xlt', 'xlw', 'xlb', 'xll']], + ['application/vnd.ms-excel.addin.macroenabled.12', 'xlam'], + ['application/vnd.ms-excel.sheet.binary.macroenabled.12', 'xlsb'], + ['application/vnd.ms-excel.sheet.macroenabled.12', 'xlsm'], + ['application/vnd.ms-excel.template.macroenabled.12', 'xltm'], + ['application/vnd.ms-fontobject', 'eot'], + ['application/vnd.ms-htmlhelp', 'chm'], + ['application/vnd.ms-ims', 'ims'], + ['application/vnd.ms-lrm', 'lrm'], + ['application/vnd.ms-officetheme', 'thmx'], + ['application/vnd.ms-outlook', 'msg'], + ['application/vnd.ms-pki.certstore', 'sst'], + ['application/vnd.ms-pki.pko', 'pko'], + ['application/vnd.ms-pki.seccat', 'cat'], + ['application/vnd.ms-pki.stl', 'stl'], + ['application/vnd.ms-pkicertstore', 'sst'], + ['application/vnd.ms-pkiseccat', 'cat'], + ['application/vnd.ms-pkistl', 'stl'], + ['application/vnd.ms-powerpoint', ['ppt', 'pot', 'pps', 'ppa', 'pwz']], + ['application/vnd.ms-powerpoint.addin.macroenabled.12', 'ppam'], + ['application/vnd.ms-powerpoint.presentation.macroenabled.12', 'pptm'], + ['application/vnd.ms-powerpoint.slide.macroenabled.12', 'sldm'], + ['application/vnd.ms-powerpoint.slideshow.macroenabled.12', 'ppsm'], + ['application/vnd.ms-powerpoint.template.macroenabled.12', 'potm'], + ['application/vnd.ms-project', 'mpp'], + ['application/vnd.ms-word.document.macroenabled.12', 'docm'], + ['application/vnd.ms-word.template.macroenabled.12', 'dotm'], + ['application/vnd.ms-works', ['wks', 'wcm', 'wdb', 'wps']], + ['application/vnd.ms-wpl', 'wpl'], + ['application/vnd.ms-xpsdocument', 'xps'], + ['application/vnd.mseq', 'mseq'], + ['application/vnd.musician', 'mus'], + ['application/vnd.muvee.style', 'msty'], + ['application/vnd.neurolanguage.nlu', 'nlu'], + ['application/vnd.noblenet-directory', 'nnd'], + ['application/vnd.noblenet-sealer', 'nns'], + ['application/vnd.noblenet-web', 'nnw'], + ['application/vnd.nokia.configuration-message', 'ncm'], + ['application/vnd.nokia.n-gage.data', 'ngdat'], + ['application/vnd.nokia.n-gage.symbian.install', 'n-gage'], + ['application/vnd.nokia.radio-preset', 'rpst'], + ['application/vnd.nokia.radio-presets', 'rpss'], + ['application/vnd.nokia.ringing-tone', 'rng'], + ['application/vnd.novadigm.edm', 'edm'], + ['application/vnd.novadigm.edx', 'edx'], + ['application/vnd.novadigm.ext', 'ext'], + ['application/vnd.oasis.opendocument.chart', 'odc'], + ['application/vnd.oasis.opendocument.chart-template', 'otc'], + ['application/vnd.oasis.opendocument.database', 'odb'], + ['application/vnd.oasis.opendocument.formula', 'odf'], + ['application/vnd.oasis.opendocument.formula-template', 'odft'], + ['application/vnd.oasis.opendocument.graphics', 'odg'], + ['application/vnd.oasis.opendocument.graphics-template', 'otg'], + ['application/vnd.oasis.opendocument.image', 'odi'], + ['application/vnd.oasis.opendocument.image-template', 'oti'], + ['application/vnd.oasis.opendocument.presentation', 'odp'], + ['application/vnd.oasis.opendocument.presentation-template', 'otp'], + ['application/vnd.oasis.opendocument.spreadsheet', 'ods'], + ['application/vnd.oasis.opendocument.spreadsheet-template', 'ots'], + ['application/vnd.oasis.opendocument.text', 'odt'], + ['application/vnd.oasis.opendocument.text-master', 'odm'], + ['application/vnd.oasis.opendocument.text-template', 'ott'], + ['application/vnd.oasis.opendocument.text-web', 'oth'], + ['application/vnd.olpc-sugar', 'xo'], + ['application/vnd.oma.dd2+xml', 'dd2'], + ['application/vnd.openofficeorg.extension', 'oxt'], + ['application/vnd.openxmlformats-officedocument.presentationml.presentation', 'pptx'], + ['application/vnd.openxmlformats-officedocument.presentationml.slide', 'sldx'], + ['application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'ppsx'], + ['application/vnd.openxmlformats-officedocument.presentationml.template', 'potx'], + ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlsx'], + ['application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'xltx'], + ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'docx'], + ['application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'dotx'], + ['application/vnd.osgeo.mapguide.package', 'mgp'], + ['application/vnd.osgi.dp', 'dp'], + ['application/vnd.palm', 'pdb'], + ['application/vnd.pawaafile', 'paw'], + ['application/vnd.pg.format', 'str'], + ['application/vnd.pg.osasli', 'ei6'], + ['application/vnd.picsel', 'efif'], + ['application/vnd.pmi.widget', 'wg'], + ['application/vnd.pocketlearn', 'plf'], + ['application/vnd.powerbuilder6', 'pbd'], + ['application/vnd.previewsystems.box', 'box'], + ['application/vnd.proteus.magazine', 'mgz'], + ['application/vnd.publishare-delta-tree', 'qps'], + ['application/vnd.pvi.ptid1', 'ptid'], + ['application/vnd.quark.quarkxpress', 'qxd'], + ['application/vnd.realvnc.bed', 'bed'], + ['application/vnd.recordare.musicxml', 'mxl'], + ['application/vnd.recordare.musicxml+xml', 'musicxml'], + ['application/vnd.rig.cryptonote', 'cryptonote'], + ['application/vnd.rim.cod', 'cod'], + ['application/vnd.rn-realmedia', 'rm'], + ['application/vnd.rn-realplayer', 'rnx'], + ['application/vnd.route66.link66+xml', 'link66'], + ['application/vnd.sailingtracker.track', 'st'], + ['application/vnd.seemail', 'see'], + ['application/vnd.sema', 'sema'], + ['application/vnd.semd', 'semd'], + ['application/vnd.semf', 'semf'], + ['application/vnd.shana.informed.formdata', 'ifm'], + ['application/vnd.shana.informed.formtemplate', 'itp'], + ['application/vnd.shana.informed.interchange', 'iif'], + ['application/vnd.shana.informed.package', 'ipk'], + ['application/vnd.simtech-mindmapper', 'twd'], + ['application/vnd.smaf', 'mmf'], + ['application/vnd.smart.teacher', 'teacher'], + ['application/vnd.solent.sdkm+xml', 'sdkm'], + ['application/vnd.spotfire.dxp', 'dxp'], + ['application/vnd.spotfire.sfs', 'sfs'], + ['application/vnd.stardivision.calc', 'sdc'], + ['application/vnd.stardivision.draw', 'sda'], + ['application/vnd.stardivision.impress', 'sdd'], + ['application/vnd.stardivision.math', 'smf'], + ['application/vnd.stardivision.writer', 'sdw'], + ['application/vnd.stardivision.writer-global', 'sgl'], + ['application/vnd.stepmania.stepchart', 'sm'], + ['application/vnd.sun.xml.calc', 'sxc'], + ['application/vnd.sun.xml.calc.template', 'stc'], + ['application/vnd.sun.xml.draw', 'sxd'], + ['application/vnd.sun.xml.draw.template', 'std'], + ['application/vnd.sun.xml.impress', 'sxi'], + ['application/vnd.sun.xml.impress.template', 'sti'], + ['application/vnd.sun.xml.math', 'sxm'], + ['application/vnd.sun.xml.writer', 'sxw'], + ['application/vnd.sun.xml.writer.global', 'sxg'], + ['application/vnd.sun.xml.writer.template', 'stw'], + ['application/vnd.sus-calendar', 'sus'], + ['application/vnd.svd', 'svd'], + ['application/vnd.symbian.install', 'sis'], + ['application/vnd.syncml+xml', 'xsm'], + ['application/vnd.syncml.dm+wbxml', 'bdm'], + ['application/vnd.syncml.dm+xml', 'xdm'], + ['application/vnd.tao.intent-module-archive', 'tao'], + ['application/vnd.tmobile-livetv', 'tmo'], + ['application/vnd.trid.tpt', 'tpt'], + ['application/vnd.triscape.mxs', 'mxs'], + ['application/vnd.trueapp', 'tra'], + ['application/vnd.ufdl', 'ufd'], + ['application/vnd.uiq.theme', 'utz'], + ['application/vnd.umajin', 'umj'], + ['application/vnd.unity', 'unityweb'], + ['application/vnd.uoml+xml', 'uoml'], + ['application/vnd.vcx', 'vcx'], + ['application/vnd.visio', 'vsd'], + ['application/vnd.visionary', 'vis'], + ['application/vnd.vsf', 'vsf'], + ['application/vnd.wap.wbxml', 'wbxml'], + ['application/vnd.wap.wmlc', 'wmlc'], + ['application/vnd.wap.wmlscriptc', 'wmlsc'], + ['application/vnd.webturbo', 'wtb'], + ['application/vnd.wolfram.player', 'nbp'], + ['application/vnd.wordperfect', 'wpd'], + ['application/vnd.wqd', 'wqd'], + ['application/vnd.wt.stf', 'stf'], + ['application/vnd.xara', ['web', 'xar']], + ['application/vnd.xfdl', 'xfdl'], + ['application/vnd.yamaha.hv-dic', 'hvd'], + ['application/vnd.yamaha.hv-script', 'hvs'], + ['application/vnd.yamaha.hv-voice', 'hvp'], + ['application/vnd.yamaha.openscoreformat', 'osf'], + ['application/vnd.yamaha.openscoreformat.osfpvg+xml', 'osfpvg'], + ['application/vnd.yamaha.smaf-audio', 'saf'], + ['application/vnd.yamaha.smaf-phrase', 'spf'], + ['application/vnd.yellowriver-custom-menu', 'cmp'], + ['application/vnd.zul', 'zir'], + ['application/vnd.zzazz.deck+xml', 'zaz'], + ['application/vocaltec-media-desc', 'vmd'], + ['application/vocaltec-media-file', 'vmf'], + ['application/voicexml+xml', 'vxml'], + ['application/widget', 'wgt'], + ['application/winhlp', 'hlp'], + ['application/wordperfect', ['wp', 'wp5', 'wp6', 'wpd']], + ['application/wordperfect6.0', ['w60', 'wp5']], + ['application/wordperfect6.1', 'w61'], + ['application/wsdl+xml', 'wsdl'], + ['application/wspolicy+xml', 'wspolicy'], + ['application/x-123', 'wk1'], + ['application/x-7z-compressed', '7z'], + ['application/x-abiword', 'abw'], + ['application/x-ace-compressed', 'ace'], + ['application/x-aim', 'aim'], + ['application/x-authorware-bin', 'aab'], + ['application/x-authorware-map', 'aam'], + ['application/x-authorware-seg', 'aas'], + ['application/x-bcpio', 'bcpio'], + ['application/x-binary', 'bin'], + ['application/x-binhex40', 'hqx'], + ['application/x-bittorrent', 'torrent'], + ['application/x-bsh', ['bsh', 'sh', 'shar']], + ['application/x-bytecode.elisp', 'elc'], + ['application/x-bytecode.python', 'pyc'], + ['application/x-bzip', 'bz'], + ['application/x-bzip2', ['boz', 'bz2']], + ['application/x-cdf', 'cdf'], + ['application/x-cdlink', 'vcd'], + ['application/x-chat', ['cha', 'chat']], + ['application/x-chess-pgn', 'pgn'], + ['application/x-cmu-raster', 'ras'], + ['application/x-cocoa', 'cco'], + ['application/x-compactpro', 'cpt'], + ['application/x-compress', 'z'], + ['application/x-compressed', ['tgz', 'gz', 'z', 'zip']], + ['application/x-conference', 'nsc'], + ['application/x-cpio', 'cpio'], + ['application/x-cpt', 'cpt'], + ['application/x-csh', 'csh'], + ['application/x-debian-package', 'deb'], + ['application/x-deepv', 'deepv'], + ['application/x-director', ['dir', 'dcr', 'dxr']], + ['application/x-doom', 'wad'], + ['application/x-dtbncx+xml', 'ncx'], + ['application/x-dtbook+xml', 'dtb'], + ['application/x-dtbresource+xml', 'res'], + ['application/x-dvi', 'dvi'], + ['application/x-elc', 'elc'], + ['application/x-envoy', ['env', 'evy']], + ['application/x-esrehber', 'es'], + ['application/x-excel', ['xls', 'xla', 'xlb', 'xlc', 'xld', 'xlk', 'xll', 'xlm', 'xlt', 'xlv', 'xlw']], + ['application/x-font-bdf', 'bdf'], + ['application/x-font-ghostscript', 'gsf'], + ['application/x-font-linux-psf', 'psf'], + ['application/x-font-otf', 'otf'], + ['application/x-font-pcf', 'pcf'], + ['application/x-font-snf', 'snf'], + ['application/x-font-ttf', 'ttf'], + ['application/x-font-type1', 'pfa'], + ['application/x-font-woff', 'woff'], + ['application/x-frame', 'mif'], + ['application/x-freelance', 'pre'], + ['application/x-futuresplash', 'spl'], + ['application/x-gnumeric', 'gnumeric'], + ['application/x-gsp', 'gsp'], + ['application/x-gss', 'gss'], + ['application/x-gtar', 'gtar'], + ['application/x-gzip', ['gz', 'gzip']], + ['application/x-hdf', 'hdf'], + ['application/x-helpfile', ['help', 'hlp']], + ['application/x-httpd-imap', 'imap'], + ['application/x-ima', 'ima'], + ['application/x-internet-signup', ['ins', 'isp']], + ['application/x-internett-signup', 'ins'], + ['application/x-inventor', 'iv'], + ['application/x-ip2', 'ip'], + ['application/x-iphone', 'iii'], + ['application/x-java-class', 'class'], + ['application/x-java-commerce', 'jcm'], + ['application/x-java-jnlp-file', 'jnlp'], + ['application/x-javascript', 'js'], + ['application/x-koan', ['skd', 'skm', 'skp', 'skt']], + ['application/x-ksh', 'ksh'], + ['application/x-latex', ['latex', 'ltx']], + ['application/x-lha', 'lha'], + ['application/x-lisp', 'lsp'], + ['application/x-livescreen', 'ivy'], + ['application/x-lotus', 'wq1'], + ['application/x-lotusscreencam', 'scm'], + ['application/x-lzh', 'lzh'], + ['application/x-lzx', 'lzx'], + ['application/x-mac-binhex40', 'hqx'], + ['application/x-macbinary', 'bin'], + ['application/x-magic-cap-package-1.0', 'mc$'], + ['application/x-mathcad', 'mcd'], + ['application/x-meme', 'mm'], + ['application/x-midi', ['mid', 'midi']], + ['application/x-mif', 'mif'], + ['application/x-mix-transfer', 'nix'], + ['application/x-mobipocket-ebook', 'prc'], + ['application/x-mplayer2', 'asx'], + ['application/x-ms-application', 'application'], + ['application/x-ms-wmd', 'wmd'], + ['application/x-ms-wmz', 'wmz'], + ['application/x-ms-xbap', 'xbap'], + ['application/x-msaccess', 'mdb'], + ['application/x-msbinder', 'obd'], + ['application/x-mscardfile', 'crd'], + ['application/x-msclip', 'clp'], + ['application/x-msdownload', ['exe', 'dll']], + ['application/x-msexcel', ['xls', 'xla', 'xlw']], + ['application/x-msmediaview', ['mvb', 'm13', 'm14']], + ['application/x-msmetafile', 'wmf'], + ['application/x-msmoney', 'mny'], + ['application/x-mspowerpoint', 'ppt'], + ['application/x-mspublisher', 'pub'], + ['application/x-msschedule', 'scd'], + ['application/x-msterminal', 'trm'], + ['application/x-mswrite', 'wri'], + ['application/x-navi-animation', 'ani'], + ['application/x-navidoc', 'nvd'], + ['application/x-navimap', 'map'], + ['application/x-navistyle', 'stl'], + ['application/x-netcdf', ['cdf', 'nc']], + ['application/x-newton-compatible-pkg', 'pkg'], + ['application/x-nokia-9000-communicator-add-on-software', 'aos'], + ['application/x-omc', 'omc'], + ['application/x-omcdatamaker', 'omcd'], + ['application/x-omcregerator', 'omcr'], + ['application/x-pagemaker', ['pm4', 'pm5']], + ['application/x-pcl', 'pcl'], + ['application/x-perfmon', ['pma', 'pmc', 'pml', 'pmr', 'pmw']], + ['application/x-pixclscript', 'plx'], + ['application/x-pkcs10', 'p10'], + ['application/x-pkcs12', ['p12', 'pfx']], + ['application/x-pkcs7-certificates', ['p7b', 'spc']], + ['application/x-pkcs7-certreqresp', 'p7r'], + ['application/x-pkcs7-mime', ['p7m', 'p7c']], + ['application/x-pkcs7-signature', ['p7s', 'p7a']], + ['application/x-pointplus', 'css'], + ['application/x-portable-anymap', 'pnm'], + ['application/x-project', ['mpc', 'mpt', 'mpv', 'mpx']], + ['application/x-qpro', 'wb1'], + ['application/x-rar-compressed', 'rar'], + ['application/x-rtf', 'rtf'], + ['application/x-sdp', 'sdp'], + ['application/x-sea', 'sea'], + ['application/x-seelogo', 'sl'], + ['application/x-sh', 'sh'], + ['application/x-shar', ['shar', 'sh']], + ['application/x-shockwave-flash', 'swf'], + ['application/x-silverlight-app', 'xap'], + ['application/x-sit', 'sit'], + ['application/x-sprite', ['spr', 'sprite']], + ['application/x-stuffit', 'sit'], + ['application/x-stuffitx', 'sitx'], + ['application/x-sv4cpio', 'sv4cpio'], + ['application/x-sv4crc', 'sv4crc'], + ['application/x-tar', 'tar'], + ['application/x-tbook', ['sbk', 'tbk']], + ['application/x-tcl', 'tcl'], + ['application/x-tex', 'tex'], + ['application/x-tex-tfm', 'tfm'], + ['application/x-texinfo', ['texi', 'texinfo']], + ['application/x-troff', ['roff', 't', 'tr']], + ['application/x-troff-man', 'man'], + ['application/x-troff-me', 'me'], + ['application/x-troff-ms', 'ms'], + ['application/x-troff-msvideo', 'avi'], + ['application/x-ustar', 'ustar'], + ['application/x-visio', ['vsd', 'vst', 'vsw']], + ['application/x-vnd.audioexplosion.mzz', 'mzz'], + ['application/x-vnd.ls-xpix', 'xpix'], + ['application/x-vrml', 'vrml'], + ['application/x-wais-source', ['src', 'wsrc']], + ['application/x-winhelp', 'hlp'], + ['application/x-wintalk', 'wtk'], + ['application/x-world', ['wrl', 'svr']], + ['application/x-wpwin', 'wpd'], + ['application/x-wri', 'wri'], + ['application/x-x509-ca-cert', ['cer', 'crt', 'der']], + ['application/x-x509-user-cert', 'crt'], + ['application/x-xfig', 'fig'], + ['application/x-xpinstall', 'xpi'], + ['application/x-zip-compressed', 'zip'], + ['application/xcap-diff+xml', 'xdf'], + ['application/xenc+xml', 'xenc'], + ['application/xhtml+xml', 'xhtml'], + ['application/xml', 'xml'], + ['application/xml-dtd', 'dtd'], + ['application/xop+xml', 'xop'], + ['application/xslt+xml', 'xslt'], + ['application/xspf+xml', 'xspf'], + ['application/xv+xml', 'mxml'], + ['application/yang', 'yang'], + ['application/yin+xml', 'yin'], + ['application/ynd.ms-pkipko', 'pko'], + ['application/zip', 'zip'], + ['audio/adpcm', 'adp'], + ['audio/aiff', ['aiff', 'aif', 'aifc']], + ['audio/basic', ['snd', 'au']], + ['audio/it', 'it'], + ['audio/make', ['funk', 'my', 'pfunk']], + ['audio/make.my.funk', 'pfunk'], + ['audio/mid', ['mid', 'rmi']], + ['audio/midi', ['midi', 'kar', 'mid']], + ['audio/mod', 'mod'], + ['audio/mp4', 'mp4a'], + ['audio/mpeg', ['mpga', 'mp3', 'm2a', 'mp2', 'mpa', 'mpg']], + ['audio/mpeg3', 'mp3'], + ['audio/nspaudio', ['la', 'lma']], + ['audio/ogg', 'oga'], + ['audio/s3m', 's3m'], + ['audio/tsp-audio', 'tsi'], + ['audio/tsplayer', 'tsp'], + ['audio/vnd.dece.audio', 'uva'], + ['audio/vnd.digital-winds', 'eol'], + ['audio/vnd.dra', 'dra'], + ['audio/vnd.dts', 'dts'], + ['audio/vnd.dts.hd', 'dtshd'], + ['audio/vnd.lucent.voice', 'lvp'], + ['audio/vnd.ms-playready.media.pya', 'pya'], + ['audio/vnd.nuera.ecelp4800', 'ecelp4800'], + ['audio/vnd.nuera.ecelp7470', 'ecelp7470'], + ['audio/vnd.nuera.ecelp9600', 'ecelp9600'], + ['audio/vnd.qcelp', 'qcp'], + ['audio/vnd.rip', 'rip'], + ['audio/voc', 'voc'], + ['audio/voxware', 'vox'], + ['audio/wav', 'wav'], + ['audio/webm', 'weba'], + ['audio/x-aac', 'aac'], + ['audio/x-adpcm', 'snd'], + ['audio/x-aiff', ['aiff', 'aif', 'aifc']], + ['audio/x-au', 'au'], + ['audio/x-gsm', ['gsd', 'gsm']], + ['audio/x-jam', 'jam'], + ['audio/x-liveaudio', 'lam'], + ['audio/x-mid', ['mid', 'midi']], + ['audio/x-midi', ['midi', 'mid']], + ['audio/x-mod', 'mod'], + ['audio/x-mpeg', 'mp2'], + ['audio/x-mpeg-3', 'mp3'], + ['audio/x-mpegurl', 'm3u'], + ['audio/x-mpequrl', 'm3u'], + ['audio/x-ms-wax', 'wax'], + ['audio/x-ms-wma', 'wma'], + ['audio/x-nspaudio', ['la', 'lma']], + ['audio/x-pn-realaudio', ['ra', 'ram', 'rm', 'rmm', 'rmp']], + ['audio/x-pn-realaudio-plugin', ['ra', 'rmp', 'rpm']], + ['audio/x-psid', 'sid'], + ['audio/x-realaudio', 'ra'], + ['audio/x-twinvq', 'vqf'], + ['audio/x-twinvq-plugin', ['vqe', 'vql']], + ['audio/x-vnd.audioexplosion.mjuicemediafile', 'mjf'], + ['audio/x-voc', 'voc'], + ['audio/x-wav', 'wav'], + ['audio/xm', 'xm'], + ['chemical/x-cdx', 'cdx'], + ['chemical/x-cif', 'cif'], + ['chemical/x-cmdf', 'cmdf'], + ['chemical/x-cml', 'cml'], + ['chemical/x-csml', 'csml'], + ['chemical/x-pdb', ['pdb', 'xyz']], + ['chemical/x-xyz', 'xyz'], + ['drawing/x-dwf', 'dwf'], + ['i-world/i-vrml', 'ivr'], + ['image/bmp', ['bmp', 'bm']], + ['image/cgm', 'cgm'], + ['image/cis-cod', 'cod'], + ['image/cmu-raster', ['ras', 'rast']], + ['image/fif', 'fif'], + ['image/florian', ['flo', 'turbot']], + ['image/g3fax', 'g3'], + ['image/gif', 'gif'], + ['image/ief', ['ief', 'iefs']], + ['image/jpeg', ['jpeg', 'jpe', 'jpg', 'jfif', 'jfif-tbnl']], + ['image/jutvision', 'jut'], + ['image/ktx', 'ktx'], + ['image/naplps', ['nap', 'naplps']], + ['image/pict', ['pic', 'pict']], + ['image/pipeg', 'jfif'], + ['image/pjpeg', ['jfif', 'jpe', 'jpeg', 'jpg']], + ['image/png', ['png', 'x-png']], + ['image/prs.btif', 'btif'], + ['image/svg+xml', 'svg'], + ['image/tiff', ['tif', 'tiff']], + ['image/vasa', 'mcf'], + ['image/vnd.adobe.photoshop', 'psd'], + ['image/vnd.dece.graphic', 'uvi'], + ['image/vnd.djvu', 'djvu'], + ['image/vnd.dvb.subtitle', 'sub'], + ['image/vnd.dwg', ['dwg', 'dxf', 'svf']], + ['image/vnd.dxf', 'dxf'], + ['image/vnd.fastbidsheet', 'fbs'], + ['image/vnd.fpx', 'fpx'], + ['image/vnd.fst', 'fst'], + ['image/vnd.fujixerox.edmics-mmr', 'mmr'], + ['image/vnd.fujixerox.edmics-rlc', 'rlc'], + ['image/vnd.ms-modi', 'mdi'], + ['image/vnd.net-fpx', ['fpx', 'npx']], + ['image/vnd.rn-realflash', 'rf'], + ['image/vnd.rn-realpix', 'rp'], + ['image/vnd.wap.wbmp', 'wbmp'], + ['image/vnd.xiff', 'xif'], + ['image/webp', 'webp'], + ['image/x-cmu-raster', 'ras'], + ['image/x-cmx', 'cmx'], + ['image/x-dwg', ['dwg', 'dxf', 'svf']], + ['image/x-freehand', 'fh'], + ['image/x-icon', 'ico'], + ['image/x-jg', 'art'], + ['image/x-jps', 'jps'], + ['image/x-niff', ['niff', 'nif']], + ['image/x-pcx', 'pcx'], + ['image/x-pict', ['pct', 'pic']], + ['image/x-portable-anymap', 'pnm'], + ['image/x-portable-bitmap', 'pbm'], + ['image/x-portable-graymap', 'pgm'], + ['image/x-portable-greymap', 'pgm'], + ['image/x-portable-pixmap', 'ppm'], + ['image/x-quicktime', ['qif', 'qti', 'qtif']], + ['image/x-rgb', 'rgb'], + ['image/x-tiff', ['tif', 'tiff']], + ['image/x-windows-bmp', 'bmp'], + ['image/x-xbitmap', 'xbm'], + ['image/x-xbm', 'xbm'], + ['image/x-xpixmap', ['xpm', 'pm']], + ['image/x-xwd', 'xwd'], + ['image/x-xwindowdump', 'xwd'], + ['image/xbm', 'xbm'], + ['image/xpm', 'xpm'], + ['message/rfc822', ['eml', 'mht', 'mhtml', 'nws', 'mime']], + ['model/iges', ['iges', 'igs']], + ['model/mesh', 'msh'], + ['model/vnd.collada+xml', 'dae'], + ['model/vnd.dwf', 'dwf'], + ['model/vnd.gdl', 'gdl'], + ['model/vnd.gtw', 'gtw'], + ['model/vnd.mts', 'mts'], + ['model/vnd.vtu', 'vtu'], + ['model/vrml', ['vrml', 'wrl', 'wrz']], + ['model/x-pov', 'pov'], + ['multipart/x-gzip', 'gzip'], + ['multipart/x-ustar', 'ustar'], + ['multipart/x-zip', 'zip'], + ['music/crescendo', ['mid', 'midi']], + ['music/x-karaoke', 'kar'], + ['paleovu/x-pv', 'pvu'], + ['text/asp', 'asp'], + ['text/calendar', 'ics'], + ['text/css', 'css'], + ['text/csv', 'csv'], + ['text/ecmascript', 'js'], + ['text/h323', '323'], + ['text/html', ['html', 'htm', 'stm', 'acgi', 'htmls', 'htx', 'shtml']], + ['text/iuls', 'uls'], + ['text/javascript', 'js'], + ['text/mcf', 'mcf'], + ['text/n3', 'n3'], + ['text/pascal', 'pas'], + [ + 'text/plain', + [ + 'txt', + 'bas', + 'c', + 'h', + 'c++', + 'cc', + 'com', + 'conf', + 'cxx', + 'def', + 'f', + 'f90', + 'for', + 'g', + 'hh', + 'idc', + 'jav', + 'java', + 'list', + 'log', + 'lst', + 'm', + 'mar', + 'pl', + 'sdml', + 'text' + ] + ], + ['text/plain-bas', 'par'], + ['text/prs.lines.tag', 'dsc'], + ['text/richtext', ['rtx', 'rt', 'rtf']], + ['text/scriplet', 'wsc'], + ['text/scriptlet', 'sct'], + ['text/sgml', ['sgm', 'sgml']], + ['text/tab-separated-values', 'tsv'], + ['text/troff', 't'], + ['text/turtle', 'ttl'], + ['text/uri-list', ['uni', 'unis', 'uri', 'uris']], + ['text/vnd.abc', 'abc'], + ['text/vnd.curl', 'curl'], + ['text/vnd.curl.dcurl', 'dcurl'], + ['text/vnd.curl.mcurl', 'mcurl'], + ['text/vnd.curl.scurl', 'scurl'], + ['text/vnd.fly', 'fly'], + ['text/vnd.fmi.flexstor', 'flx'], + ['text/vnd.graphviz', 'gv'], + ['text/vnd.in3d.3dml', '3dml'], + ['text/vnd.in3d.spot', 'spot'], + ['text/vnd.rn-realtext', 'rt'], + ['text/vnd.sun.j2me.app-descriptor', 'jad'], + ['text/vnd.wap.wml', 'wml'], + ['text/vnd.wap.wmlscript', 'wmls'], + ['text/webviewhtml', 'htt'], + ['text/x-asm', ['asm', 's']], + ['text/x-audiosoft-intra', 'aip'], + ['text/x-c', ['c', 'cc', 'cpp']], + ['text/x-component', 'htc'], + ['text/x-fortran', ['for', 'f', 'f77', 'f90']], + ['text/x-h', ['h', 'hh']], + ['text/x-java-source', ['java', 'jav']], + ['text/x-java-source,java', 'java'], + ['text/x-la-asf', 'lsx'], + ['text/x-m', 'm'], + ['text/x-pascal', 'p'], + ['text/x-script', 'hlb'], + ['text/x-script.csh', 'csh'], + ['text/x-script.elisp', 'el'], + ['text/x-script.guile', 'scm'], + ['text/x-script.ksh', 'ksh'], + ['text/x-script.lisp', 'lsp'], + ['text/x-script.perl', 'pl'], + ['text/x-script.perl-module', 'pm'], + ['text/x-script.phyton', 'py'], + ['text/x-script.rexx', 'rexx'], + ['text/x-script.scheme', 'scm'], + ['text/x-script.sh', 'sh'], + ['text/x-script.tcl', 'tcl'], + ['text/x-script.tcsh', 'tcsh'], + ['text/x-script.zsh', 'zsh'], + ['text/x-server-parsed-html', ['shtml', 'ssi']], + ['text/x-setext', 'etx'], + ['text/x-sgml', ['sgm', 'sgml']], + ['text/x-speech', ['spc', 'talk']], + ['text/x-uil', 'uil'], + ['text/x-uuencode', ['uu', 'uue']], + ['text/x-vcalendar', 'vcs'], + ['text/x-vcard', 'vcf'], + ['text/xml', 'xml'], + ['video/3gpp', '3gp'], + ['video/3gpp2', '3g2'], + ['video/animaflex', 'afl'], + ['video/avi', 'avi'], + ['video/avs-video', 'avs'], + ['video/dl', 'dl'], + ['video/fli', 'fli'], + ['video/gl', 'gl'], + ['video/h261', 'h261'], + ['video/h263', 'h263'], + ['video/h264', 'h264'], + ['video/jpeg', 'jpgv'], + ['video/jpm', 'jpm'], + ['video/mj2', 'mj2'], + ['video/mp4', 'mp4'], + ['video/mpeg', ['mpeg', 'mp2', 'mpa', 'mpe', 'mpg', 'mpv2', 'm1v', 'm2v', 'mp3']], + ['video/msvideo', 'avi'], + ['video/ogg', 'ogv'], + ['video/quicktime', ['mov', 'qt', 'moov']], + ['video/vdo', 'vdo'], + ['video/vivo', ['viv', 'vivo']], + ['video/vnd.dece.hd', 'uvh'], + ['video/vnd.dece.mobile', 'uvm'], + ['video/vnd.dece.pd', 'uvp'], + ['video/vnd.dece.sd', 'uvs'], + ['video/vnd.dece.video', 'uvv'], + ['video/vnd.fvt', 'fvt'], + ['video/vnd.mpegurl', 'mxu'], + ['video/vnd.ms-playready.media.pyv', 'pyv'], + ['video/vnd.rn-realvideo', 'rv'], + ['video/vnd.uvvu.mp4', 'uvu'], + ['video/vnd.vivo', ['viv', 'vivo']], + ['video/vosaic', 'vos'], + ['video/webm', 'webm'], + ['video/x-amt-demorun', 'xdr'], + ['video/x-amt-showrun', 'xsr'], + ['video/x-atomic3d-feature', 'fmf'], + ['video/x-dl', 'dl'], + ['video/x-dv', ['dif', 'dv']], + ['video/x-f4v', 'f4v'], + ['video/x-fli', 'fli'], + ['video/x-flv', 'flv'], + ['video/x-gl', 'gl'], + ['video/x-isvideo', 'isu'], + ['video/x-la-asf', ['lsf', 'lsx']], + ['video/x-m4v', 'm4v'], + ['video/x-motion-jpeg', 'mjpg'], + ['video/x-mpeg', ['mp3', 'mp2']], + ['video/x-mpeq2a', 'mp2'], + ['video/x-ms-asf', ['asf', 'asr', 'asx']], + ['video/x-ms-asf-plugin', 'asx'], + ['video/x-ms-wm', 'wm'], + ['video/x-ms-wmv', 'wmv'], + ['video/x-ms-wmx', 'wmx'], + ['video/x-ms-wvx', 'wvx'], + ['video/x-msvideo', 'avi'], + ['video/x-qtc', 'qtc'], + ['video/x-scm', 'scm'], + ['video/x-sgi-movie', ['movie', 'mv']], + ['windows/metafile', 'wmf'], + ['www/mime', 'mime'], + ['x-conference/x-cooltalk', 'ice'], + ['x-music/x-midi', ['mid', 'midi']], + ['x-world/x-3dmf', ['3dm', '3dmf', 'qd3', 'qd3d']], + ['x-world/x-svr', 'svr'], + ['x-world/x-vrml', ['flr', 'vrml', 'wrl', 'wrz', 'xaf', 'xof']], + ['x-world/x-vrt', 'vrt'], + ['xgl/drawing', 'xgz'], + ['xgl/movie', 'xmz'] +]); +const extensions = new Map([ + ['123', 'application/vnd.lotus-1-2-3'], + ['323', 'text/h323'], + ['*', 'application/octet-stream'], + ['3dm', 'x-world/x-3dmf'], + ['3dmf', 'x-world/x-3dmf'], + ['3dml', 'text/vnd.in3d.3dml'], + ['3g2', 'video/3gpp2'], + ['3gp', 'video/3gpp'], + ['7z', 'application/x-7z-compressed'], + ['a', 'application/octet-stream'], + ['aab', 'application/x-authorware-bin'], + ['aac', 'audio/x-aac'], + ['aam', 'application/x-authorware-map'], + ['aas', 'application/x-authorware-seg'], + ['abc', 'text/vnd.abc'], + ['abw', 'application/x-abiword'], + ['ac', 'application/pkix-attr-cert'], + ['acc', 'application/vnd.americandynamics.acc'], + ['ace', 'application/x-ace-compressed'], + ['acgi', 'text/html'], + ['acu', 'application/vnd.acucobol'], + ['acx', 'application/internet-property-stream'], + ['adp', 'audio/adpcm'], + ['aep', 'application/vnd.audiograph'], + ['afl', 'video/animaflex'], + ['afp', 'application/vnd.ibm.modcap'], + ['ahead', 'application/vnd.ahead.space'], + ['ai', 'application/postscript'], + ['aif', ['audio/aiff', 'audio/x-aiff']], + ['aifc', ['audio/aiff', 'audio/x-aiff']], + ['aiff', ['audio/aiff', 'audio/x-aiff']], + ['aim', 'application/x-aim'], + ['aip', 'text/x-audiosoft-intra'], + ['air', 'application/vnd.adobe.air-application-installer-package+zip'], + ['ait', 'application/vnd.dvb.ait'], + ['ami', 'application/vnd.amiga.ami'], + ['ani', 'application/x-navi-animation'], + ['aos', 'application/x-nokia-9000-communicator-add-on-software'], + ['apk', 'application/vnd.android.package-archive'], + ['application', 'application/x-ms-application'], + ['apr', 'application/vnd.lotus-approach'], + ['aps', 'application/mime'], + ['arc', 'application/octet-stream'], + ['arj', ['application/arj', 'application/octet-stream']], + ['art', 'image/x-jg'], + ['asf', 'video/x-ms-asf'], + ['asm', 'text/x-asm'], + ['aso', 'application/vnd.accpac.simply.aso'], + ['asp', 'text/asp'], + ['asr', 'video/x-ms-asf'], + ['asx', ['video/x-ms-asf', 'application/x-mplayer2', 'video/x-ms-asf-plugin']], + ['atc', 'application/vnd.acucorp'], + ['atomcat', 'application/atomcat+xml'], + ['atomsvc', 'application/atomsvc+xml'], + ['atx', 'application/vnd.antix.game-component'], + ['au', ['audio/basic', 'audio/x-au']], + ['avi', ['video/avi', 'video/msvideo', 'application/x-troff-msvideo', 'video/x-msvideo']], + ['avs', 'video/avs-video'], + ['aw', 'application/applixware'], + ['axs', 'application/olescript'], + ['azf', 'application/vnd.airzip.filesecure.azf'], + ['azs', 'application/vnd.airzip.filesecure.azs'], + ['azw', 'application/vnd.amazon.ebook'], + ['bas', 'text/plain'], + ['bcpio', 'application/x-bcpio'], + ['bdf', 'application/x-font-bdf'], + ['bdm', 'application/vnd.syncml.dm+wbxml'], + ['bed', 'application/vnd.realvnc.bed'], + ['bh2', 'application/vnd.fujitsu.oasysprs'], + [ + 'bin', + ['application/octet-stream', 'application/mac-binary', 'application/macbinary', 'application/x-macbinary', 'application/x-binary'] + ], + ['bm', 'image/bmp'], + ['bmi', 'application/vnd.bmi'], + ['bmp', ['image/bmp', 'image/x-windows-bmp']], + ['boo', 'application/book'], + ['book', 'application/book'], + ['box', 'application/vnd.previewsystems.box'], + ['boz', 'application/x-bzip2'], + ['bsh', 'application/x-bsh'], + ['btif', 'image/prs.btif'], + ['bz', 'application/x-bzip'], + ['bz2', 'application/x-bzip2'], + ['c', ['text/plain', 'text/x-c']], + ['c++', 'text/plain'], + ['c11amc', 'application/vnd.cluetrust.cartomobile-config'], + ['c11amz', 'application/vnd.cluetrust.cartomobile-config-pkg'], + ['c4g', 'application/vnd.clonk.c4group'], + ['cab', 'application/vnd.ms-cab-compressed'], + ['car', 'application/vnd.curl.car'], + ['cat', ['application/vnd.ms-pkiseccat', 'application/vnd.ms-pki.seccat']], + ['cc', ['text/plain', 'text/x-c']], + ['ccad', 'application/clariscad'], + ['cco', 'application/x-cocoa'], + ['ccxml', 'application/ccxml+xml,'], + ['cdbcmsg', 'application/vnd.contact.cmsg'], + ['cdf', ['application/cdf', 'application/x-cdf', 'application/x-netcdf']], + ['cdkey', 'application/vnd.mediastation.cdkey'], + ['cdmia', 'application/cdmi-capability'], + ['cdmic', 'application/cdmi-container'], + ['cdmid', 'application/cdmi-domain'], + ['cdmio', 'application/cdmi-object'], + ['cdmiq', 'application/cdmi-queue'], + ['cdx', 'chemical/x-cdx'], + ['cdxml', 'application/vnd.chemdraw+xml'], + ['cdy', 'application/vnd.cinderella'], + ['cer', ['application/pkix-cert', 'application/x-x509-ca-cert']], + ['cgm', 'image/cgm'], + ['cha', 'application/x-chat'], + ['chat', 'application/x-chat'], + ['chm', 'application/vnd.ms-htmlhelp'], + ['chrt', 'application/vnd.kde.kchart'], + ['cif', 'chemical/x-cif'], + ['cii', 'application/vnd.anser-web-certificate-issue-initiation'], + ['cil', 'application/vnd.ms-artgalry'], + ['cla', 'application/vnd.claymore'], + [ + 'class', + ['application/octet-stream', 'application/java', 'application/java-byte-code', 'application/java-vm', 'application/x-java-class'] + ], + ['clkk', 'application/vnd.crick.clicker.keyboard'], + ['clkp', 'application/vnd.crick.clicker.palette'], + ['clkt', 'application/vnd.crick.clicker.template'], + ['clkw', 'application/vnd.crick.clicker.wordbank'], + ['clkx', 'application/vnd.crick.clicker'], + ['clp', 'application/x-msclip'], + ['cmc', 'application/vnd.cosmocaller'], + ['cmdf', 'chemical/x-cmdf'], + ['cml', 'chemical/x-cml'], + ['cmp', 'application/vnd.yellowriver-custom-menu'], + ['cmx', 'image/x-cmx'], + ['cod', ['image/cis-cod', 'application/vnd.rim.cod']], + ['com', ['application/octet-stream', 'text/plain']], + ['conf', 'text/plain'], + ['cpio', 'application/x-cpio'], + ['cpp', 'text/x-c'], + ['cpt', ['application/mac-compactpro', 'application/x-compactpro', 'application/x-cpt']], + ['crd', 'application/x-mscardfile'], + ['crl', ['application/pkix-crl', 'application/pkcs-crl']], + ['crt', ['application/pkix-cert', 'application/x-x509-user-cert', 'application/x-x509-ca-cert']], + ['cryptonote', 'application/vnd.rig.cryptonote'], + ['csh', ['text/x-script.csh', 'application/x-csh']], + ['csml', 'chemical/x-csml'], + ['csp', 'application/vnd.commonspace'], + ['css', ['text/css', 'application/x-pointplus']], + ['csv', 'text/csv'], + ['cu', 'application/cu-seeme'], + ['curl', 'text/vnd.curl'], + ['cww', 'application/prs.cww'], + ['cxx', 'text/plain'], + ['dae', 'model/vnd.collada+xml'], + ['daf', 'application/vnd.mobius.daf'], + ['davmount', 'application/davmount+xml'], + ['dcr', 'application/x-director'], + ['dcurl', 'text/vnd.curl.dcurl'], + ['dd2', 'application/vnd.oma.dd2+xml'], + ['ddd', 'application/vnd.fujixerox.ddd'], + ['deb', 'application/x-debian-package'], + ['deepv', 'application/x-deepv'], + ['def', 'text/plain'], + ['der', 'application/x-x509-ca-cert'], + ['dfac', 'application/vnd.dreamfactory'], + ['dif', 'video/x-dv'], + ['dir', 'application/x-director'], + ['dis', 'application/vnd.mobius.dis'], + ['djvu', 'image/vnd.djvu'], + ['dl', ['video/dl', 'video/x-dl']], + ['dll', 'application/x-msdownload'], + ['dms', 'application/octet-stream'], + ['dna', 'application/vnd.dna'], + ['doc', 'application/msword'], + ['docm', 'application/vnd.ms-word.document.macroenabled.12'], + ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'], + ['dot', 'application/msword'], + ['dotm', 'application/vnd.ms-word.template.macroenabled.12'], + ['dotx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'], + ['dp', ['application/commonground', 'application/vnd.osgi.dp']], + ['dpg', 'application/vnd.dpgraph'], + ['dra', 'audio/vnd.dra'], + ['drw', 'application/drafting'], + ['dsc', 'text/prs.lines.tag'], + ['dssc', 'application/dssc+der'], + ['dtb', 'application/x-dtbook+xml'], + ['dtd', 'application/xml-dtd'], + ['dts', 'audio/vnd.dts'], + ['dtshd', 'audio/vnd.dts.hd'], + ['dump', 'application/octet-stream'], + ['dv', 'video/x-dv'], + ['dvi', 'application/x-dvi'], + ['dwf', ['model/vnd.dwf', 'drawing/x-dwf']], + ['dwg', ['application/acad', 'image/vnd.dwg', 'image/x-dwg']], + ['dxf', ['application/dxf', 'image/vnd.dwg', 'image/vnd.dxf', 'image/x-dwg']], + ['dxp', 'application/vnd.spotfire.dxp'], + ['dxr', 'application/x-director'], + ['ecelp4800', 'audio/vnd.nuera.ecelp4800'], + ['ecelp7470', 'audio/vnd.nuera.ecelp7470'], + ['ecelp9600', 'audio/vnd.nuera.ecelp9600'], + ['edm', 'application/vnd.novadigm.edm'], + ['edx', 'application/vnd.novadigm.edx'], + ['efif', 'application/vnd.picsel'], + ['ei6', 'application/vnd.pg.osasli'], + ['el', 'text/x-script.elisp'], + ['elc', ['application/x-elc', 'application/x-bytecode.elisp']], + ['eml', 'message/rfc822'], + ['emma', 'application/emma+xml'], + ['env', 'application/x-envoy'], + ['eol', 'audio/vnd.digital-winds'], + ['eot', 'application/vnd.ms-fontobject'], + ['eps', 'application/postscript'], + ['epub', 'application/epub+zip'], + ['es', ['application/ecmascript', 'application/x-esrehber']], + ['es3', 'application/vnd.eszigno3+xml'], + ['esf', 'application/vnd.epson.esf'], + ['etx', 'text/x-setext'], + ['evy', ['application/envoy', 'application/x-envoy']], + ['exe', ['application/octet-stream', 'application/x-msdownload']], + ['exi', 'application/exi'], + ['ext', 'application/vnd.novadigm.ext'], + ['ez2', 'application/vnd.ezpix-album'], + ['ez3', 'application/vnd.ezpix-package'], + ['f', ['text/plain', 'text/x-fortran']], + ['f4v', 'video/x-f4v'], + ['f77', 'text/x-fortran'], + ['f90', ['text/plain', 'text/x-fortran']], + ['fbs', 'image/vnd.fastbidsheet'], + ['fcs', 'application/vnd.isac.fcs'], + ['fdf', 'application/vnd.fdf'], + ['fe_launch', 'application/vnd.denovo.fcselayout-link'], + ['fg5', 'application/vnd.fujitsu.oasysgp'], + ['fh', 'image/x-freehand'], + ['fif', ['application/fractals', 'image/fif']], + ['fig', 'application/x-xfig'], + ['fli', ['video/fli', 'video/x-fli']], + ['flo', ['image/florian', 'application/vnd.micrografx.flo']], + ['flr', 'x-world/x-vrml'], + ['flv', 'video/x-flv'], + ['flw', 'application/vnd.kde.kivio'], + ['flx', 'text/vnd.fmi.flexstor'], + ['fly', 'text/vnd.fly'], + ['fm', 'application/vnd.framemaker'], + ['fmf', 'video/x-atomic3d-feature'], + ['fnc', 'application/vnd.frogans.fnc'], + ['for', ['text/plain', 'text/x-fortran']], + ['fpx', ['image/vnd.fpx', 'image/vnd.net-fpx']], + ['frl', 'application/freeloader'], + ['fsc', 'application/vnd.fsc.weblaunch'], + ['fst', 'image/vnd.fst'], + ['ftc', 'application/vnd.fluxtime.clip'], + ['fti', 'application/vnd.anser-web-funds-transfer-initiation'], + ['funk', 'audio/make'], + ['fvt', 'video/vnd.fvt'], + ['fxp', 'application/vnd.adobe.fxp'], + ['fzs', 'application/vnd.fuzzysheet'], + ['g', 'text/plain'], + ['g2w', 'application/vnd.geoplan'], + ['g3', 'image/g3fax'], + ['g3w', 'application/vnd.geospace'], + ['gac', 'application/vnd.groove-account'], + ['gdl', 'model/vnd.gdl'], + ['geo', 'application/vnd.dynageo'], + ['geojson', 'application/geo+json'], + ['gex', 'application/vnd.geometry-explorer'], + ['ggb', 'application/vnd.geogebra.file'], + ['ggt', 'application/vnd.geogebra.tool'], + ['ghf', 'application/vnd.groove-help'], + ['gif', 'image/gif'], + ['gim', 'application/vnd.groove-identity-message'], + ['gl', ['video/gl', 'video/x-gl']], + ['gmx', 'application/vnd.gmx'], + ['gnumeric', 'application/x-gnumeric'], + ['gph', 'application/vnd.flographit'], + ['gqf', 'application/vnd.grafeq'], + ['gram', 'application/srgs'], + ['grv', 'application/vnd.groove-injector'], + ['grxml', 'application/srgs+xml'], + ['gsd', 'audio/x-gsm'], + ['gsf', 'application/x-font-ghostscript'], + ['gsm', 'audio/x-gsm'], + ['gsp', 'application/x-gsp'], + ['gss', 'application/x-gss'], + ['gtar', 'application/x-gtar'], + ['gtm', 'application/vnd.groove-tool-message'], + ['gtw', 'model/vnd.gtw'], + ['gv', 'text/vnd.graphviz'], + ['gxt', 'application/vnd.geonext'], + ['gz', ['application/x-gzip', 'application/x-compressed']], + ['gzip', ['multipart/x-gzip', 'application/x-gzip']], + ['h', ['text/plain', 'text/x-h']], + ['h261', 'video/h261'], + ['h263', 'video/h263'], + ['h264', 'video/h264'], + ['hal', 'application/vnd.hal+xml'], + ['hbci', 'application/vnd.hbci'], + ['hdf', 'application/x-hdf'], + ['help', 'application/x-helpfile'], + ['hgl', 'application/vnd.hp-hpgl'], + ['hh', ['text/plain', 'text/x-h']], + ['hlb', 'text/x-script'], + ['hlp', ['application/winhlp', 'application/hlp', 'application/x-helpfile', 'application/x-winhelp']], + ['hpg', 'application/vnd.hp-hpgl'], + ['hpgl', 'application/vnd.hp-hpgl'], + ['hpid', 'application/vnd.hp-hpid'], + ['hps', 'application/vnd.hp-hps'], + [ + 'hqx', + [ + 'application/mac-binhex40', + 'application/binhex', + 'application/binhex4', + 'application/mac-binhex', + 'application/x-binhex40', + 'application/x-mac-binhex40' + ] + ], + ['hta', 'application/hta'], + ['htc', 'text/x-component'], + ['htke', 'application/vnd.kenameaapp'], + ['htm', 'text/html'], + ['html', 'text/html'], + ['htmls', 'text/html'], + ['htt', 'text/webviewhtml'], + ['htx', 'text/html'], + ['hvd', 'application/vnd.yamaha.hv-dic'], + ['hvp', 'application/vnd.yamaha.hv-voice'], + ['hvs', 'application/vnd.yamaha.hv-script'], + ['i2g', 'application/vnd.intergeo'], + ['icc', 'application/vnd.iccprofile'], + ['ice', 'x-conference/x-cooltalk'], + ['ico', 'image/x-icon'], + ['ics', 'text/calendar'], + ['idc', 'text/plain'], + ['ief', 'image/ief'], + ['iefs', 'image/ief'], + ['ifm', 'application/vnd.shana.informed.formdata'], + ['iges', ['application/iges', 'model/iges']], + ['igl', 'application/vnd.igloader'], + ['igm', 'application/vnd.insors.igm'], + ['igs', ['application/iges', 'model/iges']], + ['igx', 'application/vnd.micrografx.igx'], + ['iif', 'application/vnd.shana.informed.interchange'], + ['iii', 'application/x-iphone'], + ['ima', 'application/x-ima'], + ['imap', 'application/x-httpd-imap'], + ['imp', 'application/vnd.accpac.simply.imp'], + ['ims', 'application/vnd.ms-ims'], + ['inf', 'application/inf'], + ['ins', ['application/x-internet-signup', 'application/x-internett-signup']], + ['ip', 'application/x-ip2'], + ['ipfix', 'application/ipfix'], + ['ipk', 'application/vnd.shana.informed.package'], + ['irm', 'application/vnd.ibm.rights-management'], + ['irp', 'application/vnd.irepository.package+xml'], + ['isp', 'application/x-internet-signup'], + ['isu', 'video/x-isvideo'], + ['it', 'audio/it'], + ['itp', 'application/vnd.shana.informed.formtemplate'], + ['iv', 'application/x-inventor'], + ['ivp', 'application/vnd.immervision-ivp'], + ['ivr', 'i-world/i-vrml'], + ['ivu', 'application/vnd.immervision-ivu'], + ['ivy', 'application/x-livescreen'], + ['jad', 'text/vnd.sun.j2me.app-descriptor'], + ['jam', ['application/vnd.jam', 'audio/x-jam']], + ['jar', 'application/java-archive'], + ['jav', ['text/plain', 'text/x-java-source']], + ['java', ['text/plain', 'text/x-java-source,java', 'text/x-java-source']], + ['jcm', 'application/x-java-commerce'], + ['jfif', ['image/pipeg', 'image/jpeg', 'image/pjpeg']], + ['jfif-tbnl', 'image/jpeg'], + ['jisp', 'application/vnd.jisp'], + ['jlt', 'application/vnd.hp-jlyt'], + ['jnlp', 'application/x-java-jnlp-file'], + ['joda', 'application/vnd.joost.joda-archive'], + ['jpe', ['image/jpeg', 'image/pjpeg']], + ['jpeg', ['image/jpeg', 'image/pjpeg']], + ['jpg', ['image/jpeg', 'image/pjpeg']], + ['jpgv', 'video/jpeg'], + ['jpm', 'video/jpm'], + ['jps', 'image/x-jps'], + ['js', ['application/javascript', 'application/ecmascript', 'text/javascript', 'text/ecmascript', 'application/x-javascript']], + ['json', 'application/json'], + ['jut', 'image/jutvision'], + ['kar', ['audio/midi', 'music/x-karaoke']], + ['karbon', 'application/vnd.kde.karbon'], + ['kfo', 'application/vnd.kde.kformula'], + ['kia', 'application/vnd.kidspiration'], + ['kml', 'application/vnd.google-earth.kml+xml'], + ['kmz', 'application/vnd.google-earth.kmz'], + ['kne', 'application/vnd.kinar'], + ['kon', 'application/vnd.kde.kontour'], + ['kpr', 'application/vnd.kde.kpresenter'], + ['ksh', ['application/x-ksh', 'text/x-script.ksh']], + ['ksp', 'application/vnd.kde.kspread'], + ['ktx', 'image/ktx'], + ['ktz', 'application/vnd.kahootz'], + ['kwd', 'application/vnd.kde.kword'], + ['la', ['audio/nspaudio', 'audio/x-nspaudio']], + ['lam', 'audio/x-liveaudio'], + ['lasxml', 'application/vnd.las.las+xml'], + ['latex', 'application/x-latex'], + ['lbd', 'application/vnd.llamagraphics.life-balance.desktop'], + ['lbe', 'application/vnd.llamagraphics.life-balance.exchange+xml'], + ['les', 'application/vnd.hhe.lesson-player'], + ['lha', ['application/octet-stream', 'application/lha', 'application/x-lha']], + ['lhx', 'application/octet-stream'], + ['link66', 'application/vnd.route66.link66+xml'], + ['list', 'text/plain'], + ['lma', ['audio/nspaudio', 'audio/x-nspaudio']], + ['log', 'text/plain'], + ['lrm', 'application/vnd.ms-lrm'], + ['lsf', 'video/x-la-asf'], + ['lsp', ['application/x-lisp', 'text/x-script.lisp']], + ['lst', 'text/plain'], + ['lsx', ['video/x-la-asf', 'text/x-la-asf']], + ['ltf', 'application/vnd.frogans.ltf'], + ['ltx', 'application/x-latex'], + ['lvp', 'audio/vnd.lucent.voice'], + ['lwp', 'application/vnd.lotus-wordpro'], + ['lzh', ['application/octet-stream', 'application/x-lzh']], + ['lzx', ['application/lzx', 'application/octet-stream', 'application/x-lzx']], + ['m', ['text/plain', 'text/x-m']], + ['m13', 'application/x-msmediaview'], + ['m14', 'application/x-msmediaview'], + ['m1v', 'video/mpeg'], + ['m21', 'application/mp21'], + ['m2a', 'audio/mpeg'], + ['m2v', 'video/mpeg'], + ['m3u', ['audio/x-mpegurl', 'audio/x-mpequrl']], + ['m3u8', 'application/vnd.apple.mpegurl'], + ['m4v', 'video/x-m4v'], + ['ma', 'application/mathematica'], + ['mads', 'application/mads+xml'], + ['mag', 'application/vnd.ecowin.chart'], + ['man', 'application/x-troff-man'], + ['map', 'application/x-navimap'], + ['mar', 'text/plain'], + ['mathml', 'application/mathml+xml'], + ['mbd', 'application/mbedlet'], + ['mbk', 'application/vnd.mobius.mbk'], + ['mbox', 'application/mbox'], + ['mc$', 'application/x-magic-cap-package-1.0'], + ['mc1', 'application/vnd.medcalcdata'], + ['mcd', ['application/mcad', 'application/vnd.mcd', 'application/x-mathcad']], + ['mcf', ['image/vasa', 'text/mcf']], + ['mcp', 'application/netmc'], + ['mcurl', 'text/vnd.curl.mcurl'], + ['mdb', 'application/x-msaccess'], + ['mdi', 'image/vnd.ms-modi'], + ['me', 'application/x-troff-me'], + ['meta4', 'application/metalink4+xml'], + ['mets', 'application/mets+xml'], + ['mfm', 'application/vnd.mfmp'], + ['mgp', 'application/vnd.osgeo.mapguide.package'], + ['mgz', 'application/vnd.proteus.magazine'], + ['mht', 'message/rfc822'], + ['mhtml', 'message/rfc822'], + ['mid', ['audio/mid', 'audio/midi', 'music/crescendo', 'x-music/x-midi', 'audio/x-midi', 'application/x-midi', 'audio/x-mid']], + ['midi', ['audio/midi', 'music/crescendo', 'x-music/x-midi', 'audio/x-midi', 'application/x-midi', 'audio/x-mid']], + ['mif', ['application/vnd.mif', 'application/x-mif', 'application/x-frame']], + ['mime', ['message/rfc822', 'www/mime']], + ['mj2', 'video/mj2'], + ['mjf', 'audio/x-vnd.audioexplosion.mjuicemediafile'], + ['mjpg', 'video/x-motion-jpeg'], + ['mlp', 'application/vnd.dolby.mlp'], + ['mm', ['application/base64', 'application/x-meme']], + ['mmd', 'application/vnd.chipnuts.karaoke-mmd'], + ['mme', 'application/base64'], + ['mmf', 'application/vnd.smaf'], + ['mmr', 'image/vnd.fujixerox.edmics-mmr'], + ['mny', 'application/x-msmoney'], + ['mod', ['audio/mod', 'audio/x-mod']], + ['mods', 'application/mods+xml'], + ['moov', 'video/quicktime'], + ['mov', 'video/quicktime'], + ['movie', 'video/x-sgi-movie'], + ['mp2', ['video/mpeg', 'audio/mpeg', 'video/x-mpeg', 'audio/x-mpeg', 'video/x-mpeq2a']], + ['mp3', ['audio/mpeg', 'audio/mpeg3', 'video/mpeg', 'audio/x-mpeg-3', 'video/x-mpeg']], + ['mp4', ['video/mp4', 'application/mp4']], + ['mp4a', 'audio/mp4'], + ['mpa', ['video/mpeg', 'audio/mpeg']], + ['mpc', ['application/vnd.mophun.certificate', 'application/x-project']], + ['mpe', 'video/mpeg'], + ['mpeg', 'video/mpeg'], + ['mpg', ['video/mpeg', 'audio/mpeg']], + ['mpga', 'audio/mpeg'], + ['mpkg', 'application/vnd.apple.installer+xml'], + ['mpm', 'application/vnd.blueice.multipass'], + ['mpn', 'application/vnd.mophun.application'], + ['mpp', 'application/vnd.ms-project'], + ['mpt', 'application/x-project'], + ['mpv', 'application/x-project'], + ['mpv2', 'video/mpeg'], + ['mpx', 'application/x-project'], + ['mpy', 'application/vnd.ibm.minipay'], + ['mqy', 'application/vnd.mobius.mqy'], + ['mrc', 'application/marc'], + ['mrcx', 'application/marcxml+xml'], + ['ms', 'application/x-troff-ms'], + ['mscml', 'application/mediaservercontrol+xml'], + ['mseq', 'application/vnd.mseq'], + ['msf', 'application/vnd.epson.msf'], + ['msg', 'application/vnd.ms-outlook'], + ['msh', 'model/mesh'], + ['msl', 'application/vnd.mobius.msl'], + ['msty', 'application/vnd.muvee.style'], + ['mts', 'model/vnd.mts'], + ['mus', 'application/vnd.musician'], + ['musicxml', 'application/vnd.recordare.musicxml+xml'], + ['mv', 'video/x-sgi-movie'], + ['mvb', 'application/x-msmediaview'], + ['mwf', 'application/vnd.mfer'], + ['mxf', 'application/mxf'], + ['mxl', 'application/vnd.recordare.musicxml'], + ['mxml', 'application/xv+xml'], + ['mxs', 'application/vnd.triscape.mxs'], + ['mxu', 'video/vnd.mpegurl'], + ['my', 'audio/make'], + ['mzz', 'application/x-vnd.audioexplosion.mzz'], + ['n-gage', 'application/vnd.nokia.n-gage.symbian.install'], + ['n3', 'text/n3'], + ['nap', 'image/naplps'], + ['naplps', 'image/naplps'], + ['nbp', 'application/vnd.wolfram.player'], + ['nc', 'application/x-netcdf'], + ['ncm', 'application/vnd.nokia.configuration-message'], + ['ncx', 'application/x-dtbncx+xml'], + ['ngdat', 'application/vnd.nokia.n-gage.data'], + ['nif', 'image/x-niff'], + ['niff', 'image/x-niff'], + ['nix', 'application/x-mix-transfer'], + ['nlu', 'application/vnd.neurolanguage.nlu'], + ['nml', 'application/vnd.enliven'], + ['nnd', 'application/vnd.noblenet-directory'], + ['nns', 'application/vnd.noblenet-sealer'], + ['nnw', 'application/vnd.noblenet-web'], + ['npx', 'image/vnd.net-fpx'], + ['nsc', 'application/x-conference'], + ['nsf', 'application/vnd.lotus-notes'], + ['nvd', 'application/x-navidoc'], + ['nws', 'message/rfc822'], + ['o', 'application/octet-stream'], + ['oa2', 'application/vnd.fujitsu.oasys2'], + ['oa3', 'application/vnd.fujitsu.oasys3'], + ['oas', 'application/vnd.fujitsu.oasys'], + ['obd', 'application/x-msbinder'], + ['oda', 'application/oda'], + ['odb', 'application/vnd.oasis.opendocument.database'], + ['odc', 'application/vnd.oasis.opendocument.chart'], + ['odf', 'application/vnd.oasis.opendocument.formula'], + ['odft', 'application/vnd.oasis.opendocument.formula-template'], + ['odg', 'application/vnd.oasis.opendocument.graphics'], + ['odi', 'application/vnd.oasis.opendocument.image'], + ['odm', 'application/vnd.oasis.opendocument.text-master'], + ['odp', 'application/vnd.oasis.opendocument.presentation'], + ['ods', 'application/vnd.oasis.opendocument.spreadsheet'], + ['odt', 'application/vnd.oasis.opendocument.text'], + ['oga', 'audio/ogg'], + ['ogv', 'video/ogg'], + ['ogx', 'application/ogg'], + ['omc', 'application/x-omc'], + ['omcd', 'application/x-omcdatamaker'], + ['omcr', 'application/x-omcregerator'], + ['onetoc', 'application/onenote'], + ['opf', 'application/oebps-package+xml'], + ['org', 'application/vnd.lotus-organizer'], + ['osf', 'application/vnd.yamaha.openscoreformat'], + ['osfpvg', 'application/vnd.yamaha.openscoreformat.osfpvg+xml'], + ['otc', 'application/vnd.oasis.opendocument.chart-template'], + ['otf', 'application/x-font-otf'], + ['otg', 'application/vnd.oasis.opendocument.graphics-template'], + ['oth', 'application/vnd.oasis.opendocument.text-web'], + ['oti', 'application/vnd.oasis.opendocument.image-template'], + ['otp', 'application/vnd.oasis.opendocument.presentation-template'], + ['ots', 'application/vnd.oasis.opendocument.spreadsheet-template'], + ['ott', 'application/vnd.oasis.opendocument.text-template'], + ['oxt', 'application/vnd.openofficeorg.extension'], + ['p', 'text/x-pascal'], + ['p10', ['application/pkcs10', 'application/x-pkcs10']], + ['p12', ['application/pkcs-12', 'application/x-pkcs12']], + ['p7a', 'application/x-pkcs7-signature'], + ['p7b', 'application/x-pkcs7-certificates'], + ['p7c', ['application/pkcs7-mime', 'application/x-pkcs7-mime']], + ['p7m', ['application/pkcs7-mime', 'application/x-pkcs7-mime']], + ['p7r', 'application/x-pkcs7-certreqresp'], + ['p7s', ['application/pkcs7-signature', 'application/x-pkcs7-signature']], + ['p8', 'application/pkcs8'], + ['par', 'text/plain-bas'], + ['part', 'application/pro_eng'], + ['pas', 'text/pascal'], + ['paw', 'application/vnd.pawaafile'], + ['pbd', 'application/vnd.powerbuilder6'], + ['pbm', 'image/x-portable-bitmap'], + ['pcf', 'application/x-font-pcf'], + ['pcl', ['application/vnd.hp-pcl', 'application/x-pcl']], + ['pclxl', 'application/vnd.hp-pclxl'], + ['pct', 'image/x-pict'], + ['pcurl', 'application/vnd.curl.pcurl'], + ['pcx', 'image/x-pcx'], + ['pdb', ['application/vnd.palm', 'chemical/x-pdb']], + ['pdf', 'application/pdf'], + ['pfa', 'application/x-font-type1'], + ['pfr', 'application/font-tdpfr'], + ['pfunk', ['audio/make', 'audio/make.my.funk']], + ['pfx', 'application/x-pkcs12'], + ['pgm', ['image/x-portable-graymap', 'image/x-portable-greymap']], + ['pgn', 'application/x-chess-pgn'], + ['pgp', 'application/pgp-signature'], + ['pic', ['image/pict', 'image/x-pict']], + ['pict', 'image/pict'], + ['pkg', 'application/x-newton-compatible-pkg'], + ['pki', 'application/pkixcmp'], + ['pkipath', 'application/pkix-pkipath'], + ['pko', ['application/ynd.ms-pkipko', 'application/vnd.ms-pki.pko']], + ['pl', ['text/plain', 'text/x-script.perl']], + ['plb', 'application/vnd.3gpp.pic-bw-large'], + ['plc', 'application/vnd.mobius.plc'], + ['plf', 'application/vnd.pocketlearn'], + ['pls', 'application/pls+xml'], + ['plx', 'application/x-pixclscript'], + ['pm', ['text/x-script.perl-module', 'image/x-xpixmap']], + ['pm4', 'application/x-pagemaker'], + ['pm5', 'application/x-pagemaker'], + ['pma', 'application/x-perfmon'], + ['pmc', 'application/x-perfmon'], + ['pml', ['application/vnd.ctc-posml', 'application/x-perfmon']], + ['pmr', 'application/x-perfmon'], + ['pmw', 'application/x-perfmon'], + ['png', 'image/png'], + ['pnm', ['application/x-portable-anymap', 'image/x-portable-anymap']], + ['portpkg', 'application/vnd.macports.portpkg'], + ['pot', ['application/vnd.ms-powerpoint', 'application/mspowerpoint']], + ['potm', 'application/vnd.ms-powerpoint.template.macroenabled.12'], + ['potx', 'application/vnd.openxmlformats-officedocument.presentationml.template'], + ['pov', 'model/x-pov'], + ['ppa', 'application/vnd.ms-powerpoint'], + ['ppam', 'application/vnd.ms-powerpoint.addin.macroenabled.12'], + ['ppd', 'application/vnd.cups-ppd'], + ['ppm', 'image/x-portable-pixmap'], + ['pps', ['application/vnd.ms-powerpoint', 'application/mspowerpoint']], + ['ppsm', 'application/vnd.ms-powerpoint.slideshow.macroenabled.12'], + ['ppsx', 'application/vnd.openxmlformats-officedocument.presentationml.slideshow'], + ['ppt', ['application/vnd.ms-powerpoint', 'application/mspowerpoint', 'application/powerpoint', 'application/x-mspowerpoint']], + ['pptm', 'application/vnd.ms-powerpoint.presentation.macroenabled.12'], + ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'], + ['ppz', 'application/mspowerpoint'], + ['prc', 'application/x-mobipocket-ebook'], + ['pre', ['application/vnd.lotus-freelance', 'application/x-freelance']], + ['prf', 'application/pics-rules'], + ['prt', 'application/pro_eng'], + ['ps', 'application/postscript'], + ['psb', 'application/vnd.3gpp.pic-bw-small'], + ['psd', ['application/octet-stream', 'image/vnd.adobe.photoshop']], + ['psf', 'application/x-font-linux-psf'], + ['pskcxml', 'application/pskc+xml'], + ['ptid', 'application/vnd.pvi.ptid1'], + ['pub', 'application/x-mspublisher'], + ['pvb', 'application/vnd.3gpp.pic-bw-var'], + ['pvu', 'paleovu/x-pv'], + ['pwn', 'application/vnd.3m.post-it-notes'], + ['pwz', 'application/vnd.ms-powerpoint'], + ['py', 'text/x-script.phyton'], + ['pya', 'audio/vnd.ms-playready.media.pya'], + ['pyc', 'application/x-bytecode.python'], + ['pyv', 'video/vnd.ms-playready.media.pyv'], + ['qam', 'application/vnd.epson.quickanime'], + ['qbo', 'application/vnd.intu.qbo'], + ['qcp', 'audio/vnd.qcelp'], + ['qd3', 'x-world/x-3dmf'], + ['qd3d', 'x-world/x-3dmf'], + ['qfx', 'application/vnd.intu.qfx'], + ['qif', 'image/x-quicktime'], + ['qps', 'application/vnd.publishare-delta-tree'], + ['qt', 'video/quicktime'], + ['qtc', 'video/x-qtc'], + ['qti', 'image/x-quicktime'], + ['qtif', 'image/x-quicktime'], + ['qxd', 'application/vnd.quark.quarkxpress'], + ['ra', ['audio/x-realaudio', 'audio/x-pn-realaudio', 'audio/x-pn-realaudio-plugin']], + ['ram', 'audio/x-pn-realaudio'], + ['rar', 'application/x-rar-compressed'], + ['ras', ['image/cmu-raster', 'application/x-cmu-raster', 'image/x-cmu-raster']], + ['rast', 'image/cmu-raster'], + ['rcprofile', 'application/vnd.ipunplugged.rcprofile'], + ['rdf', 'application/rdf+xml'], + ['rdz', 'application/vnd.data-vision.rdz'], + ['rep', 'application/vnd.businessobjects'], + ['res', 'application/x-dtbresource+xml'], + ['rexx', 'text/x-script.rexx'], + ['rf', 'image/vnd.rn-realflash'], + ['rgb', 'image/x-rgb'], + ['rif', 'application/reginfo+xml'], + ['rip', 'audio/vnd.rip'], + ['rl', 'application/resource-lists+xml'], + ['rlc', 'image/vnd.fujixerox.edmics-rlc'], + ['rld', 'application/resource-lists-diff+xml'], + ['rm', ['application/vnd.rn-realmedia', 'audio/x-pn-realaudio']], + ['rmi', 'audio/mid'], + ['rmm', 'audio/x-pn-realaudio'], + ['rmp', ['audio/x-pn-realaudio-plugin', 'audio/x-pn-realaudio']], + ['rms', 'application/vnd.jcp.javame.midlet-rms'], + ['rnc', 'application/relax-ng-compact-syntax'], + ['rng', ['application/ringing-tones', 'application/vnd.nokia.ringing-tone']], + ['rnx', 'application/vnd.rn-realplayer'], + ['roff', 'application/x-troff'], + ['rp', 'image/vnd.rn-realpix'], + ['rp9', 'application/vnd.cloanto.rp9'], + ['rpm', 'audio/x-pn-realaudio-plugin'], + ['rpss', 'application/vnd.nokia.radio-presets'], + ['rpst', 'application/vnd.nokia.radio-preset'], + ['rq', 'application/sparql-query'], + ['rs', 'application/rls-services+xml'], + ['rsd', 'application/rsd+xml'], + ['rt', ['text/richtext', 'text/vnd.rn-realtext']], + ['rtf', ['application/rtf', 'text/richtext', 'application/x-rtf']], + ['rtx', ['text/richtext', 'application/rtf']], + ['rv', 'video/vnd.rn-realvideo'], + ['s', 'text/x-asm'], + ['s3m', 'audio/s3m'], + ['saf', 'application/vnd.yamaha.smaf-audio'], + ['saveme', 'application/octet-stream'], + ['sbk', 'application/x-tbook'], + ['sbml', 'application/sbml+xml'], + ['sc', 'application/vnd.ibm.secure-container'], + ['scd', 'application/x-msschedule'], + [ + 'scm', + ['application/vnd.lotus-screencam', 'video/x-scm', 'text/x-script.guile', 'application/x-lotusscreencam', 'text/x-script.scheme'] + ], + ['scq', 'application/scvp-cv-request'], + ['scs', 'application/scvp-cv-response'], + ['sct', 'text/scriptlet'], + ['scurl', 'text/vnd.curl.scurl'], + ['sda', 'application/vnd.stardivision.draw'], + ['sdc', 'application/vnd.stardivision.calc'], + ['sdd', 'application/vnd.stardivision.impress'], + ['sdkm', 'application/vnd.solent.sdkm+xml'], + ['sdml', 'text/plain'], + ['sdp', ['application/sdp', 'application/x-sdp']], + ['sdr', 'application/sounder'], + ['sdw', 'application/vnd.stardivision.writer'], + ['sea', ['application/sea', 'application/x-sea']], + ['see', 'application/vnd.seemail'], + ['seed', 'application/vnd.fdsn.seed'], + ['sema', 'application/vnd.sema'], + ['semd', 'application/vnd.semd'], + ['semf', 'application/vnd.semf'], + ['ser', 'application/java-serialized-object'], + ['set', 'application/set'], + ['setpay', 'application/set-payment-initiation'], + ['setreg', 'application/set-registration-initiation'], + ['sfd-hdstx', 'application/vnd.hydrostatix.sof-data'], + ['sfs', 'application/vnd.spotfire.sfs'], + ['sgl', 'application/vnd.stardivision.writer-global'], + ['sgm', ['text/sgml', 'text/x-sgml']], + ['sgml', ['text/sgml', 'text/x-sgml']], + ['sh', ['application/x-shar', 'application/x-bsh', 'application/x-sh', 'text/x-script.sh']], + ['shar', ['application/x-bsh', 'application/x-shar']], + ['shf', 'application/shf+xml'], + ['shtml', ['text/html', 'text/x-server-parsed-html']], + ['sid', 'audio/x-psid'], + ['sis', 'application/vnd.symbian.install'], + ['sit', ['application/x-stuffit', 'application/x-sit']], + ['sitx', 'application/x-stuffitx'], + ['skd', 'application/x-koan'], + ['skm', 'application/x-koan'], + ['skp', ['application/vnd.koan', 'application/x-koan']], + ['skt', 'application/x-koan'], + ['sl', 'application/x-seelogo'], + ['sldm', 'application/vnd.ms-powerpoint.slide.macroenabled.12'], + ['sldx', 'application/vnd.openxmlformats-officedocument.presentationml.slide'], + ['slt', 'application/vnd.epson.salt'], + ['sm', 'application/vnd.stepmania.stepchart'], + ['smf', 'application/vnd.stardivision.math'], + ['smi', ['application/smil', 'application/smil+xml']], + ['smil', 'application/smil'], + ['snd', ['audio/basic', 'audio/x-adpcm']], + ['snf', 'application/x-font-snf'], + ['sol', 'application/solids'], + ['spc', ['text/x-speech', 'application/x-pkcs7-certificates']], + ['spf', 'application/vnd.yamaha.smaf-phrase'], + ['spl', ['application/futuresplash', 'application/x-futuresplash']], + ['spot', 'text/vnd.in3d.spot'], + ['spp', 'application/scvp-vp-response'], + ['spq', 'application/scvp-vp-request'], + ['spr', 'application/x-sprite'], + ['sprite', 'application/x-sprite'], + ['src', 'application/x-wais-source'], + ['sru', 'application/sru+xml'], + ['srx', 'application/sparql-results+xml'], + ['sse', 'application/vnd.kodak-descriptor'], + ['ssf', 'application/vnd.epson.ssf'], + ['ssi', 'text/x-server-parsed-html'], + ['ssm', 'application/streamingmedia'], + ['ssml', 'application/ssml+xml'], + ['sst', ['application/vnd.ms-pkicertstore', 'application/vnd.ms-pki.certstore']], + ['st', 'application/vnd.sailingtracker.track'], + ['stc', 'application/vnd.sun.xml.calc.template'], + ['std', 'application/vnd.sun.xml.draw.template'], + ['step', 'application/step'], + ['stf', 'application/vnd.wt.stf'], + ['sti', 'application/vnd.sun.xml.impress.template'], + ['stk', 'application/hyperstudio'], + ['stl', ['application/vnd.ms-pkistl', 'application/sla', 'application/vnd.ms-pki.stl', 'application/x-navistyle']], + ['stm', 'text/html'], + ['stp', 'application/step'], + ['str', 'application/vnd.pg.format'], + ['stw', 'application/vnd.sun.xml.writer.template'], + ['sub', 'image/vnd.dvb.subtitle'], + ['sus', 'application/vnd.sus-calendar'], + ['sv4cpio', 'application/x-sv4cpio'], + ['sv4crc', 'application/x-sv4crc'], + ['svc', 'application/vnd.dvb.service'], + ['svd', 'application/vnd.svd'], + ['svf', ['image/vnd.dwg', 'image/x-dwg']], + ['svg', 'image/svg+xml'], + ['svr', ['x-world/x-svr', 'application/x-world']], + ['swf', 'application/x-shockwave-flash'], + ['swi', 'application/vnd.aristanetworks.swi'], + ['sxc', 'application/vnd.sun.xml.calc'], + ['sxd', 'application/vnd.sun.xml.draw'], + ['sxg', 'application/vnd.sun.xml.writer.global'], + ['sxi', 'application/vnd.sun.xml.impress'], + ['sxm', 'application/vnd.sun.xml.math'], + ['sxw', 'application/vnd.sun.xml.writer'], + ['t', ['text/troff', 'application/x-troff']], + ['talk', 'text/x-speech'], + ['tao', 'application/vnd.tao.intent-module-archive'], + ['tar', 'application/x-tar'], + ['tbk', ['application/toolbook', 'application/x-tbook']], + ['tcap', 'application/vnd.3gpp2.tcap'], + ['tcl', ['text/x-script.tcl', 'application/x-tcl']], + ['tcsh', 'text/x-script.tcsh'], + ['teacher', 'application/vnd.smart.teacher'], + ['tei', 'application/tei+xml'], + ['tex', 'application/x-tex'], + ['texi', 'application/x-texinfo'], + ['texinfo', 'application/x-texinfo'], + ['text', ['application/plain', 'text/plain']], + ['tfi', 'application/thraud+xml'], + ['tfm', 'application/x-tex-tfm'], + ['tgz', ['application/gnutar', 'application/x-compressed']], + ['thmx', 'application/vnd.ms-officetheme'], + ['tif', ['image/tiff', 'image/x-tiff']], + ['tiff', ['image/tiff', 'image/x-tiff']], + ['tmo', 'application/vnd.tmobile-livetv'], + ['torrent', 'application/x-bittorrent'], + ['tpl', 'application/vnd.groove-tool-template'], + ['tpt', 'application/vnd.trid.tpt'], + ['tr', 'application/x-troff'], + ['tra', 'application/vnd.trueapp'], + ['trm', 'application/x-msterminal'], + ['tsd', 'application/timestamped-data'], + ['tsi', 'audio/tsp-audio'], + ['tsp', ['application/dsptype', 'audio/tsplayer']], + ['tsv', 'text/tab-separated-values'], + ['ttf', 'application/x-font-ttf'], + ['ttl', 'text/turtle'], + ['turbot', 'image/florian'], + ['twd', 'application/vnd.simtech-mindmapper'], + ['txd', 'application/vnd.genomatix.tuxedo'], + ['txf', 'application/vnd.mobius.txf'], + ['txt', 'text/plain'], + ['ufd', 'application/vnd.ufdl'], + ['uil', 'text/x-uil'], + ['uls', 'text/iuls'], + ['umj', 'application/vnd.umajin'], + ['uni', 'text/uri-list'], + ['unis', 'text/uri-list'], + ['unityweb', 'application/vnd.unity'], + ['unv', 'application/i-deas'], + ['uoml', 'application/vnd.uoml+xml'], + ['uri', 'text/uri-list'], + ['uris', 'text/uri-list'], + ['ustar', ['application/x-ustar', 'multipart/x-ustar']], + ['utz', 'application/vnd.uiq.theme'], + ['uu', ['application/octet-stream', 'text/x-uuencode']], + ['uue', 'text/x-uuencode'], + ['uva', 'audio/vnd.dece.audio'], + ['uvh', 'video/vnd.dece.hd'], + ['uvi', 'image/vnd.dece.graphic'], + ['uvm', 'video/vnd.dece.mobile'], + ['uvp', 'video/vnd.dece.pd'], + ['uvs', 'video/vnd.dece.sd'], + ['uvu', 'video/vnd.uvvu.mp4'], + ['uvv', 'video/vnd.dece.video'], + ['vcd', 'application/x-cdlink'], + ['vcf', 'text/x-vcard'], + ['vcg', 'application/vnd.groove-vcard'], + ['vcs', 'text/x-vcalendar'], + ['vcx', 'application/vnd.vcx'], + ['vda', 'application/vda'], + ['vdo', 'video/vdo'], + ['vew', 'application/groupwise'], + ['vis', 'application/vnd.visionary'], + ['viv', ['video/vivo', 'video/vnd.vivo']], + ['vivo', ['video/vivo', 'video/vnd.vivo']], + ['vmd', 'application/vocaltec-media-desc'], + ['vmf', 'application/vocaltec-media-file'], + ['voc', ['audio/voc', 'audio/x-voc']], + ['vos', 'video/vosaic'], + ['vox', 'audio/voxware'], + ['vqe', 'audio/x-twinvq-plugin'], + ['vqf', 'audio/x-twinvq'], + ['vql', 'audio/x-twinvq-plugin'], + ['vrml', ['model/vrml', 'x-world/x-vrml', 'application/x-vrml']], + ['vrt', 'x-world/x-vrt'], + ['vsd', ['application/vnd.visio', 'application/x-visio']], + ['vsf', 'application/vnd.vsf'], + ['vst', 'application/x-visio'], + ['vsw', 'application/x-visio'], + ['vtu', 'model/vnd.vtu'], + ['vxml', 'application/voicexml+xml'], + ['w60', 'application/wordperfect6.0'], + ['w61', 'application/wordperfect6.1'], + ['w6w', 'application/msword'], + ['wad', 'application/x-doom'], + ['wav', ['audio/wav', 'audio/x-wav']], + ['wax', 'audio/x-ms-wax'], + ['wb1', 'application/x-qpro'], + ['wbmp', 'image/vnd.wap.wbmp'], + ['wbs', 'application/vnd.criticaltools.wbs+xml'], + ['wbxml', 'application/vnd.wap.wbxml'], + ['wcm', 'application/vnd.ms-works'], + ['wdb', 'application/vnd.ms-works'], + ['web', 'application/vnd.xara'], + ['weba', 'audio/webm'], + ['webm', 'video/webm'], + ['webp', 'image/webp'], + ['wg', 'application/vnd.pmi.widget'], + ['wgt', 'application/widget'], + ['wiz', 'application/msword'], + ['wk1', 'application/x-123'], + ['wks', 'application/vnd.ms-works'], + ['wm', 'video/x-ms-wm'], + ['wma', 'audio/x-ms-wma'], + ['wmd', 'application/x-ms-wmd'], + ['wmf', ['windows/metafile', 'application/x-msmetafile']], + ['wml', 'text/vnd.wap.wml'], + ['wmlc', 'application/vnd.wap.wmlc'], + ['wmls', 'text/vnd.wap.wmlscript'], + ['wmlsc', 'application/vnd.wap.wmlscriptc'], + ['wmv', 'video/x-ms-wmv'], + ['wmx', 'video/x-ms-wmx'], + ['wmz', 'application/x-ms-wmz'], + ['woff', 'application/x-font-woff'], + ['word', 'application/msword'], + ['wp', 'application/wordperfect'], + ['wp5', ['application/wordperfect', 'application/wordperfect6.0']], + ['wp6', 'application/wordperfect'], + ['wpd', ['application/wordperfect', 'application/vnd.wordperfect', 'application/x-wpwin']], + ['wpl', 'application/vnd.ms-wpl'], + ['wps', 'application/vnd.ms-works'], + ['wq1', 'application/x-lotus'], + ['wqd', 'application/vnd.wqd'], + ['wri', ['application/mswrite', 'application/x-wri', 'application/x-mswrite']], + ['wrl', ['model/vrml', 'x-world/x-vrml', 'application/x-world']], + ['wrz', ['model/vrml', 'x-world/x-vrml']], + ['wsc', 'text/scriplet'], + ['wsdl', 'application/wsdl+xml'], + ['wspolicy', 'application/wspolicy+xml'], + ['wsrc', 'application/x-wais-source'], + ['wtb', 'application/vnd.webturbo'], + ['wtk', 'application/x-wintalk'], + ['wvx', 'video/x-ms-wvx'], + ['x-png', 'image/png'], + ['x3d', 'application/vnd.hzn-3d-crossword'], + ['xaf', 'x-world/x-vrml'], + ['xap', 'application/x-silverlight-app'], + ['xar', 'application/vnd.xara'], + ['xbap', 'application/x-ms-xbap'], + ['xbd', 'application/vnd.fujixerox.docuworks.binder'], + ['xbm', ['image/xbm', 'image/x-xbm', 'image/x-xbitmap']], + ['xdf', 'application/xcap-diff+xml'], + ['xdm', 'application/vnd.syncml.dm+xml'], + ['xdp', 'application/vnd.adobe.xdp+xml'], + ['xdr', 'video/x-amt-demorun'], + ['xdssc', 'application/dssc+xml'], + ['xdw', 'application/vnd.fujixerox.docuworks'], + ['xenc', 'application/xenc+xml'], + ['xer', 'application/patch-ops-error+xml'], + ['xfdf', 'application/vnd.adobe.xfdf'], + ['xfdl', 'application/vnd.xfdl'], + ['xgz', 'xgl/drawing'], + ['xhtml', 'application/xhtml+xml'], + ['xif', 'image/vnd.xiff'], + ['xl', 'application/excel'], + ['xla', ['application/vnd.ms-excel', 'application/excel', 'application/x-msexcel', 'application/x-excel']], + ['xlam', 'application/vnd.ms-excel.addin.macroenabled.12'], + ['xlb', ['application/excel', 'application/vnd.ms-excel', 'application/x-excel']], + ['xlc', ['application/vnd.ms-excel', 'application/excel', 'application/x-excel']], + ['xld', ['application/excel', 'application/x-excel']], + ['xlk', ['application/excel', 'application/x-excel']], + ['xll', ['application/excel', 'application/vnd.ms-excel', 'application/x-excel']], + ['xlm', ['application/vnd.ms-excel', 'application/excel', 'application/x-excel']], + ['xls', ['application/vnd.ms-excel', 'application/excel', 'application/x-msexcel', 'application/x-excel']], + ['xlsb', 'application/vnd.ms-excel.sheet.binary.macroenabled.12'], + ['xlsm', 'application/vnd.ms-excel.sheet.macroenabled.12'], + ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'], + ['xlt', ['application/vnd.ms-excel', 'application/excel', 'application/x-excel']], + ['xltm', 'application/vnd.ms-excel.template.macroenabled.12'], + ['xltx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.template'], + ['xlv', ['application/excel', 'application/x-excel']], + ['xlw', ['application/vnd.ms-excel', 'application/excel', 'application/x-msexcel', 'application/x-excel']], + ['xm', 'audio/xm'], + ['xml', ['application/xml', 'text/xml', 'application/atom+xml', 'application/rss+xml']], + ['xmz', 'xgl/movie'], + ['xo', 'application/vnd.olpc-sugar'], + ['xof', 'x-world/x-vrml'], + ['xop', 'application/xop+xml'], + ['xpi', 'application/x-xpinstall'], + ['xpix', 'application/x-vnd.ls-xpix'], + ['xpm', ['image/xpm', 'image/x-xpixmap']], + ['xpr', 'application/vnd.is-xpr'], + ['xps', 'application/vnd.ms-xpsdocument'], + ['xpw', 'application/vnd.intercon.formnet'], + ['xslt', 'application/xslt+xml'], + ['xsm', 'application/vnd.syncml+xml'], + ['xspf', 'application/xspf+xml'], + ['xsr', 'video/x-amt-showrun'], + ['xul', 'application/vnd.mozilla.xul+xml'], + ['xwd', ['image/x-xwd', 'image/x-xwindowdump']], + ['xyz', ['chemical/x-xyz', 'chemical/x-pdb']], + ['yang', 'application/yang'], + ['yin', 'application/yin+xml'], + ['z', ['application/x-compressed', 'application/x-compress']], + ['zaz', 'application/vnd.zzazz.deck+xml'], + ['zip', ['application/zip', 'multipart/x-zip', 'application/x-zip-compressed', 'application/x-compressed']], + ['zir', 'application/vnd.zul'], + ['zmm', 'application/vnd.handheld-entertainment+xml'], + ['zoo', 'application/octet-stream'], + ['zsh', 'text/x-script.zsh'] +]); + +module.exports = { + detectMimeType(filename) { + if (!filename) { + return defaultMimeType; + } + + const parsed = path.parse(filename); + const extension = (parsed.ext.substr(1) || parsed.name || '').split('?').shift().trim().toLowerCase(); + const value = extensions.has(extension) ? extensions.get(extension) : defaultMimeType; + + if (Array.isArray(value)) { + return value[0]; + } + return value; + }, + + detectExtension(mimeType) { + if (!mimeType) { + return defaultExtension; + } + const parts = mimeType.toLowerCase().trim().split('/'); + const rootType = parts.shift().trim(); + const subType = parts.join('/').trim(); + + if (mimeTypes.has(rootType + '/' + subType)) { + const value = mimeTypes.get(rootType + '/' + subType); + if (Array.isArray(value)) { + return value[0]; + } + return value; + } + + switch (rootType) { + case 'text': + return 'txt'; + default: + return 'bin'; + } + } +}; diff --git a/node_modules/nodemailer/lib/mime-node/index.js b/node_modules/nodemailer/lib/mime-node/index.js new file mode 100644 index 0000000000000000000000000000000000000000..586b268a460b9a5e472a6bac17ceebcfdf1a9022 --- /dev/null +++ b/node_modules/nodemailer/lib/mime-node/index.js @@ -0,0 +1,1338 @@ +/* eslint no-undefined: 0, prefer-spread: 0, no-control-regex: 0 */ + +'use strict'; + +const crypto = require('crypto'); +const fs = require('fs'); +const punycode = require('../punycode'); +const { PassThrough } = require('stream'); +const shared = require('../shared'); + +const mimeFuncs = require('../mime-funcs'); +const qp = require('../qp'); +const base64 = require('../base64'); +const addressparser = require('../addressparser'); +const nmfetch = require('../fetch'); +const errors = require('../errors'); +const LastNewline = require('./last-newline'); + +const LeWindows = require('./le-windows'); +const LeUnix = require('./le-unix'); + +const FORMATTED_HEADERS = ['From', 'Sender', 'To', 'Cc', 'Bcc', 'Reply-To', 'Date', 'References']; + +/** + * Creates a new mime tree node. Assumes 'multipart/*' as the content type + * if it is a branch, anything else counts as leaf. If rootNode is missing from + * the options, assumes this is the root. + * + * @param {String} contentType Define the content type for the node. Can be left blank for attachments (derived from filename) + * @param {Object} [options] optional options + * @param {Object} [options.rootNode] root node for this tree + * @param {Object} [options.parentNode] immediate parent for this node + * @param {Object} [options.filename] filename for an attachment node + * @param {String} [options.baseBoundary] shared part of the unique multipart boundary + * @param {Boolean} [options.keepBcc] If true, do not exclude Bcc from the generated headers + * @param {Function} [options.normalizeHeaderKey] method to normalize header keys for custom caseing + * @param {String} [options.textEncoding] either 'Q' (the default) or 'B' + */ +class MimeNode { + constructor(contentType, options) { + this.nodeCounter = 0; + + options = options || {}; + + /** + * shared part of the unique multipart boundary + */ + this.baseBoundary = options.baseBoundary || crypto.randomBytes(8).toString('hex'); + this.boundaryPrefix = options.boundaryPrefix || '--_NmP'; + + this.disableFileAccess = !!options.disableFileAccess; + this.disableUrlAccess = !!options.disableUrlAccess; + + this.normalizeHeaderKey = options.normalizeHeaderKey; + + /** + * If date headers is missing and current node is the root, this value is used instead + */ + this.date = options.parentNode ? null : new Date(); + + /** + * Root node for current mime tree + */ + this.rootNode = options.rootNode || this; + + /** + * If true include Bcc in generated headers (if available) + */ + this.keepBcc = !!options.keepBcc; + + /** + * If filename is specified but contentType is not (probably an attachment) + * detect the content type from filename extension + */ + if (options.filename) { + /** + * Filename for this node. Useful with attachments + */ + this.filename = options.filename; + if (!contentType) { + contentType = mimeFuncs.detectMimeType(this.filename.split('.').pop()); + } + } + + /** + * Indicates which encoding should be used for header strings: "Q" or "B" + */ + this.textEncoding = (options.textEncoding || '').toString().trim().charAt(0).toUpperCase(); + + /** + * Immediate parent for this node (or undefined if not set) + */ + this.parentNode = options.parentNode; + + /** + * Hostname for default message-id values + */ + this.hostname = options.hostname; + + /** + * If set to 'win' then uses \r\n, if 'linux' then \n. If not set (or `raw` is used) then newlines are kept as is. + */ + this.newline = options.newline; + + /** + * An array for possible child nodes + */ + this.childNodes = []; + + /** + * Used for generating unique boundaries (prepended to the shared base) + */ + this._nodeId = ++this.rootNode.nodeCounter; + + /** + * A list of header values for this node in the form of [{key:'', value:''}] + */ + this._headers = []; + + /** + * True if the content only uses ASCII printable characters + * @type {Boolean} + */ + this._isPlainText = false; + + /** + * True if the content is plain text but has longer lines than allowed + * @type {Boolean} + */ + this._hasLongLines = false; + + /** + * If set, use instead this value for envelopes instead of generating one + * @type {Boolean} + */ + this._envelope = false; + + /** + * If set then use this value as the stream content instead of building it + * @type {String|Buffer|Stream} + */ + this._raw = false; + + /** + * Additional transform streams that the message will be piped before + * exposing by createReadStream + * @type {Array} + */ + this._transforms = []; + + /** + * Additional process functions that the message will be piped through before + * exposing by createReadStream. These functions are run after transforms + * @type {Array} + */ + this._processFuncs = []; + + /** + * If content type is set (or derived from the filename) add it to headers + */ + if (contentType) { + this.setHeader('Content-Type', contentType); + } + } + + /////// PUBLIC METHODS + + /** + * Creates and appends a child node.Arguments provided are passed to MimeNode constructor + * + * @param {String} [contentType] Optional content type + * @param {Object} [options] Optional options object + * @return {Object} Created node object + */ + createChild(contentType, options) { + if (!options && typeof contentType === 'object') { + options = contentType; + contentType = undefined; + } + const node = new MimeNode(contentType, options); + this.appendChild(node); + return node; + } + + /** + * Appends an existing node to the mime tree. Removes the node from an existing + * tree if needed + * + * @param {Object} childNode node to be appended + * @return {Object} Appended node object + */ + appendChild(childNode) { + if (childNode.rootNode !== this.rootNode) { + childNode.rootNode = this.rootNode; + childNode._nodeId = ++this.rootNode.nodeCounter; + } + + childNode.parentNode = this; + + this.childNodes.push(childNode); + return childNode; + } + + /** + * Replaces current node with another node + * + * @param {Object} node Replacement node + * @return {Object} Replacement node + */ + replace(node) { + if (node === this) { + return this; + } + + this.parentNode.childNodes.forEach((childNode, i) => { + if (childNode === this) { + node.rootNode = this.rootNode; + node.parentNode = this.parentNode; + node._nodeId = this._nodeId; + + this.rootNode = this; + this.parentNode = undefined; + + node.parentNode.childNodes[i] = node; + } + }); + + return node; + } + + /** + * Removes current node from the mime tree + * + * @return {Object} removed node + */ + remove() { + if (!this.parentNode) { + return this; + } + + for (let i = this.parentNode.childNodes.length - 1; i >= 0; i--) { + if (this.parentNode.childNodes[i] === this) { + this.parentNode.childNodes.splice(i, 1); + this.parentNode = undefined; + this.rootNode = this; + return this; + } + } + } + + /** + * Sets a header value. If the value for selected key exists, it is overwritten. + * You can set multiple values as well by using [{key:'', value:''}] or + * {key: 'value'} as the first argument. + * + * @param {String|Array|Object} key Header key or a list of key value pairs + * @param {String} value Header value + * @return {Object} current node + */ + setHeader(key, value) { + let added = false; + + // Allow setting multiple headers at once + if (!value && key && typeof key === 'object') { + // allow {key:'content-type', value: 'text/plain'} + if (key.key && 'value' in key) { + this.setHeader(key.key, key.value); + } else if (Array.isArray(key)) { + // allow [{key:'content-type', value: 'text/plain'}] + key.forEach(i => { + this.setHeader(i.key, i.value); + }); + } else { + // allow {'content-type': 'text/plain'} + Object.keys(key).forEach(i => { + this.setHeader(i, key[i]); + }); + } + return this; + } + + key = this._normalizeHeaderKey(key); + + const headerValue = { + key, + value + }; + + // Check if the value exists and overwrite + for (let i = 0, len = this._headers.length; i < len; i++) { + if (this._headers[i].key === key) { + if (!added) { + // replace the first match + this._headers[i] = headerValue; + added = true; + } else { + // remove following matches + this._headers.splice(i, 1); + i--; + len--; + } + } + } + + // match not found, append the value + if (!added) { + this._headers.push(headerValue); + } + + return this; + } + + /** + * Adds a header value. If the value for selected key exists, the value is appended + * as a new field and old one is not touched. + * You can set multiple values as well by using [{key:'', value:''}] or + * {key: 'value'} as the first argument. + * + * @param {String|Array|Object} key Header key or a list of key value pairs + * @param {String} value Header value + * @return {Object} current node + */ + addHeader(key, value) { + // Allow setting multiple headers at once + if (!value && key && typeof key === 'object') { + // allow {key:'content-type', value: 'text/plain'} + if (key.key && key.value) { + this.addHeader(key.key, key.value); + } else if (Array.isArray(key)) { + // allow [{key:'content-type', value: 'text/plain'}] + key.forEach(i => { + this.addHeader(i.key, i.value); + }); + } else { + // allow {'content-type': 'text/plain'} + Object.keys(key).forEach(i => { + this.addHeader(i, key[i]); + }); + } + return this; + } else if (Array.isArray(value)) { + value.forEach(val => { + this.addHeader(key, val); + }); + return this; + } + + this._headers.push({ + key: this._normalizeHeaderKey(key), + value + }); + + return this; + } + + /** + * Retrieves the first mathcing value of a selected key + * + * @param {String} key Key to search for + * @retun {String} Value for the key + */ + getHeader(key) { + key = this._normalizeHeaderKey(key); + for (let i = 0, len = this._headers.length; i < len; i++) { + if (this._headers[i].key === key) { + return this._headers[i].value; + } + } + } + + /** + * Sets body content for current node. If the value is a string, charset is added automatically + * to Content-Type (if it is text/*). If the value is a Buffer, you need to specify + * the charset yourself + * + * @param (String|Buffer) content Body content + * @return {Object} current node + */ + setContent(content) { + this.content = content; + if (typeof this.content.pipe === 'function') { + // pre-stream handler. might be triggered if a stream is set as content + // and 'error' fires before anything is done with this stream + this._contentErrorHandler = err => { + this.content.removeListener('error', this._contentErrorHandler); + this.content = err; + }; + this.content.once('error', this._contentErrorHandler); + } else if (typeof this.content === 'string') { + this._isPlainText = mimeFuncs.isPlainText(this.content); + if (this._isPlainText && mimeFuncs.hasLongerLines(this.content, 76)) { + // If there are lines longer than 76 symbols/bytes do not use 7bit + this._hasLongLines = true; + } + } + return this; + } + + build(callback) { + let promise; + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = shared.callbackPromise(resolve, reject); + }); + } + + const stream = this.createReadStream(); + const buf = []; + let buflen = 0; + let returned = false; + + stream.on('readable', () => { + let chunk; + + while ((chunk = stream.read()) !== null) { + buf.push(chunk); + buflen += chunk.length; + } + }); + + stream.once('error', err => { + if (returned) { + return; + } + returned = true; + + return callback(err); + }); + + stream.once('end', chunk => { + if (returned) { + return; + } + returned = true; + + if (chunk && chunk.length) { + buf.push(chunk); + buflen += chunk.length; + } + return callback(null, Buffer.concat(buf, buflen)); + }); + + return promise; + } + + getTransferEncoding() { + let transferEncoding = false; + const contentType = (this.getHeader('Content-Type') || '').toString().toLowerCase().trim(); + + if (this.content) { + transferEncoding = (this.getHeader('Content-Transfer-Encoding') || '').toString().toLowerCase().trim(); + if (!transferEncoding || !['base64', 'quoted-printable'].includes(transferEncoding)) { + if (/^text\//i.test(contentType)) { + // If there are no special symbols, no need to modify the text + if (this._isPlainText && !this._hasLongLines) { + transferEncoding = '7bit'; + } else if (typeof this.content === 'string' || this.content instanceof Buffer) { + // detect preferred encoding for string value + transferEncoding = this._getTextEncoding(this.content) === 'Q' ? 'quoted-printable' : 'base64'; + } else { + // we can not check content for a stream, so either use preferred encoding or fallback to QP + transferEncoding = this.textEncoding === 'B' ? 'base64' : 'quoted-printable'; + } + } else if (!/^(multipart|message)\//i.test(contentType)) { + transferEncoding = transferEncoding || 'base64'; + } + } + } + return transferEncoding; + } + + /** + * Builds the header block for the mime node. Append \r\n\r\n before writing the content + * + * @returns {String} Headers + */ + buildHeaders() { + const transferEncoding = this.getTransferEncoding(); + const headers = []; + + if (transferEncoding) { + this.setHeader('Content-Transfer-Encoding', transferEncoding); + } + + if (this.filename && !this.getHeader('Content-Disposition')) { + this.setHeader('Content-Disposition', 'attachment'); + } + + // Ensure mandatory header fields + if (this.rootNode === this) { + if (!this.getHeader('Date')) { + this.setHeader('Date', this.date.toUTCString().replace(/GMT/, '+0000')); + } + + // ensure that Message-Id is present + this.messageId(); + + if (!this.getHeader('MIME-Version')) { + this.setHeader('MIME-Version', '1.0'); + } + + // Ensure that Content-Type is the last header for the root node + for (let i = this._headers.length - 2; i >= 0; i--) { + const header = this._headers[i]; + if (header.key === 'Content-Type') { + this._headers.splice(i, 1); + this._headers.push(header); + } + } + } + + this._headers.forEach(header => { + let key = header.key; + let value = header.value; + let structured; + let param; + const options = {}; + const formattedHeaders = FORMATTED_HEADERS; + + if (value && typeof value === 'object' && !formattedHeaders.includes(key)) { + Object.keys(value).forEach(key => { + if (key !== 'value') { + options[key] = value[key]; + } + }); + value = (value.value || '').toString(); + if (!value.trim()) { + return; + } + } + + if (options.prepared) { + // header value is + if (options.foldLines) { + headers.push(mimeFuncs.foldLines(key + ': ' + value)); + } else { + headers.push(key + ': ' + value); + } + return; + } + + switch (header.key) { + case 'Content-Disposition': + structured = mimeFuncs.parseHeaderValue(value); + if (this.filename) { + structured.params.filename = this.filename; + } + value = mimeFuncs.buildHeaderValue(structured); + break; + + case 'Content-Type': + structured = mimeFuncs.parseHeaderValue(value); + + this._handleContentType(structured); + + if ( + structured.value.match(/^text\/plain\b/) && + typeof this.content === 'string' && + /[\u0080-\uFFFF]/.test(this.content) + ) { + structured.params.charset = 'utf-8'; + } + + value = mimeFuncs.buildHeaderValue(structured); + + if (this.filename) { + // add support for non-compliant clients like QQ webmail + // we can't build the value with buildHeaderValue as the value is non standard and + // would be converted to parameter continuation encoding that we do not want + param = this._encodeWords(this.filename); + + if (param !== this.filename || /[\s'"\\;:/=(),<>@[\]?]|^-/.test(param)) { + // include value in quotes if needed + param = '"' + param + '"'; + } + value += '; name=' + param; + } + break; + + case 'Bcc': + if (!this.keepBcc) { + // skip BCC values + return; + } + break; + } + + value = this._encodeHeaderValue(key, value); + + // skip empty lines + if (!(value || '').toString().trim()) { + return; + } + + if (typeof this.normalizeHeaderKey === 'function') { + const normalized = this.normalizeHeaderKey(key, value); + if (normalized && typeof normalized === 'string' && normalized.length) { + key = normalized; + } + } + + headers.push(mimeFuncs.foldLines(key + ': ' + value, 76)); + }); + + return headers.join('\r\n'); + } + + /** + * Streams the rfc2822 message from the current node. If this is a root node, + * mandatory header fields are set if missing (Date, Message-Id, MIME-Version) + * + * @return {String} Compiled message + */ + createReadStream(options) { + options = options || {}; + + const stream = new PassThrough(options); + let outputStream = stream; + let transform; + + this.stream(stream, options, err => { + if (err) { + outputStream.emit('error', err); + return; + } + stream.end(); + }); + + for (let i = 0, len = this._transforms.length; i < len; i++) { + transform = typeof this._transforms[i] === 'function' ? this._transforms[i]() : this._transforms[i]; + outputStream.once('error', err => { + transform.emit('error', err); + }); + outputStream = outputStream.pipe(transform); + } + + // ensure terminating newline after possible user transforms + transform = new LastNewline(); + outputStream.once('error', err => { + transform.emit('error', err); + }); + outputStream = outputStream.pipe(transform); + + // dkim and stuff + for (let i = 0, len = this._processFuncs.length; i < len; i++) { + transform = this._processFuncs[i]; + outputStream = transform(outputStream); + } + + if (this.newline) { + const winbreak = ['win', 'windows', 'dos', '\r\n'].includes(this.newline.toString().toLowerCase()); + const newlineTransform = winbreak ? new LeWindows() : new LeUnix(); + + const stream = outputStream.pipe(newlineTransform); + outputStream.on('error', err => stream.emit('error', err)); + return stream; + } + + return outputStream; + } + + /** + * Appends a transform stream object to the transforms list. Final output + * is passed through this stream before exposing + * + * @param {Object} transform Read-Write stream + */ + transform(transform) { + this._transforms.push(transform); + } + + /** + * Appends a post process function. The functon is run after transforms and + * uses the following syntax + * + * processFunc(input) -> outputStream + * + * @param {Object} processFunc Read-Write stream + */ + processFunc(processFunc) { + this._processFuncs.push(processFunc); + } + + stream(outputStream, options, done) { + const transferEncoding = this.getTransferEncoding(); + let contentStream; + let localStream; + + // protect actual callback against multiple triggering + let returned = false; + const callback = err => { + if (returned) { + return; + } + returned = true; + done(err); + }; + + // for multipart nodes, push child nodes + // for content nodes end the stream + const finalize = () => { + let childId = 0; + const processChildNode = () => { + if (childId >= this.childNodes.length) { + outputStream.write('\r\n--' + this.boundary + '--\r\n'); + return callback(); + } + const child = this.childNodes[childId++]; + outputStream.write((childId > 1 ? '\r\n' : '') + '--' + this.boundary + '\r\n'); + child.stream(outputStream, options, err => { + if (err) { + return callback(err); + } + setImmediate(processChildNode); + }); + }; + + if (this.multipart) { + setImmediate(processChildNode); + } else { + return callback(); + } + }; + + // pushes node content + const sendContent = () => { + if (this.content) { + if (Object.prototype.toString.call(this.content) === '[object Error]') { + // content is already errored + return callback(this.content); + } + + if (typeof this.content.pipe === 'function') { + this.content.removeListener('error', this._contentErrorHandler); + this._contentErrorHandler = err => callback(err); + this.content.once('error', this._contentErrorHandler); + } + + const createStream = () => { + if (['quoted-printable', 'base64'].includes(transferEncoding)) { + contentStream = new (transferEncoding === 'base64' ? base64 : qp).Encoder(options); + + contentStream.pipe(outputStream, { + end: false + }); + contentStream.once('end', finalize); + contentStream.once('error', err => callback(err)); + + localStream = this._getStream(this.content); + localStream.pipe(contentStream); + } else { + // anything that is not QP or Base54 passes as-is + localStream = this._getStream(this.content); + localStream.pipe(outputStream, { + end: false + }); + localStream.once('end', finalize); + } + + localStream.once('error', err => callback(err)); + }; + + if (this.content._resolve) { + const chunks = []; + let chunklen = 0; + let returned = false; + const sourceStream = this._getStream(this.content); + sourceStream.on('error', err => { + if (returned) { + return; + } + returned = true; + callback(err); + }); + sourceStream.on('readable', () => { + let chunk; + while ((chunk = sourceStream.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; + } + }); + sourceStream.on('end', () => { + if (returned) { + return; + } + returned = true; + this.content._resolve = false; + this.content._resolvedValue = Buffer.concat(chunks, chunklen); + setImmediate(createStream); + }); + } else { + setImmediate(createStream); + } + return; + } + return setImmediate(finalize); + }; + + if (this._raw) { + setImmediate(() => { + if (Object.prototype.toString.call(this._raw) === '[object Error]') { + // content is already errored + return callback(this._raw); + } + + // remove default error handler (if set) + if (typeof this._raw.pipe === 'function') { + this._raw.removeListener('error', this._contentErrorHandler); + } + + const raw = this._getStream(this._raw); + raw.pipe(outputStream, { + end: false + }); + raw.on('error', err => outputStream.emit('error', err)); + raw.on('end', finalize); + }); + } else { + outputStream.write(this.buildHeaders() + '\r\n\r\n'); + setImmediate(sendContent); + } + } + + /** + * Sets envelope to be used instead of the generated one + * + * @return {Object} SMTP envelope in the form of {from: 'from@example.com', to: ['to@example.com']} + */ + setEnvelope(envelope) { + let list; + + this._envelope = { + from: false, + to: [] + }; + + if (envelope.from) { + list = []; + this._convertAddresses(this._parseAddresses(envelope.from), list); + list = list.filter(address => address && address.address); + if (list.length && list[0]) { + this._envelope.from = list[0].address; + } + } + ['to', 'cc', 'bcc'].forEach(key => { + if (envelope[key]) { + this._convertAddresses(this._parseAddresses(envelope[key]), this._envelope.to); + } + }); + + this._envelope.to = this._envelope.to.map(to => to.address).filter(address => address); + + const standardFields = ['to', 'cc', 'bcc', 'from']; + Object.keys(envelope).forEach(key => { + if (!standardFields.includes(key)) { + this._envelope[key] = envelope[key]; + } + }); + + return this; + } + + /** + * Generates and returns an object with parsed address fields + * + * @return {Object} Address object + */ + getAddresses() { + const addresses = {}; + + this._headers.forEach(header => { + const key = header.key.toLowerCase(); + if (['from', 'sender', 'reply-to', 'to', 'cc', 'bcc'].includes(key)) { + if (!Array.isArray(addresses[key])) { + addresses[key] = []; + } + + this._convertAddresses(this._parseAddresses(header.value), addresses[key]); + } + }); + + return addresses; + } + + /** + * Generates and returns SMTP envelope with the sender address and a list of recipients addresses + * + * @return {Object} SMTP envelope in the form of {from: 'from@example.com', to: ['to@example.com']} + */ + getEnvelope() { + if (this._envelope) { + return this._envelope; + } + + const envelope = { + from: false, + to: [] + }; + this._headers.forEach(header => { + const list = []; + if (header.key === 'From' || (!envelope.from && ['Reply-To', 'Sender'].includes(header.key))) { + this._convertAddresses(this._parseAddresses(header.value), list); + if (list.length && list[0]) { + envelope.from = list[0].address; + } + } else if (['To', 'Cc', 'Bcc'].includes(header.key)) { + this._convertAddresses(this._parseAddresses(header.value), envelope.to); + } + }); + + envelope.to = envelope.to.map(to => to.address); + + return envelope; + } + + /** + * Returns Message-Id value. If it does not exist, then creates one + * + * @return {String} Message-Id value + */ + messageId() { + let messageId = this.getHeader('Message-ID'); + // You really should define your own Message-Id field! + if (!messageId) { + messageId = this._generateMessageId(); + this.setHeader('Message-ID', messageId); + } + return messageId; + } + + /** + * Sets pregenerated content that will be used as the output of this node + * + * @param {String|Buffer|Stream} Raw MIME contents + */ + setRaw(raw) { + this._raw = raw; + + if (this._raw && typeof this._raw.pipe === 'function') { + // pre-stream handler. might be triggered if a stream is set as content + // and 'error' fires before anything is done with this stream + this._contentErrorHandler = err => { + this._raw.removeListener('error', this._contentErrorHandler); + this._raw = err; + }; + this._raw.once('error', this._contentErrorHandler); + } + + return this; + } + + /////// PRIVATE METHODS + + /** + * Detects and returns handle to a stream related with the content. + * + * @param {Mixed} content Node content + * @returns {Object} Stream object + */ + _getStream(content) { + let contentStream; + + if (content._resolvedValue) { + // pass string or buffer content as a stream + contentStream = new PassThrough(); + + setImmediate(() => { + try { + contentStream.end(content._resolvedValue); + } catch (_err) { + contentStream.emit('error', _err); + } + }); + + return contentStream; + } + + if (typeof content.pipe === 'function') { + // assume as stream + return content; + } + + if (content && typeof content.path === 'string' && !content.href) { + if (this.disableFileAccess) { + contentStream = new PassThrough(); + setImmediate(() => { + const err = new Error('File access rejected for ' + content.path); + err.code = errors.EFILEACCESS; + contentStream.emit('error', err); + }); + return contentStream; + } + // read file + return fs.createReadStream(content.path); + } + + if (content && typeof content.href === 'string') { + if (this.disableUrlAccess) { + contentStream = new PassThrough(); + setImmediate(() => { + const err = new Error('Url access rejected for ' + content.href); + err.code = errors.EURLACCESS; + contentStream.emit('error', err); + }); + return contentStream; + } + // fetch URL + return nmfetch(content.href, { headers: content.httpHeaders }); + } + + // pass string or buffer content as a stream + contentStream = new PassThrough(); + + setImmediate(() => { + try { + contentStream.end(content || ''); + } catch (_err) { + contentStream.emit('error', _err); + } + }); + return contentStream; + } + + /** + * Parses addresses. Takes in a single address or an array or an + * array of address arrays (eg. To: [[first group], [second group],...]) + * + * @param {Mixed} addresses Addresses to be parsed + * @return {Array} An array of address objects + */ + _parseAddresses(addresses) { + return [].concat.apply( + [], + [].concat(addresses).map(address => { + if (address && address.address) { + address.address = this._normalizeAddress(address.address); + address.name = address.name || ''; + return [address]; + } + return addressparser(address); + }) + ); + } + + /** + * Normalizes a header key, uses Camel-Case form, except for uppercase MIME- + * + * @param {String} key Key to be normalized + * @return {String} key in Camel-Case form + */ + _normalizeHeaderKey(key) { + key = (key || '') + .toString() + // no newlines in keys + .replace(/\r?\n|\r/g, ' ') + .trim() + .toLowerCase() + // use uppercase words, except MIME + .replace(/^X-SMTPAPI$|^(MIME|DKIM|ARC|BIMI)\b|^[a-z]|-(SPF|FBL|ID|MD5)$|-[a-z]/gi, c => c.toUpperCase()) + // special case + .replace(/^Content-Features$/i, 'Content-features'); + + return key; + } + + /** + * Checks if the content type is multipart and defines boundary if needed. + * Doesn't return anything, modifies object argument instead. + * + * @param {Object} structured Parsed header value for 'Content-Type' key + */ + _handleContentType(structured) { + this.contentType = structured.value.trim().toLowerCase(); + + this.multipart = /^multipart\//i.test(this.contentType) ? this.contentType.substr(this.contentType.indexOf('/') + 1) : false; + + if (this.multipart) { + this.boundary = structured.params.boundary = structured.params.boundary || this.boundary || this._generateBoundary(); + } else { + this.boundary = false; + } + } + + /** + * Generates a multipart boundary value + * + * @return {String} boundary value + */ + _generateBoundary() { + return this.rootNode.boundaryPrefix + '-' + this.rootNode.baseBoundary + '-Part_' + this._nodeId; + } + + /** + * Encodes a header value for use in the generated rfc2822 email. + * + * @param {String} key Header key + * @param {String} value Header value + */ + _encodeHeaderValue(key, value) { + key = this._normalizeHeaderKey(key); + + switch (key) { + // Structured headers + case 'From': + case 'Sender': + case 'To': + case 'Cc': + case 'Bcc': + case 'Reply-To': + return this._convertAddresses(this._parseAddresses(value)); + + // values enclosed in <> + case 'Message-ID': + case 'In-Reply-To': + case 'Content-Id': + value = (value || '').toString().replace(/\r?\n|\r/g, ' '); + + if (value.charAt(0) !== '<') { + value = '<' + value; + } + + if (value.charAt(value.length - 1) !== '>') { + value = value + '>'; + } + return value; + + // space separated list of values enclosed in <> + case 'References': + value = [].concat + .apply( + [], + [].concat(value || '').map(elm => { + elm = (elm || '') + .toString() + .replace(/\r?\n|\r/g, ' ') + .trim(); + return elm.replace(/<[^>]*>/g, str => str.replace(/\s/g, '')).split(/\s+/); + }) + ) + .map(elm => { + if (elm.charAt(0) !== '<') { + elm = '<' + elm; + } + if (elm.charAt(elm.length - 1) !== '>') { + elm = elm + '>'; + } + return elm; + }); + + return value.join(' ').trim(); + + case 'Date': + if (Object.prototype.toString.call(value) === '[object Date]') { + return value.toUTCString().replace(/GMT/, '+0000'); + } + + value = (value || '').toString().replace(/\r?\n|\r/g, ' '); + return this._encodeWords(value); + + case 'Content-Type': + case 'Content-Disposition': + // if it includes a filename then it is already encoded + return (value || '').toString().replace(/\r?\n|\r/g, ' '); + + default: + value = (value || '').toString().replace(/\r?\n|\r/g, ' '); + // encodeWords only encodes if needed, otherwise the original string is returned + return this._encodeWords(value); + } + } + + /** + * Rebuilds address object using punycode and other adjustments + * + * @param {Array} addresses An array of address objects + * @param {Array} [uniqueList] An array to be populated with addresses + * @return {String} address string + */ + _convertAddresses(addresses, uniqueList) { + const values = []; + + uniqueList = uniqueList || []; + + [].concat(addresses || []).forEach(address => { + if (address.address) { + address.address = this._normalizeAddress(address.address); + + if (!address.name) { + values.push(address.address.indexOf(' ') >= 0 ? `<${address.address}>` : `${address.address}`); + } else { + values.push(`${this._encodeAddressName(address.name)} <${address.address}>`); + } + + if (!uniqueList.some(a => a.address === address.address)) { + uniqueList.push(address); + } + } else if (address.group) { + const groupListAddresses = (address.group.length ? this._convertAddresses(address.group, uniqueList) : '').trim(); + values.push(`${this._encodeAddressName(address.name)}:${groupListAddresses};`); + } + }); + + return values.join(', '); + } + + /** + * Normalizes an email address + * + * @param {Array} address An array of address objects + * @return {String} address string + */ + _normalizeAddress(address) { + address = (address || '') + .toString() + .replace(/[\x00-\x1F<>]+/g, ' ') // remove unallowed characters + .trim(); + + const lastAt = address.lastIndexOf('@'); + if (lastAt < 0) { + // Bare username + return address; + } + + let user = address.substr(0, lastAt); + const domain = address.substr(lastAt + 1); + + // Usernames are not touched and are kept as is even if these include unicode. + // Domains are punycoded when the local part is ASCII ('safe@jõgeva.ee' -> 'safe@xn--jgeva-dua.ee'). + // When the local part contains non-ASCII bytes the address already requires SMTPUTF8, + // so the domain is kept (or decoded back) as UTF-8 for symmetry on both sides of '@'. + + let encodedDomain = domain; + + try { + if (/[\x80-\uFFFF]/.test(user)) { + encodedDomain = punycode.toUnicode(domain.toLowerCase()); + } else { + encodedDomain = punycode.toASCII(domain.toLowerCase()); + } + } catch (_err) { + // keep domain as supplied + } + + if (user.indexOf(' ') >= 0) { + if (user.charAt(0) !== '"') { + user = '"' + user; + } + if (user.substr(-1) !== '"') { + user = user + '"'; + } + } + + return `${user}@${encodedDomain}`; + } + + /** + * If needed, mime encodes the name part + * + * @param {String} name Name part of an address + * @returns {String} Mime word encoded string if needed + */ + _encodeAddressName(name) { + if (!/^[\w ]*$/.test(name)) { + if (/^[\x20-\x7e]*$/.test(name)) { + return '"' + name.replace(/([\\"])/g, '\\$1') + '"'; + } else { + return mimeFuncs.encodeWord(name, this._getTextEncoding(name), 52); + } + } + return name; + } + + /** + * If needed, mime encodes the name part + * + * @param {String} name Name part of an address + * @returns {String} Mime word encoded string if needed + */ + _encodeWords(value) { + // set encodeAll parameter to true even though it is against the recommendation of RFC2047, + // by default only words that include non-ascii should be converted into encoded words + // but some clients (eg. Zimbra) do not handle it properly and remove surrounding whitespace + return mimeFuncs.encodeWords(value, this._getTextEncoding(value), 52, true); + } + + /** + * Detects best mime encoding for a text value + * + * @param {String} value Value to check for + * @return {String} either 'Q' or 'B' + */ + _getTextEncoding(value) { + value = (value || '').toString(); + + if (this.textEncoding) { + return this.textEncoding; + } + + // count latin alphabet symbols and 8-bit range symbols + control symbols + // if there are more latin characters, then use quoted-printable + // encoding, otherwise use base64 + let nonLatinLen = 0; + let latinLen = 0; + for (let i = 0, len = value.length; i < len; i++) { + const code = value.charCodeAt(i); + if ((code >= 0x00 && code <= 0x08) || code === 0x0b || code === 0x0c || (code >= 0x0e && code <= 0x1f) || code >= 0x80) { + nonLatinLen++; + } else if ((code >= 0x41 && code <= 0x5a) || (code >= 0x61 && code <= 0x7a)) { + latinLen++; + } + } + // if there are more latin symbols than binary/unicode, then prefer Q, otherwise B + return nonLatinLen < latinLen ? 'Q' : 'B'; + } + + /** + * Generates a message id + * + * @return {String} Random Message-ID value + */ + _generateMessageId() { + return ( + '<' + + [2, 2, 2, 6].reduce( + // crux to generate UUID-like random strings + (prev, len) => prev + '-' + crypto.randomBytes(len).toString('hex'), + crypto.randomBytes(4).toString('hex') + ) + + '@' + + // try to use the domain of the FROM address or fallback to server hostname + (this.getEnvelope().from || this.hostname || 'localhost').split('@').pop() + + '>' + ); + } +} + +module.exports = MimeNode; diff --git a/node_modules/nodemailer/lib/mime-node/last-newline.js b/node_modules/nodemailer/lib/mime-node/last-newline.js new file mode 100644 index 0000000000000000000000000000000000000000..0d8684dc3313efb8b6b89fdaf35c69d472c31dbe --- /dev/null +++ b/node_modules/nodemailer/lib/mime-node/last-newline.js @@ -0,0 +1,33 @@ +'use strict'; + +const { Transform } = require('stream'); + +class LastNewline extends Transform { + constructor() { + super(); + this.lastByte = false; + } + + _transform(chunk, encoding, done) { + if (chunk.length) { + this.lastByte = chunk[chunk.length - 1]; + } + + this.push(chunk); + done(); + } + + _flush(done) { + if (this.lastByte === 0x0a) { + return done(); + } + if (this.lastByte === 0x0d) { + this.push(Buffer.from('\n')); + return done(); + } + this.push(Buffer.from('\r\n')); + return done(); + } +} + +module.exports = LastNewline; diff --git a/node_modules/nodemailer/lib/mime-node/le-unix.js b/node_modules/nodemailer/lib/mime-node/le-unix.js new file mode 100644 index 0000000000000000000000000000000000000000..ab51f8caafe3da7f641bad54cd779472ee6e7763 --- /dev/null +++ b/node_modules/nodemailer/lib/mime-node/le-unix.js @@ -0,0 +1,40 @@ +'use strict'; + +const { Transform } = require('stream'); + +/** + * Ensures that only is used for linebreaks + * + * @param {Object} options Stream options + */ +class LeUnix extends Transform { + constructor(options) { + super(options); + } + + /** + * Escapes dots + */ + _transform(chunk, encoding, done) { + let buf; + let lastPos = 0; + + for (let i = 0, len = chunk.length; i < len; i++) { + if (chunk[i] === 0x0d) { + // \r + buf = chunk.slice(lastPos, i); + lastPos = i + 1; + this.push(buf); + } + } + if (lastPos && lastPos < chunk.length) { + buf = chunk.slice(lastPos); + this.push(buf); + } else if (!lastPos) { + this.push(chunk); + } + done(); + } +} + +module.exports = LeUnix; diff --git a/node_modules/nodemailer/lib/mime-node/le-windows.js b/node_modules/nodemailer/lib/mime-node/le-windows.js new file mode 100644 index 0000000000000000000000000000000000000000..4b1159b574b93ffd0e6743a4c59c0aa7549d08f6 --- /dev/null +++ b/node_modules/nodemailer/lib/mime-node/le-windows.js @@ -0,0 +1,49 @@ +'use strict'; + +const { Transform } = require('stream'); + +/** + * Ensures that only sequences are used for linebreaks + * + * @param {Object} options Stream options + */ +class LeWindows extends Transform { + constructor(options) { + super(options); + this.lastByte = false; + } + + /** + * Escapes dots + */ + _transform(chunk, encoding, done) { + let buf; + let lastPos = 0; + + for (let i = 0, len = chunk.length; i < len; i++) { + if (chunk[i] === 0x0a) { + // \n + if ((i && chunk[i - 1] !== 0x0d) || (!i && this.lastByte !== 0x0d)) { + if (i > lastPos) { + buf = chunk.slice(lastPos, i); + this.push(buf); + } + this.push(Buffer.from('\r\n')); + lastPos = i + 1; + } + } + } + + if (lastPos && lastPos < chunk.length) { + buf = chunk.slice(lastPos); + this.push(buf); + } else if (!lastPos) { + this.push(chunk); + } + + this.lastByte = chunk[chunk.length - 1]; + done(); + } +} + +module.exports = LeWindows; diff --git a/node_modules/nodemailer/lib/nodemailer.js b/node_modules/nodemailer/lib/nodemailer.js new file mode 100644 index 0000000000000000000000000000000000000000..3a65f29ed5def9bb5022fda1c08fa40990e02473 --- /dev/null +++ b/node_modules/nodemailer/lib/nodemailer.js @@ -0,0 +1,170 @@ +'use strict'; + +const Mailer = require('./mailer'); +const shared = require('./shared'); +const SMTPPool = require('./smtp-pool'); +const SMTPTransport = require('./smtp-transport'); +const SendmailTransport = require('./sendmail-transport'); +const StreamTransport = require('./stream-transport'); +const JSONTransport = require('./json-transport'); +const SESTransport = require('./ses-transport'); +const errors = require('./errors'); +const nmfetch = require('./fetch'); +const packageData = require('../package.json'); + +const ETHEREAL_API = (process.env.ETHEREAL_API || 'https://api.nodemailer.com').replace(/\/+$/, ''); +const ETHEREAL_WEB = (process.env.ETHEREAL_WEB || 'https://ethereal.email').replace(/\/+$/, ''); +const ETHEREAL_API_KEY = (process.env.ETHEREAL_API_KEY || '').replace(/\s*/g, '') || null; +const ETHEREAL_CACHE = ['true', 'yes', 'y', '1'].includes((process.env.ETHEREAL_CACHE || 'yes').toString().trim().toLowerCase()); + +let testAccount = false; + +module.exports.createTransport = function (transporter, defaults) { + let options; + + if ( + // provided transporter is a configuration object, not transporter plugin + (typeof transporter === 'object' && typeof transporter.send !== 'function') || + // provided transporter looks like a connection url + (typeof transporter === 'string' && /^(smtps?|direct):/i.test(transporter)) + ) { + const urlConfig = typeof transporter === 'string' ? transporter : transporter.url; + if (urlConfig) { + // parse a configuration URL into configuration options + options = shared.parseConnectionUrl(urlConfig); + } else { + options = transporter; + } + + if (options.pool) { + transporter = new SMTPPool(options); + } else if (options.sendmail) { + transporter = new SendmailTransport(options); + } else if (options.streamTransport) { + transporter = new StreamTransport(options); + } else if (options.jsonTransport) { + transporter = new JSONTransport(options); + } else if (options.SES) { + if (options.SES.ses && options.SES.aws) { + const error = new Error( + 'Using legacy SES configuration, expecting @aws-sdk/client-sesv2, see https://nodemailer.com/transports/ses/' + ); + error.code = errors.ECONFIG; + throw error; + } + transporter = new SESTransport(options); + } else { + transporter = new SMTPTransport(options); + } + } + + return new Mailer(transporter, options, defaults); +}; + +module.exports.createTestAccount = function (apiUrl, callback) { + let promise; + + if (!callback && typeof apiUrl === 'function') { + callback = apiUrl; + apiUrl = false; + } + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = shared.callbackPromise(resolve, reject); + }); + } + + if (ETHEREAL_CACHE && testAccount) { + setImmediate(() => callback(null, testAccount)); + return promise; + } + + apiUrl = apiUrl || ETHEREAL_API; + + const chunks = []; + let chunklen = 0; + + const requestHeaders = {}; + const requestBody = { + requestor: packageData.name, + version: packageData.version + }; + + if (ETHEREAL_API_KEY) { + requestHeaders.Authorization = 'Bearer ' + ETHEREAL_API_KEY; + } + + const fetchOptions = { + contentType: 'application/json', + method: 'POST', + headers: requestHeaders, + body: Buffer.from(JSON.stringify(requestBody)) + }; + + // Credential-bearing request — opt back into strict cert validation when + // the API URL is HTTPS. lib/fetch defaults to rejectUnauthorized:false + // for attachment hosts that may be self-signed; the Ethereal API has a + // real cert, so the lax default was a free attack surface. + if (/^https:/i.test(apiUrl)) { + fetchOptions.tls = { rejectUnauthorized: true }; + } + + const req = nmfetch(apiUrl + '/user', fetchOptions); + + req.on('readable', () => { + let chunk; + while ((chunk = req.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; + } + }); + + req.once('error', err => callback(err)); + + req.once('end', () => { + const res = Buffer.concat(chunks, chunklen); + let data; + try { + data = JSON.parse(res.toString()); + } catch (E) { + return callback(E); + } + if (data.status !== 'success' || data.error) { + return callback(new Error(data.error || 'Request failed')); + } + delete data.status; + testAccount = data; + callback(null, testAccount); + }); + + return promise; +}; + +module.exports.getTestMessageUrl = function (info) { + if (!info || !info.response) { + return false; + } + + const infoProps = new Map(); + + // Extract the trailing "[...]" part of the response (no "]" allowed inside) + // with linear string scanning; the equivalent regex /\[([^\]]+)\]$/ was + // flagged for polynomial backtracking on adversarial server responses + const response = info.response.toString(); + if (response.length > 2 && response.charAt(response.length - 1) === ']') { + const open = response.indexOf('[', response.lastIndexOf(']', response.length - 2) + 1); + if (open >= 0 && open < response.length - 2) { + const props = response.substring(open + 1, response.length - 1); + props.replace(/\b([A-Z0-9]+)=([^\s]+)/g, (m, key, value) => { + infoProps.set(key, value); + }); + } + } + + if (infoProps.has('STATUS') && infoProps.has('MSGID')) { + return (testAccount.web || ETHEREAL_WEB) + '/message/' + infoProps.get('MSGID'); + } + + return false; +}; diff --git a/node_modules/nodemailer/lib/punycode/index.js b/node_modules/nodemailer/lib/punycode/index.js new file mode 100644 index 0000000000000000000000000000000000000000..cd3e494b92a04c94ab8340f48e3a6e6510b792cb --- /dev/null +++ b/node_modules/nodemailer/lib/punycode/index.js @@ -0,0 +1,460 @@ +/* + +Copied from https://github.com/mathiasbynens/punycode.js/blob/ef3505c8abb5143a00d53ce59077c9f7f4b2ac47/punycode.js + +Copyright Mathias Bynens + +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. + +*/ +/* eslint callback-return: 0, no-bitwise: 0, eqeqeq: 0, prefer-arrow-callback: 0, object-shorthand: 0 */ + +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + overflow: 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {String} A new string of characters returned by the callback + * function. + */ +function mapDomain(domain, callback) { + const parts = domain.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, '\x2E'); + const labels = domain.split('.'); + const encoded = map(labels, callback).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xd800 && value <= 0xdbff && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xfc00) == 0xdc00) { + // Low surrogate. + output.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = codePoints => String.fromCodePoint(...codePoints); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function (codePoint) { + if (codePoint >= 0x30 && codePoint < 0x3a) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5b) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7b) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function (digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function (delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; /* no initialization */ delta > (baseMinusTMin * tMax) >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + ((baseMinusTMin + 1) * delta) / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function (input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength /* no final expression */; ) { + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + const oldi = i; + for (let w = 1, k = base /* no condition */; ; k += base) { + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base) { + error('invalid-input'); + } + if (digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function (input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + const inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + const basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue === n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base /* no condition */; ; k += base) { + const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + (qMinusT % baseMinusT), 0))); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function (input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function (input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + version: '2.3.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + ucs2: { + decode: ucs2decode, + encode: ucs2encode + }, + decode: decode, + encode: encode, + toASCII: toASCII, + toUnicode: toUnicode +}; + +module.exports = punycode; diff --git a/node_modules/nodemailer/lib/qp/index.js b/node_modules/nodemailer/lib/qp/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9bde0a5806ac3dd21b3e1da4cafafc7a451297c3 --- /dev/null +++ b/node_modules/nodemailer/lib/qp/index.js @@ -0,0 +1,230 @@ +'use strict'; + +const { Transform } = require('stream'); + +/** + * Encodes a Buffer into a Quoted-Printable encoded string + * + * @param {Buffer} buffer Buffer to convert + * @returns {String} Quoted-Printable encoded string + */ +// usable characters that do not need encoding +// https://tools.ietf.org/html/rfc2045#section-6.7 +const QP_RANGES = [ + [0x09], // + [0x0a], // + [0x0d], // + [0x20, 0x3c], // !"#$%&'()*+,-./0123456789:; + [0x3e, 0x7e] // >?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|} +]; + +function encode(buffer) { + if (typeof buffer === 'string') { + buffer = Buffer.from(buffer, 'utf-8'); + } + + let result = ''; + let ord; + + for (let i = 0, len = buffer.length; i < len; i++) { + ord = buffer[i]; + // if the char is in allowed range, then keep as is, unless it is a WS in the end of a line + if ( + checkRanges(ord, QP_RANGES) && + !((ord === 0x20 || ord === 0x09) && (i === len - 1 || buffer[i + 1] === 0x0a || buffer[i + 1] === 0x0d)) + ) { + result += String.fromCharCode(ord); + continue; + } + result += '=' + (ord < 0x10 ? '0' : '') + ord.toString(16).toUpperCase(); + } + + return result; +} + +/** + * Adds soft line breaks to a Quoted-Printable string + * + * @param {String} str Quoted-Printable encoded string that might need line wrapping + * @param {Number} [lineLength=76] Maximum allowed length for a line + * @returns {String} Soft-wrapped Quoted-Printable encoded string + */ +function wrap(str, lineLength) { + str = (str || '').toString(); + lineLength = lineLength || 76; + + if (str.length <= lineLength) { + return str; + } + + let pos = 0; + const len = str.length; + let match, code, line; + const lineMargin = Math.floor(lineLength / 3); + let result = ''; + + // insert soft linebreaks where needed + while (pos < len) { + line = str.substr(pos, lineLength); + if ((match = line.match(/\r\n/))) { + line = line.substr(0, match.index + match[0].length); + result += line; + pos += line.length; + continue; + } + + if (line.substr(-1) === '\n') { + result += line; + pos += line.length; + continue; + } + + if ((match = line.substr(-lineMargin).match(/\n.*?$/))) { + // truncate to nearest line break + line = line.substr(0, line.length - (match[0].length - 1)); + result += line; + pos += line.length; + continue; + } + + if (line.length > lineLength - lineMargin && (match = line.substr(-lineMargin).match(/[ \t.,!?][^ \t.,!?]*$/))) { + // truncate to nearest space + line = line.substr(0, line.length - (match[0].length - 1)); + } else if (line.match(/[=][\da-f]{0,2}$/i)) { + // push incomplete encoding sequences to the next line + if ((match = line.match(/[=][\da-f]{0,1}$/i))) { + line = line.substr(0, line.length - match[0].length); + } + + // ensure that utf-8 sequences are not split + while ( + line.length > 3 && + line.length < len - pos && + !line.match(/^(?:=[\da-f]{2}){1,4}$/i) && + (match = line.match(/[=][\da-f]{2}$/gi)) + ) { + code = parseInt(match[0].substr(1, 2), 16); + if (code < 128) { + break; + } + + line = line.substr(0, line.length - 3); + + if (code >= 0xc0) { + break; + } + } + } + + if (pos + line.length < len && line.substr(-1) !== '\n') { + if (line.length === lineLength && line.match(/[=][\da-f]{2}$/i)) { + line = line.substr(0, line.length - 3); + } else if (line.length === lineLength) { + line = line.substr(0, line.length - 1); + } + pos += line.length; + line += '=\r\n'; + } else { + pos += line.length; + } + + result += line; + } + + return result; +} + +/** + * Helper function to check if a number is inside provided ranges + * + * @param {Number} nr Number to check for + * @param {Array} ranges An Array of allowed values + * @returns {Boolean} True if the value was found inside allowed ranges, false otherwise + */ +function checkRanges(nr, ranges) { + for (let i = ranges.length - 1; i >= 0; i--) { + const range = ranges[i]; + if (!range.length) { + continue; + } + if (range.length === 1 && nr === range[0]) { + return true; + } + if (range.length === 2 && nr >= range[0] && nr <= range[1]) { + return true; + } + } + return false; +} + +/** + * Creates a transform stream for encoding data to Quoted-Printable encoding + * + * @constructor + * @param {Object} options Stream options + * @param {Number} [options.lineLength=76] Maximum length for lines, set to false to disable wrapping + */ +class Encoder extends Transform { + constructor(options) { + super(); + + this.options = options || {}; + + if (this.options.lineLength !== false) { + this.options.lineLength = this.options.lineLength || 76; + } + + this._curLine = ''; + + this.inputBytes = 0; + this.outputBytes = 0; + } + + _transform(chunk, encoding, done) { + let qp; + + if (encoding !== 'buffer') { + chunk = Buffer.from(chunk, encoding); + } + + if (!chunk || !chunk.length) { + return done(); + } + + this.inputBytes += chunk.length; + + if (this.options.lineLength) { + qp = this._curLine + encode(chunk); + qp = wrap(qp, this.options.lineLength); + qp = qp.replace(/(^|\n)([^\n]*)$/, (match, lineBreak, lastLine) => { + this._curLine = lastLine; + return lineBreak; + }); + + if (qp) { + this.outputBytes += qp.length; + this.push(qp); + } + } else { + qp = encode(chunk); + this.outputBytes += qp.length; + this.push(qp, 'ascii'); + } + + done(); + } + + _flush(done) { + if (this._curLine) { + this.outputBytes += this._curLine.length; + this.push(this._curLine, 'ascii'); + } + done(); + } +} + +module.exports = { + encode, + wrap, + Encoder +}; diff --git a/node_modules/nodemailer/lib/sendmail-transport/index.js b/node_modules/nodemailer/lib/sendmail-transport/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b89d5dd2ebe71c4eb9be3be96e0c2ed8c142d13a --- /dev/null +++ b/node_modules/nodemailer/lib/sendmail-transport/index.js @@ -0,0 +1,217 @@ +'use strict'; + +const { spawn } = require('child_process'); +const packageData = require('../../package.json'); +const shared = require('../shared'); +const errors = require('../errors'); +const LeWindows = require('../mime-node/le-windows'); +const LeUnix = require('../mime-node/le-unix'); + +/** + * Generates a Transport object for Sendmail + * + * Possible options can be the following: + * + * * **path** optional path to sendmail binary + * * **newline** either 'windows' or 'unix' + * * **args** an array of arguments for the sendmail binary + * + * @constructor + * @param {Object} optional config parameter for Sendmail + */ +class SendmailTransport { + constructor(options) { + options = options || {}; + + // use a reference to spawn for mocking purposes + this._spawn = spawn; + + this.options = options; + + this.name = 'Sendmail'; + this.version = packageData.version; + + this.path = 'sendmail'; + this.args = false; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'sendmail' + }); + + if (typeof options === 'string') { + this.path = options; + } else if (typeof options === 'object') { + if (options.path) { + this.path = options.path; + } + if (Array.isArray(options.args)) { + this.args = options.args; + } + } + + this.winbreak = ['win', 'windows', 'dos', '\r\n'].includes((options.newline || '').toString().toLowerCase()); + } + + /** + *

Compiles a mailcomposer message and forwards it to handler that sends it.

+ * + * @param {Object} emailMessage MailComposer object + * @param {Function} callback Callback function to run when the sending is completed + */ + send(mail, done) { + // Sendmail strips this header line by itself + mail.message.keepBcc = true; + + const envelope = mail.data.envelope || mail.message.getEnvelope(); + const messageId = mail.message.messageId(); + let returned; + + const hasInvalidAddresses = [] + .concat(envelope.from || []) + .concat(envelope.to || []) + .some(addr => /^-/.test(addr)); + if (hasInvalidAddresses) { + const err = new Error('Can not send mail. Invalid envelope addresses.'); + err.code = errors.ESENDMAIL; + return done(err); + } + + // force -i to keep single dots + const args = this.args + ? ['-i'].concat(this.args).concat(envelope.to) + : ['-i'].concat(envelope.from ? ['-f', envelope.from] : []).concat(envelope.to); + + const callback = err => { + if (returned) { + // ignore any additional responses, already done + return; + } + returned = true; + if (typeof done === 'function') { + if (err) { + return done(err); + } + return done(null, { + envelope, + messageId, + response: 'Messages queued for delivery' + }); + } + }; + + let sendmail; + try { + sendmail = this._spawn(this.path, args); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'spawn', + messageId + }, + 'Error occurred while spawning sendmail. %s', + E.message + ); + return callback(E); + } + + if (sendmail) { + sendmail.on('error', err => { + this.logger.error( + { + err, + tnx: 'spawn', + messageId + }, + 'Error occurred when sending message %s. %s', + messageId, + err.message + ); + callback(err); + }); + + sendmail.once('exit', code => { + if (!code) { + return callback(); + } + const err = new Error( + code === 127 ? 'Sendmail command not found, process exited with code ' + code : 'Sendmail exited with code ' + code + ); + err.code = errors.ESENDMAIL; + + this.logger.error( + { + err, + tnx: 'stdin', + messageId + }, + 'Error sending message %s to sendmail. %s', + messageId, + err.message + ); + callback(err); + }); + sendmail.once('close', callback); + + sendmail.stdin.on('error', err => { + this.logger.error( + { + err, + tnx: 'stdin', + messageId + }, + 'Error occurred when piping message %s to sendmail. %s', + messageId, + err.message + ); + callback(err); + }); + + const recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + this.logger.info( + { + tnx: 'send', + messageId + }, + 'Sending message %s to <%s>', + messageId, + recipients.join(', ') + ); + + const sourceStream = mail.message.createReadStream(); + let stream = sourceStream; + if (this.options.newline) { + // apply the transport-level line ending transform; the message-level + // `newline` option is handled by MimeNode in createReadStream() + stream = sourceStream.pipe(this.winbreak ? new LeWindows() : new LeUnix()); + sourceStream.once('error', err => stream.emit('error', err)); + } + + stream.once('error', err => { + this.logger.error( + { + err, + tnx: 'stdin', + messageId + }, + 'Error occurred when generating message %s. %s', + messageId, + err.message + ); + sendmail.kill('SIGINT'); // do not deliver the message + callback(err); + }); + + stream.pipe(sendmail.stdin); + } else { + const err = new Error('sendmail was not found'); + err.code = errors.ESENDMAIL; + return callback(err); + } + } +} + +module.exports = SendmailTransport; diff --git a/node_modules/nodemailer/lib/ses-transport/index.js b/node_modules/nodemailer/lib/ses-transport/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4b5892cb4a711ae98100ad1f53add577525c8e29 --- /dev/null +++ b/node_modules/nodemailer/lib/ses-transport/index.js @@ -0,0 +1,235 @@ +'use strict'; + +const EventEmitter = require('events'); +const packageData = require('../../package.json'); +const shared = require('../shared'); +const errors = require('../errors'); +const LeWindows = require('../mime-node/le-windows'); +const MimeNode = require('../mime-node'); + +/** + * Tags AWS SDK rejections that carry no `code` property (SDK v3 errors only + * have a `name`) with the generic SES transport error code, keeping the + * original error object intact + */ +function tagSesError(err) { + if (err && typeof err === 'object' && !err.code) { + err.code = errors.ESES; + } + return err; +} + +/** + * Generates a Transport object for AWS SES + * + * @constructor + * @param {Object} optional config parameter + */ +class SESTransport extends EventEmitter { + constructor(options) { + super(); + options = options || {}; + + this.options = options; + this.ses = this.options.SES; + + this.name = 'SESTransport'; + this.version = packageData.version; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'ses-transport' + }); + } + + getRegion(cb) { + if (this.ses.sesClient.config && typeof this.ses.sesClient.config.region === 'function') { + // promise + return this.ses.sesClient.config + .region() + .then(region => cb(null, region)) + .catch(err => cb(err)); + } + return cb(null, false); + } + + /** + * Compiles a mailcomposer message and forwards it to SES + * + * @param {Object} emailMessage MailComposer object + * @param {Function} callback Callback function to run when the sending is completed + */ + send(mail, callback) { + let fromHeader = mail.message._headers.find(header => /^from$/i.test(header.key)); + if (fromHeader) { + const mimeNode = new MimeNode('text/plain'); + fromHeader = mimeNode._convertAddresses(mimeNode._parseAddresses(fromHeader.value)); + } + + const envelope = mail.data.envelope || mail.message.getEnvelope(); + const messageId = mail.message.messageId(); + + const recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + this.logger.info( + { + tnx: 'send', + messageId + }, + 'Sending message %s to <%s>', + messageId, + recipients.join(', ') + ); + + const getRawMessage = next => { + // do not use Message-ID and Date in DKIM signature + if (!mail.data._dkim) { + mail.data._dkim = {}; + } + if (mail.data._dkim.skipFields && typeof mail.data._dkim.skipFields === 'string') { + mail.data._dkim.skipFields += ':date:message-id'; + } else { + mail.data._dkim.skipFields = 'date:message-id'; + } + + const sourceStream = mail.message.createReadStream(); + const stream = sourceStream.pipe(new LeWindows()); + const chunks = []; + let chunklen = 0; + + stream.on('readable', () => { + let chunk; + while ((chunk = stream.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; + } + }); + + sourceStream.once('error', err => stream.emit('error', err)); + + stream.once('error', err => next(err)); + + stream.once('end', () => next(null, Buffer.concat(chunks, chunklen))); + }; + + setImmediate(() => + getRawMessage((err, raw) => { + if (err) { + this.logger.error( + { + err, + tnx: 'send', + messageId + }, + 'Failed creating message for %s. %s', + messageId, + err.message + ); + return callback(err); + } + + const sesMessage = Object.assign( + { + Content: { + Raw: { + // required + Data: raw // required + } + }, + FromEmailAddress: fromHeader || envelope.from, + Destination: { + ToAddresses: envelope.to + } + }, + mail.data.ses || {} + ); + + this.getRegion((err, region) => { + if (err || !region) { + region = 'us-east-1'; + } + + const command = new this.ses.SendEmailCommand(sesMessage); + const sendPromise = this.ses.sesClient.send(command); + + sendPromise + .then(data => { + if (region === 'us-east-1') { + region = 'email'; + } + + callback(null, { + envelope: { + from: envelope.from, + to: envelope.to + }, + messageId: '<' + data.MessageId + (!/@/.test(data.MessageId) ? '@' + region + '.amazonses.com' : '') + '>', + response: data.MessageId, + raw + }); + }) + .catch(err => { + tagSesError(err); + this.logger.error( + { + err, + tnx: 'send' + }, + 'Send error for %s: %s', + messageId, + err.message + ); + callback(err); + }); + }); + }) + ); + } + + /** + * Verifies SES configuration + * + * @param {Function} callback Callback function + */ + verify(callback) { + let promise; + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = shared.callbackPromise(resolve, reject); + }); + } + + const cb = err => { + if (err && !['InvalidParameterValue', 'MessageRejected'].includes(err.code || err.Code || err.name)) { + return callback(tagSesError(err)); + } + return callback(null, true); + }; + + const sesMessage = { + Content: { + Raw: { + Data: Buffer.from('From: \r\nTo: \r\n Subject: Invalid\r\n\r\nInvalid') + } + }, + FromEmailAddress: 'invalid@invalid', + Destination: { + ToAddresses: ['invalid@invalid'] + } + }; + + // the region value is not used for anything when verifying, but the lookup + // exercises the client configuration the same way as send() does + this.getRegion(() => { + const command = new this.ses.SendEmailCommand(sesMessage); + const sendPromise = this.ses.sesClient.send(command); + + sendPromise.then(() => cb(null)).catch(err => cb(err)); + }); + + return promise; + } +} + +module.exports = SESTransport; diff --git a/node_modules/nodemailer/lib/shared/index.js b/node_modules/nodemailer/lib/shared/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ce8c0f059e0a902185672864884d3734b221fcfa --- /dev/null +++ b/node_modules/nodemailer/lib/shared/index.js @@ -0,0 +1,731 @@ +/* eslint no-console: 0 */ + +'use strict'; + +const urllib = require('url'); +const util = require('util'); +const fs = require('fs'); +const nmfetch = require('../fetch'); +const errors = require('../errors'); +const dns = require('dns'); +const net = require('net'); +const os = require('os'); + +const DNS_TTL = 5 * 60 * 1000; +const CACHE_CLEANUP_INTERVAL = 30 * 1000; // Minimum 30 seconds between cleanups +const MAX_CACHE_SIZE = 1000; // Maximum number of entries in cache + +let lastCacheCleanup = 0; +module.exports._lastCacheCleanup = () => lastCacheCleanup; +module.exports._resetCacheCleanup = () => { + lastCacheCleanup = 0; +}; + +let networkInterfaces; +try { + networkInterfaces = os.networkInterfaces(); +} catch (_err) { + // fails on some systems +} + +module.exports.networkInterfaces = networkInterfaces; + +const isFamilySupported = (family, allowInternal) => { + const ifaces = module.exports.networkInterfaces; + if (!ifaces) { + // hope for the best + return true; + } + + return Object.keys(ifaces) + .map(key => ifaces[key]) + .reduce((acc, val) => acc.concat(val), []) + .filter(i => !i.internal || allowInternal) + .some(i => i.family === 'IPv' + family || i.family === family); +}; + +const resolve = (family, hostname, options, callback) => { + options = options || {}; + + if (!isFamilySupported(family, options.allowInternalNetworkInterfaces)) { + return callback(null, []); + } + + const dnsResolver = dns.Resolver ? new dns.Resolver(options) : dns; + dnsResolver['resolve' + family](hostname, (err, addresses) => { + if (err) { + switch (err.code) { + case dns.NODATA: + case dns.NOTFOUND: + case dns.NOTIMP: + case dns.SERVFAIL: + case dns.CONNREFUSED: + case dns.REFUSED: + case 'EAI_AGAIN': + return callback(null, []); + } + return callback(err); + } + return callback(null, Array.isArray(addresses) ? addresses : [].concat(addresses || [])); + }); +}; + +const dnsCache = (module.exports.dnsCache = new Map()); + +const formatDNSValue = (value, extra) => { + if (!value) { + return Object.assign({}, extra || {}); + } + + const addresses = value.addresses || []; + + // Select a random address from available addresses, or null if none + const host = addresses.length > 0 ? addresses[Math.floor(Math.random() * addresses.length)] : null; + + return Object.assign( + { + servername: value.servername, + host, + // Include all addresses for connection fallback support + _addresses: addresses + }, + extra || {} + ); +}; + +module.exports.resolveHostname = (options, callback) => { + options = options || {}; + + if (!options.host && options.servername) { + options.host = options.servername; + } + + if (!options.host || net.isIP(options.host)) { + // nothing to do here + const value = { + addresses: [options.host], + servername: options.servername || false + }; + return callback( + null, + formatDNSValue(value, { + cached: false + }) + ); + } + + let cached; + if (dnsCache.has(options.host)) { + cached = dnsCache.get(options.host); + + // Lazy cleanup with time throttling + const now = Date.now(); + if (now - lastCacheCleanup > CACHE_CLEANUP_INTERVAL) { + lastCacheCleanup = now; + + // Clean up expired entries + for (const [host, entry] of dnsCache.entries()) { + if (entry.expires && entry.expires < now) { + dnsCache.delete(host); + } + } + + // If cache is still too large, remove oldest entries + if (dnsCache.size > MAX_CACHE_SIZE) { + const toDelete = Math.floor(MAX_CACHE_SIZE * 0.1); // Remove 10% of entries + const keys = Array.from(dnsCache.keys()).slice(0, toDelete); + keys.forEach(key => dnsCache.delete(key)); + } + } + + if (!cached.expires || cached.expires >= now) { + return callback( + null, + formatDNSValue(cached.value, { + cached: true + }) + ); + } + } + + // Resolve both IPv4 and IPv6 addresses for fallback support + let ipv4Addresses = []; + let ipv6Addresses = []; + let ipv4Error = null; + let ipv6Error = null; + + resolve(4, options.host, options, (err, addresses) => { + if (err) { + ipv4Error = err; + } else { + ipv4Addresses = addresses || []; + } + + resolve(6, options.host, options, (err, addresses) => { + if (err) { + ipv6Error = err; + } else { + ipv6Addresses = addresses || []; + } + + // Combine addresses: IPv4 first, then IPv6 + const allAddresses = ipv4Addresses.concat(ipv6Addresses); + + if (allAddresses.length) { + const value = { + addresses: allAddresses, + servername: options.servername || options.host + }; + + dnsCache.set(options.host, { + value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + + return callback( + null, + formatDNSValue(value, { + cached: false + }) + ); + } + + // No addresses from resolve4/resolve6, try dns.lookup as fallback + if (ipv4Error && ipv6Error) { + // Both resolvers had errors + if (cached) { + dnsCache.set(options.host, { + value: cached.value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + + return callback( + null, + formatDNSValue(cached.value, { + cached: true, + error: ipv4Error + }) + ); + } + } + + try { + dns.lookup(options.host, { all: true }, (err, addresses) => { + if (err) { + if (cached) { + dnsCache.set(options.host, { + value: cached.value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + + return callback( + null, + formatDNSValue(cached.value, { + cached: true, + error: err + }) + ); + } + return callback(err); + } + + // Get all supported addresses from dns.lookup + const supportedAddresses = addresses + ? addresses.filter(addr => isFamilySupported(addr.family)).map(addr => addr.address) + : []; + + if (addresses && addresses.length && !supportedAddresses.length) { + // there are addresses but none can be used + console.warn(`Failed to resolve IPv${addresses[0].family} addresses with current network`); + } + + if (!supportedAddresses.length && cached) { + // nothing was found, fallback to cached value + return callback( + null, + formatDNSValue(cached.value, { + cached: true + }) + ); + } + + const value = { + addresses: supportedAddresses.length ? supportedAddresses : [options.host], + servername: options.servername || options.host + }; + + dnsCache.set(options.host, { + value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + + return callback( + null, + formatDNSValue(value, { + cached: false + }) + ); + }); + } catch (lookupErr) { + if (cached) { + dnsCache.set(options.host, { + value: cached.value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + + return callback( + null, + formatDNSValue(cached.value, { + cached: true, + error: lookupErr + }) + ); + } + return callback(ipv4Error || ipv6Error || lookupErr); + } + }); + }); +}; +/** + * Parses connection url to a structured configuration object + * + * @param {String} str Connection url + * @return {Object} Configuration object + */ +module.exports.parseConnectionUrl = str => { + str = str || ''; + const options = {}; + const url = urllib.parse(str, true); + + switch (url.protocol) { + case 'smtp:': + options.secure = false; + break; + case 'smtps:': + options.secure = true; + break; + case 'direct:': + options.direct = true; + break; + } + + if (!isNaN(url.port) && Number(url.port)) { + options.port = Number(url.port); + } + + if (url.hostname) { + options.host = url.hostname; + } + + if (url.auth) { + const auth = url.auth.split(':'); + options.auth = { + user: auth.shift(), + pass: auth.join(':') + }; + } + + Object.keys(url.query || {}).forEach(key => { + let obj = options; + let lKey = key; + let value = url.query[key]; + + if (!isNaN(value)) { + value = Number(value); + } + + switch (value) { + case 'true': + value = true; + break; + case 'false': + value = false; + break; + } + + // tls is nested object + if (key.indexOf('tls.') === 0) { + lKey = key.substr(4); + if (!options.tls) { + options.tls = {}; + } + obj = options.tls; + } else if (key.indexOf('.') >= 0) { + // ignore nested properties besides tls + return; + } + + if (!(lKey in obj)) { + obj[lKey] = value; + } + }); + + return options; +}; + +module.exports._logFunc = (logger, level, defaults, data, message, ...args) => { + const entry = Object.assign({}, defaults || {}, data || {}); + delete entry.level; + + let logLevel = level; + if (typeof logger[logLevel] !== 'function') { + // Provided logger does not implement this level. Fall back to a + // lower-severity handler instead of throwing. + logLevel = ['info', 'debug', 'log', 'trace', 'warn', 'error'].find(name => typeof logger[name] === 'function'); + } + + if (logLevel) { + logger[logLevel](entry, message, ...args); + } +}; + +/** + * Returns a bunyan-compatible logger interface. Uses either provided logger or + * creates a default console logger + * + * @param {Object} [options] Options object that might include 'logger' value + * @return {Object} bunyan compatible logger + */ +module.exports.getLogger = (options, defaults) => { + options = options || {}; + + const response = {}; + const levels = ['trace', 'debug', 'info', 'warn', 'error', 'fatal']; + + if (!options.logger) { + // use vanity logger + levels.forEach(level => { + response[level] = () => false; + }); + return response; + } + + const logger = options.logger === true ? createDefaultLogger(levels) : options.logger; + + levels.forEach(level => { + response[level] = (data, message, ...args) => { + module.exports._logFunc(logger, level, defaults, data, message, ...args); + }; + }); + + return response; +}; + +/** + * Wrapper for creating a callback that either resolves or rejects a promise + * based on input + * + * @param {Function} resolve Function to run if callback is called + * @param {Function} reject Function to run if callback ends with an error + */ +module.exports.callbackPromise = (resolve, reject) => + function () { + const args = Array.from(arguments); + const err = args.shift(); + if (err) { + reject(err); + } else { + resolve(...args); + } + }; + +module.exports.parseDataURI = uri => { + if (typeof uri !== 'string') { + return null; + } + + // Early return for non-data URIs to avoid unnecessary processing + if (!uri.startsWith('data:')) { + return null; + } + + // Find the first comma safely - this prevents ReDoS + const commaPos = uri.indexOf(','); + if (commaPos === -1) { + return null; + } + + const data = uri.substring(commaPos + 1); + const metaStr = uri.substring('data:'.length, commaPos); + + let encoding; + const metaEntries = metaStr.split(';'); + + if (metaEntries.length > 0) { + const lastEntry = metaEntries[metaEntries.length - 1].toLowerCase().trim(); + // Only recognize valid encoding types to prevent manipulation + if (['base64', 'utf8', 'utf-8'].includes(lastEntry) && lastEntry.indexOf('=') === -1) { + encoding = lastEntry; + metaEntries.pop(); + } + } + + const contentType = metaEntries.length > 0 ? metaEntries.shift() : 'application/octet-stream'; + const params = {}; + + for (let i = 0; i < metaEntries.length; i++) { + const entry = metaEntries[i]; + const sepPos = entry.indexOf('='); + if (sepPos > 0) { + // Ensure there's a key before the '=' + const key = entry.substring(0, sepPos).trim(); + const value = entry.substring(sepPos + 1).trim(); + if (key) { + params[key] = value; + } + } + } + + // Decode data based on encoding with proper error handling + let bufferData; + try { + if (encoding === 'base64') { + bufferData = Buffer.from(data, 'base64'); + } else { + try { + bufferData = Buffer.from(decodeURIComponent(data)); + } catch (_decodeError) { + bufferData = Buffer.from(data); + } + } + } catch (_bufferError) { + bufferData = Buffer.alloc(0); + } + + return { + data: bufferData, + encoding: encoding || null, + contentType: contentType || 'application/octet-stream', + params + }; +}; + +/** + * Resolves a String or a Buffer value for content value. Useful if the value + * is a Stream or a file or an URL. If the value is a Stream, overwrites + * the stream object with the resolved value (you can't stream a value twice). + * + * This is useful when you want to create a plugin that needs a content value, + * for example the `html` or `text` value as a String or a Buffer but not as + * a file path or an URL. + * + * @param {Object} data An object or an Array you want to resolve an element for + * @param {String|Number} key Property name or an Array index + * @param {Object} [options] Optional access policy: { disableFileAccess, disableUrlAccess } + * @param {Function} callback Callback function with (err, value) + */ +module.exports.resolveContent = (data, key, options, callback) => { + // options is optional; support the legacy resolveContent(data, key, callback) signature + if (!callback && typeof options === 'function') { + callback = options; + options = false; + } + options = options || {}; + + let promise; + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = module.exports.callbackPromise(resolve, reject); + }); + } + + resolveContentValue(data, key, options, callback); + + return promise; +}; + +function resolveContentValue(data, key, options, callback) { + let content = (data && data[key] && data[key].content) || data[key]; + const encoding = ((typeof data[key] === 'object' && data[key].encoding) || 'utf8') + .toString() + .toLowerCase() + .replace(/[-_\s]/g, ''); + + if (!content) { + return callback(null, content); + } + + if (typeof content === 'object') { + if (typeof content.pipe === 'function') { + return resolveStream(content, (err, value) => { + if (err) { + return callback(err); + } + // we can't stream twice the same content, so we need + // to replace the stream object with the streaming result + if (data[key].content) { + data[key].content = value; + } else { + data[key] = value; + } + callback(null, value); + }); + } else if (/^https?:\/\//i.test(content.path || content.href)) { + if (options.disableUrlAccess) { + return setImmediate(() => { + const err = new Error('Url access rejected for ' + (content.path || content.href)); + err.code = errors.EURLACCESS; + callback(err); + }); + } + return resolveStream(nmfetch(content.path || content.href), callback); + } else if (/^data:/i.test(content.path || content.href)) { + const parsedDataUri = module.exports.parseDataURI(content.path || content.href); + + return callback(null, parsedDataUri && parsedDataUri.data ? parsedDataUri.data : Buffer.alloc(0)); + } else if (content.path) { + if (options.disableFileAccess) { + return setImmediate(() => { + const err = new Error('File access rejected for ' + content.path); + err.code = errors.EFILEACCESS; + callback(err); + }); + } + return resolveStream(fs.createReadStream(content.path), callback); + } + } + + if (typeof data[key].content === 'string' && !['utf8', 'usascii', 'ascii'].includes(encoding)) { + content = Buffer.from(data[key].content, encoding); + } + + // default action, return as is + setImmediate(() => callback(null, content)); +} + +/** + * Copies properties from source objects to target objects + */ +module.exports.assign = function (/* target, ... sources */) { + const args = Array.from(arguments); + const target = args.shift() || {}; + + args.forEach(source => { + Object.keys(source || {}).forEach(key => { + if (['tls', 'auth'].includes(key) && source[key] && typeof source[key] === 'object') { + // tls and auth are special keys that need to be enumerated separately + // other objects are passed as is + target[key] = Object.assign(target[key] || {}, source[key]); + } else { + target[key] = source[key]; + } + }); + }); + return target; +}; + +module.exports.encodeXText = str => { + // ! 0x21 + // + 0x2B + // = 0x3D + // ~ 0x7E + if (!/[^\x21-\x2A\x2C-\x3C\x3E-\x7E]/.test(str)) { + return str; + } + const buf = Buffer.from(str); + let result = ''; + for (let i = 0, len = buf.length; i < len; i++) { + const c = buf[i]; + if (c < 0x21 || c > 0x7e || c === 0x2b || c === 0x3d) { + result += '+' + (c < 0x10 ? '0' : '') + c.toString(16).toUpperCase(); + } else { + result += String.fromCharCode(c); + } + } + return result; +}; + +/** + * Streams a stream value into a Buffer + * + * @param {Object} stream Readable stream + * @param {Function} callback Callback function with (err, value) + */ +function resolveStream(stream, callback) { + let responded = false; + const chunks = []; + let chunklen = 0; + + stream.on('error', err => { + if (responded) { + return; + } + + responded = true; + callback(err); + }); + + stream.on('readable', () => { + let chunk; + while ((chunk = stream.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; + } + }); + + stream.on('end', () => { + if (responded) { + return; + } + responded = true; + + let value; + + try { + value = Buffer.concat(chunks, chunklen); + } catch (E) { + return callback(E); + } + callback(null, value); + }); +} + +/** + * Generates a bunyan-like logger that prints to console + * + * @returns {Object} Bunyan logger instance + */ +function createDefaultLogger(levels) { + const levelMaxLen = levels.reduce((max, level) => Math.max(max, level.length), 0); + const levelNames = new Map(); + + levels.forEach(level => { + let levelName = level.toUpperCase(); + if (levelName.length < levelMaxLen) { + levelName += ' '.repeat(levelMaxLen - levelName.length); + } + levelNames.set(level, levelName); + }); + + const print = (level, entry, message, ...args) => { + let prefix = ''; + if (entry) { + if (entry.tnx === 'server') { + prefix = 'S: '; + } else if (entry.tnx === 'client') { + prefix = 'C: '; + } + + if (entry.sid) { + prefix = '[' + entry.sid + '] ' + prefix; + } + + if (entry.cid) { + prefix = '[#' + entry.cid + '] ' + prefix; + } + } + + message = util.format(message, ...args); + message.split(/\r?\n/).forEach(line => { + console.log('[%s] %s %s', new Date().toISOString().substr(0, 19).replace(/T/, ' '), levelNames.get(level), prefix + line); + }); + }; + + const logger = {}; + levels.forEach(level => { + logger[level] = print.bind(null, level); + }); + + return logger; +} diff --git a/node_modules/nodemailer/lib/smtp-connection/data-stream.js b/node_modules/nodemailer/lib/smtp-connection/data-stream.js new file mode 100644 index 0000000000000000000000000000000000000000..d8fe1c67cdbb0f56d5fa904d2d19542d10f91eff --- /dev/null +++ b/node_modules/nodemailer/lib/smtp-connection/data-stream.js @@ -0,0 +1,105 @@ +'use strict'; + +const { Transform } = require('stream'); + +/** + * Escapes dots in the beginning of lines. Ends the stream with . + * Also makes sure that only sequences are used for linebreaks + * + * @param {Object} options Stream options + */ +class DataStream extends Transform { + constructor(options) { + super(options); + this.options = options || {}; + + this.inByteCount = 0; + this.outByteCount = 0; + this.lastByte = false; + } + + /** + * Escapes dots + */ + _transform(chunk, encoding, done) { + const chunks = []; + let chunklen = 0; + let i, + len, + lastPos = 0; + let buf; + + if (!chunk || !chunk.length) { + return done(); + } + + if (typeof chunk === 'string') { + chunk = Buffer.from(chunk); + } + + this.inByteCount += chunk.length; + + for (i = 0, len = chunk.length; i < len; i++) { + if (chunk[i] === 0x2e) { + // . + if ((i && chunk[i - 1] === 0x0a) || (!i && (!this.lastByte || this.lastByte === 0x0a))) { + buf = chunk.slice(lastPos, i + 1); + chunks.push(buf); + chunks.push(Buffer.from('.')); + chunklen += buf.length + 1; + lastPos = i + 1; + } + } else if (chunk[i] === 0x0a) { + // \n + if ((i && chunk[i - 1] !== 0x0d) || (!i && this.lastByte !== 0x0d)) { + if (i > lastPos) { + buf = chunk.slice(lastPos, i); + chunks.push(buf); + chunklen += buf.length + 2; + } else { + chunklen += 2; + } + chunks.push(Buffer.from('\r\n')); + lastPos = i + 1; + } + } + } + + if (chunklen) { + // add last piece + if (lastPos < chunk.length) { + buf = chunk.slice(lastPos); + chunks.push(buf); + chunklen += buf.length; + } + + this.outByteCount += chunklen; + this.push(Buffer.concat(chunks, chunklen)); + } else { + this.outByteCount += chunk.length; + this.push(chunk); + } + + this.lastByte = chunk[chunk.length - 1]; + done(); + } + + /** + * Finalizes the stream with a dot on a single line + */ + _flush(done) { + let buf; + if (this.lastByte === 0x0a) { + buf = Buffer.from('.\r\n'); + } else if (this.lastByte === 0x0d) { + buf = Buffer.from('\n.\r\n'); + } else { + buf = Buffer.from('\r\n.\r\n'); + } + this.outByteCount += buf.length; + this.push(buf); + done(); + } +} + +module.exports = DataStream; diff --git a/node_modules/nodemailer/lib/smtp-connection/http-proxy-client.js b/node_modules/nodemailer/lib/smtp-connection/http-proxy-client.js new file mode 100644 index 0000000000000000000000000000000000000000..36cd4bd8dffa79cc56decdbddab747b6ed319deb --- /dev/null +++ b/node_modules/nodemailer/lib/smtp-connection/http-proxy-client.js @@ -0,0 +1,144 @@ +'use strict'; + +/** + * Minimal HTTP/S proxy client + */ + +const net = require('net'); +const tls = require('tls'); +const urllib = require('url'); +const errors = require('../errors'); + +/** + * Establishes proxied connection to destinationPort + * + * httpProxyClient("http://localhost:3128/", 80, "google.com", function(err, socket){ + * socket.write("GET / HTTP/1.0\r\n\r\n"); + * }); + * + * @param {String} proxyUrl proxy configuration, etg "http://proxy.host:3128/" + * @param {Number} destinationPort Port to open in destination host + * @param {String} destinationHost Destination hostname + * @param {Function} callback Callback to run with the rocket object once connection is established + */ +function httpProxyClient(proxyUrl, destinationPort, destinationHost, callback) { + const proxy = urllib.parse(proxyUrl); + + const options = { + host: proxy.hostname, + port: Number(proxy.port) ? Number(proxy.port) : proxy.protocol === 'https:' ? 443 : 80 + }; + + let connect; + if (proxy.protocol === 'https:') { + // we can use untrusted proxies as long as we verify actual SMTP certificates + options.rejectUnauthorized = false; + connect = tls.connect.bind(tls); + } else { + connect = net.connect.bind(net); + } + + let socket; + + // Error harness for initial connection. Once connection is established, the responsibility + // to handle errors is passed to whoever uses this socket + let finished = false; + const tempSocketErr = err => { + if (finished) { + return; + } + finished = true; + try { + socket.destroy(); + } catch (_E) { + // ignore + } + callback(err); + }; + + const timeoutErr = () => { + const err = new Error('Proxy socket timed out'); + err.code = 'ETIMEDOUT'; + tempSocketErr(err); + }; + + socket = connect(options, () => { + if (finished) { + return; + } + + const reqHeaders = { + Host: destinationHost + ':' + destinationPort, + Connection: 'close' + }; + if (proxy.auth) { + reqHeaders['Proxy-Authorization'] = 'Basic ' + Buffer.from(proxy.auth).toString('base64'); + } + + socket.write( + // HTTP method + 'CONNECT ' + + destinationHost + + ':' + + destinationPort + + ' HTTP/1.1\r\n' + + // HTTP request headers + Object.keys(reqHeaders) + .map(key => key + ': ' + reqHeaders[key]) + .join('\r\n') + + // End request + '\r\n\r\n' + ); + + let headers = ''; + const onSocketData = chunk => { + let match; + let remainder; + + if (finished) { + return; + } + + headers += chunk.toString('binary'); + if ((match = headers.match(/\r\n\r\n/))) { + socket.removeListener('data', onSocketData); + + remainder = headers.substr(match.index + match[0].length); + headers = headers.substr(0, match.index); + if (remainder) { + socket.unshift(Buffer.from(remainder, 'binary')); + } + + // proxy connection is now established + finished = true; + + // check response code + match = headers.match(/^HTTP\/\d+\.\d+ (\d+)/i); + if (!match || (match[1] || '').charAt(0) !== '2') { + try { + socket.destroy(); + } catch (_E) { + // ignore + } + const err = new Error('Invalid response from proxy' + ((match && ': ' + match[1]) || '')); + err.code = errors.EPROXY; + return callback(err); + } + + socket.removeListener('error', tempSocketErr); + socket.removeListener('timeout', timeoutErr); + socket.setTimeout(0); + + return callback(null, socket); + } + }; + socket.on('data', onSocketData); + }); + + socket.setTimeout(httpProxyClient.timeout || 30 * 1000); + socket.on('timeout', timeoutErr); + + socket.once('error', tempSocketErr); +} + +module.exports = httpProxyClient; diff --git a/node_modules/nodemailer/lib/smtp-connection/index.js b/node_modules/nodemailer/lib/smtp-connection/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c201529ceb9c37d965b125474b6f618446810269 --- /dev/null +++ b/node_modules/nodemailer/lib/smtp-connection/index.js @@ -0,0 +1,1959 @@ +'use strict'; + +const packageInfo = require('../../package.json'); +const { EventEmitter } = require('events'); +const net = require('net'); +const tls = require('tls'); +const os = require('os'); +const crypto = require('crypto'); +const DataStream = require('./data-stream'); +const { PassThrough } = require('stream'); +const shared = require('../shared'); + +// default timeout values in ms +const CONNECTION_TIMEOUT = 2 * 60 * 1000; // how much to wait for the connection to be established +const SOCKET_TIMEOUT = 10 * 60 * 1000; // how much to wait for socket inactivity before disconnecting the client +const GREETING_TIMEOUT = 30 * 1000; // how much to wait after connection is established but SMTP greeting is not receieved +const DNS_TIMEOUT = 30 * 1000; // how much to wait for resolveHostname +const TEARDOWN_NOOP = () => {}; // reusable no-op handler for absorbing errors during socket teardown + +/** + * Re-interpret a server response stored in fake 8-bit byte-container form + * (the result of chunk.toString('binary') in _onData) as UTF-8. + * + * Server reply text has no formally defined charset (RFC 5321 §4.2.1), but + * modern MTAs commonly use UTF-8. The byte-container plumbing in _onData is + * required to reassemble multi-byte sequences split across socket chunks; + * this helper performs the actual decode at the line boundary, falling back + * to the byte-container form when the bytes are not valid UTF-8 so that + * legacy 8-bit replies are still recoverable byte-for-byte. + */ +function decodeServerResponse(str) { + if (!str) { + return str; + } + const utf8 = Buffer.from(str, 'binary').toString('utf8'); + // The input is a byte container (each char is in U+0000..U+00FF) so it can never + // already contain U+FFFD; any \uFFFD in the result was inserted by Node's UTF-8 + // decoder for invalid bytes, which means we should return the original bytes intact. + return utf8.includes('\uFFFD') ? str : utf8; +} + +/** + * Generates a SMTP connection object + * + * Optional options object takes the following possible properties: + * + * * **port** - is the port to connect to (defaults to 587 or 465) + * * **host** - is the hostname or IP address to connect to (defaults to 'localhost') + * * **secure** - use SSL + * * **ignoreTLS** - ignore server support for STARTTLS + * * **requireTLS** - forces the client to use STARTTLS + * * **name** - the name of the client server + * * **localAddress** - outbound address to bind to (see: http://nodejs.org/api/net.html#net_net_connect_options_connectionlistener) + * * **greetingTimeout** - Time to wait in ms until greeting message is received from the server (defaults to 30 seconds) + * * **connectionTimeout** - how many milliseconds to wait for the connection to establish (defaults to 2 minutes) + * * **socketTimeout** - Time of inactivity until the connection is closed (defaults to 10 minutes) + * * **dnsTimeout** - Time to wait in ms for the DNS requests to be resolved (defaults to 30 seconds) + * * **lmtp** - if true, uses LMTP instead of SMTP protocol + * * **logger** - bunyan compatible logger interface + * * **debug** - if true pass SMTP traffic to the logger + * * **tls** - options for createCredentials + * * **socket** - existing socket to use instead of creating a new one (see: http://nodejs.org/api/net.html#net_class_net_socket) + * * **secured** - boolean indicates that the provided socket has already been upgraded to tls + * + * @constructor + * @namespace SMTP Client module + * @param {Object} [options] Option properties + */ +class SMTPConnection extends EventEmitter { + constructor(options) { + super(options); + + this.id = crypto.randomBytes(8).toString('base64').replace(/\W/g, ''); + this.stage = 'init'; + + this.options = options || {}; + + this.secureConnection = !!this.options.secure; + this.alreadySecured = !!this.options.secured; + + this.port = Number(this.options.port) || (this.secureConnection ? 465 : 587); + this.host = this.options.host || 'localhost'; + + this.servername = this.options.servername ? this.options.servername : !net.isIP(this.host) ? this.host : false; + + this.allowInternalNetworkInterfaces = this.options.allowInternalNetworkInterfaces || false; + + if (typeof this.options.secure === 'undefined' && this.port === 465) { + // if secure option is not set but port is 465, then default to secure + this.secureConnection = true; + } + + this.name = (this.options.name || this._getHostname()).toString().replace(/[\r\n]+/g, ''); + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'smtp-connection', + sid: this.id + }); + + this.customAuth = new Map(); + for (const key of Object.keys(this.options.customAuth || {})) { + const mapKey = (key || '').toString().trim().toUpperCase(); + if (mapKey) { + this.customAuth.set(mapKey, this.options.customAuth[key]); + } + } + + /** + * Expose version nr, just for the reference + * @type {String} + */ + this.version = packageInfo.version; + + /** + * If true, then the user is authenticated + * @type {Boolean} + */ + this.authenticated = false; + + /** + * If set to true, this instance is no longer active + * @private + */ + this.destroyed = false; + + /** + * Defines if the current connection is secure or not. If not, + * STARTTLS can be used if available + * @private + */ + this.secure = !!this.secureConnection; + + /** + * Store incomplete messages coming from the server + * @private + */ + this._remainder = ''; + + /** + * Unprocessed responses from the server + * @type {Array} + */ + this._responseQueue = []; + + this.lastServerResponse = false; + + /** + * The socket connecting to the server + * @public + */ + this._socket = false; + + /** + * Lists supported auth mechanisms + * @private + */ + this._supportedAuth = []; + + /** + * Set to true, if EHLO response includes "AUTH". + * If false then authentication is not tried + */ + this.allowsAuth = false; + + /** + * Includes current envelope (from, to) + * @private + */ + this._envelope = false; + + /** + * Lists supported extensions + * @private + */ + this._supportedExtensions = []; + + /** + * Defines the maximum allowed size for a single message + * @private + */ + this._maxAllowedSize = 0; + + /** + * Function queue to run if a data chunk comes from the server + * @private + */ + this._responseActions = []; + this._recipientQueue = []; + + /** + * Timeout variable for waiting the greeting + * @private + */ + this._greetingTimeout = false; + + /** + * Timeout variable for waiting the connection to start + * @private + */ + this._connectionTimeout = false; + + /** + * If the socket is deemed already closed + * @private + */ + this._destroyed = false; + + /** + * If the socket is already being closed + * @private + */ + this._closing = false; + + /** + * Message DATA stream currently piped to the socket, if any. Tracked so + * close() can unpipe it before tearing the socket down. + * @private + */ + this._currentDataStream = false; + + /** + * Callbacks for socket's listeners + */ + this._onSocketData = chunk => this._onData(chunk); + this._onSocketError = error => this._onError(error, 'ESOCKET', false, 'CONN'); + this._onSocketClose = () => this._onClose(); + this._onSocketEnd = () => this._onEnd(); + this._onSocketTimeout = () => this._onTimeout(); + + /** + * Connection-phase error handler (supports fallback to alternative addresses) + */ + this._onConnectionSocketError = err => this._onConnectionError(err, 'ESOCKET'); + + /** + * Connection attempt counter for fallback race condition protection + * @private + */ + this._connectionAttemptId = 0; + } + + /** + * Creates a connection to a SMTP server and sets up connection + * listener + */ + connect(connectCallback) { + if (typeof connectCallback === 'function') { + this.once('connect', () => { + this.logger.debug( + { + tnx: 'smtp' + }, + 'SMTP handshake finished' + ); + connectCallback(); + }); + + const isDestroyedMessage = this._isDestroyedMessage('connect'); + if (isDestroyedMessage) { + return connectCallback(this._formatError(isDestroyedMessage, 'ECONNECTION', false, 'CONN')); + } + } + + let opts = { + port: this.port, + host: this.host, + allowInternalNetworkInterfaces: this.allowInternalNetworkInterfaces, + timeout: this.options.dnsTimeout || DNS_TIMEOUT + }; + + if (this.options.localAddress) { + opts.localAddress = this.options.localAddress; + } + + if (this.options.connection) { + // connection is already opened + this._socket = this.options.connection; + this._setupConnectionHandlers(); + + if (this.secureConnection && !this.alreadySecured) { + setImmediate(() => + this._upgradeConnection(err => { + if (err) { + this._onError(new Error('Error initiating TLS - ' + (err.message || err)), 'ETLS', false, 'CONN'); + return; + } + this._onConnect(); + }) + ); + } else { + setImmediate(() => this._onConnect()); + } + return; + } else if (this.options.socket) { + // socket object is set up but not yet connected + this._socket = this.options.socket; + return this._resolveAndConnect(opts, _resolved => { + try { + this._socket.connect(this.port, this.host, () => { + this._socket.setKeepAlive(true); + this._onConnect(); + }); + this._setupConnectionHandlers(); + } catch (E) { + return setImmediate(() => this._onError(E, 'ECONNECTION', false, 'CONN')); + } + }); + } else { + if (this.secureConnection) { + Object.assign(opts, this.options.tls || {}); + + // ensure servername for SNI + if (this.servername && !opts.servername) { + opts.servername = this.servername; + } + } + + return this._resolveAndConnect(opts, resolved => { + // Store fallback addresses for retry on connection failure + this._fallbackAddresses = (resolved._addresses || []).filter(addr => addr !== opts.host); + this._connectOpts = Object.assign({}, opts); + + this._connectToHost(opts, this.secureConnection); + }); + } + } + + /** + * Resolves the hostname and applies resolved values to opts, + * then calls the provided callback with the resolved data + * + * @param {Object} opts Connection options (modified in place) + * @param {Function} callback Called with resolved data on success + */ + _resolveAndConnect(opts, callback) { + return shared.resolveHostname(opts, (err, resolved) => { + if (err) { + return setImmediate(() => this._onError(err, 'EDNS', false, 'CONN')); + } + this.logger.debug( + { + tnx: 'dns', + source: opts.host, + resolved: resolved.host, + cached: !!resolved.cached + }, + 'Resolved %s as %s [cache %s]', + opts.host, + resolved.host, + resolved.cached ? 'hit' : 'miss' + ); + for (const key of Object.keys(resolved)) { + if (key.charAt(0) !== '_' && resolved[key]) { + opts[key] = resolved[key]; + } + } + callback(resolved); + }); + } + + /** + * Attempts to connect to the specified host address + * + * @param {Object} opts Connection options + * @param {Boolean} secure Whether to use TLS + */ + _connectToHost(opts, secure) { + this._connectionAttemptId++; + const currentAttemptId = this._connectionAttemptId; + + const connectFn = secure ? tls.connect : net.connect; + try { + this._socket = connectFn(opts, () => { + // Ignore callback if this is a stale connection attempt + if (this._connectionAttemptId !== currentAttemptId) { + return; + } + this._socket.setKeepAlive(true); + this._onConnect(); + }); + this._setupConnectionHandlers(); + } catch (E) { + return setImmediate(() => this._onError(E, 'ECONNECTION', false, 'CONN')); + } + } + + /** + * Sets up connection timeout and error handlers + */ + _setupConnectionHandlers() { + this._connectionTimeout = setTimeout(() => { + this._onConnectionError('Connection timeout', 'ETIMEDOUT'); + }, this.options.connectionTimeout || CONNECTION_TIMEOUT); + + this._socket.on('error', this._onConnectionSocketError); + } + + /** + * Handles connection errors with fallback to alternative addresses + * + * @param {Error|String} err Error object or message + * @param {String} code Error code + */ + _onConnectionError(err, code) { + clearTimeout(this._connectionTimeout); + + // Check if we have fallback addresses to try + const canFallback = this._fallbackAddresses && this._fallbackAddresses.length && this.stage === 'init' && !this._destroyed; + + if (!canFallback) { + // No more fallback addresses, report the error + this._onError(err, code, false, 'CONN'); + return; + } + + const nextHost = this._fallbackAddresses.shift(); + + this.logger.info( + { + tnx: 'network', + failedHost: this._connectOpts.host, + nextHost, + error: err.message || err + }, + 'Connection to %s failed, trying %s', + this._connectOpts.host, + nextHost + ); + + // Clean up current socket + if (this._socket) { + try { + this._socket.removeListener('error', this._onConnectionSocketError); + this._socket.destroy(); + } catch (_E) { + // ignore + } + this._socket = null; + } + + // Update host and retry + this._connectOpts.host = nextHost; + this._connectToHost(this._connectOpts, this.secureConnection); + } + + /** + * Sends QUIT + */ + quit() { + this._sendCommand('QUIT'); + this._responseActions.push(this.close); + } + + /** + * Closes the connection to the server + */ + close() { + clearTimeout(this._connectionTimeout); + clearTimeout(this._greetingTimeout); + this._responseActions = []; + + // allow to run this function only once + if (this._closing) { + return; + } + this._closing = true; + + const closeMethod = this.stage === 'init' ? 'destroy' : 'end'; + + this.logger.debug( + { + tnx: 'smtp' + }, + 'Closing connection to the server using "%s"', + closeMethod + ); + + const socket = (this._socket && this._socket.socket) || this._socket; + + // Detach any in-flight DATA stream from the socket so the source stream + // can be garbage-collected once the socket is gone. + if (this._currentDataStream) { + try { + this._currentDataStream.unpipe(this._socket); + } catch (_E) { + // ignore + } + this._currentDataStream = false; + } + + if (socket && !socket.destroyed) { + try { + // Clear socket timeout to prevent timer leaks + socket.setTimeout(0); + // Remove all listeners to allow proper garbage collection + socket.removeListener('data', this._onSocketData); + socket.removeListener('timeout', this._onSocketTimeout); + socket.removeListener('close', this._onSocketClose); + socket.removeListener('end', this._onSocketEnd); + socket.removeListener('error', this._onSocketError); + socket.removeListener('error', this._onConnectionSocketError); + // Absorb errors that may fire during socket teardown (e.g. server + // sending cleartext after TLS shutdown triggers ERR_SSL_BAD_RECORD_TYPE) + socket.on('error', TEARDOWN_NOOP); + socket[closeMethod](); + } catch (_E) { + // just ignore + } + } + + this._destroy(); + } + + /** + * Authenticate user + */ + login(authData, callback) { + const isDestroyedMessage = this._isDestroyedMessage('login'); + if (isDestroyedMessage) { + return callback(this._formatError(isDestroyedMessage, 'ECONNECTION', false, 'API')); + } + + this._auth = authData || {}; + // Select SASL authentication method + this._authMethod = (this._auth.method || '').toString().trim().toUpperCase() || false; + + if (!this._authMethod && this._auth.oauth2 && !this._auth.credentials) { + this._authMethod = 'XOAUTH2'; + } else if (!this._authMethod || (this._authMethod === 'XOAUTH2' && !this._auth.oauth2)) { + // use first supported + this._authMethod = (this._supportedAuth[0] || 'PLAIN').toUpperCase().trim(); + } + + if (this._authMethod !== 'XOAUTH2' && (!this._auth.credentials || !this._auth.credentials.user || !this._auth.credentials.pass)) { + if ((this._auth.user && this._auth.pass) || this.customAuth.has(this._authMethod)) { + this._auth.credentials = { + user: this._auth.user, + pass: this._auth.pass, + options: this._auth.options + }; + } else { + return callback(this._formatError('Missing credentials for "' + this._authMethod + '"', 'EAUTH', false, 'API')); + } + } + + if (this.customAuth.has(this._authMethod)) { + const handler = this.customAuth.get(this._authMethod); + let lastResponse; + let returned = false; + + const resolve = () => { + if (returned) { + return; + } + returned = true; + this.logger.info( + { + tnx: 'smtp', + username: this._auth.user, + action: 'authenticated', + method: this._authMethod + }, + 'User %s authenticated', + JSON.stringify(this._auth.user) + ); + this.authenticated = true; + callback(null, true); + }; + + const reject = err => { + if (returned) { + return; + } + returned = true; + callback(this._formatError(err, 'EAUTH', lastResponse, 'AUTH ' + this._authMethod)); + }; + + const handlerResponse = handler({ + auth: this._auth, + method: this._authMethod, + + extensions: [].concat(this._supportedExtensions), + authMethods: [].concat(this._supportedAuth), + maxAllowedSize: this._maxAllowedSize || false, + + sendCommand: (cmd, done) => { + let promise; + + if (!done) { + promise = new Promise((resolve, reject) => { + done = shared.callbackPromise(resolve, reject); + }); + } + + this._responseActions.push(str => { + lastResponse = str; + + let codes = str.match(/^(\d+)(?:\s(\d+\.\d+\.\d+))?\s/); + let data = { + command: cmd, + response: str + }; + if (codes) { + data.status = Number(codes[1]) || 0; + if (codes[2]) { + data.code = codes[2]; + } + data.text = str.substr(codes[0].length); + } else { + data.text = str; + data.status = 0; // just in case we need to perform numeric comparisons + } + done(null, data); + }); + setImmediate(() => this._sendCommand(cmd)); + + return promise; + }, + + resolve, + reject + }); + + if (handlerResponse && typeof handlerResponse.catch === 'function') { + // a promise was returned + handlerResponse.then(resolve).catch(reject); + } + + return; + } + + switch (this._authMethod) { + case 'XOAUTH2': + this._handleXOauth2Token(false, callback); + return; + case 'LOGIN': + this._responseActions.push(str => { + this._actionAUTH_LOGIN_USER(str, callback); + }); + this._sendCommand('AUTH LOGIN'); + return; + case 'PLAIN': + this._responseActions.push(str => { + this._actionAUTHComplete(str, callback); + }); + this._sendCommand( + 'AUTH PLAIN ' + + Buffer.from( + //this._auth.user+'\u0000'+ + '\u0000' + // skip authorization identity as it causes problems with some servers + this._auth.credentials.user + + '\u0000' + + this._auth.credentials.pass, + 'utf-8' + ).toString('base64'), + // log entry without passwords + 'AUTH PLAIN ' + + Buffer.from( + //this._auth.user+'\u0000'+ + '\u0000' + // skip authorization identity as it causes problems with some servers + this._auth.credentials.user + + '\u0000' + + '/* secret */', + 'utf-8' + ).toString('base64') + ); + return; + case 'CRAM-MD5': + this._responseActions.push(str => { + this._actionAUTH_CRAM_MD5(str, callback); + }); + this._sendCommand('AUTH CRAM-MD5'); + return; + } + + return callback(this._formatError('Unknown authentication method "' + this._authMethod + '"', 'EAUTH', false, 'API')); + } + + /** + * Sends a message + * + * @param {Object} envelope Envelope object, {from: addr, to: [addr]} + * @param {Object} message String, Buffer or a Stream + * @param {Function} callback Callback to return once sending is completed + */ + send(envelope, message, done) { + if (!message) { + return done(this._formatError('Empty message', 'EMESSAGE', false, 'API')); + } + + const isDestroyedMessage = this._isDestroyedMessage('send message'); + if (isDestroyedMessage) { + return done(this._formatError(isDestroyedMessage, 'ECONNECTION', false, 'API')); + } + + // reject larger messages than allowed + if (this._maxAllowedSize && envelope.size > this._maxAllowedSize) { + return setImmediate(() => { + done(this._formatError('Message size larger than allowed ' + this._maxAllowedSize, 'EMESSAGE', false, 'MAIL FROM')); + }); + } + + // ensure that callback is only called once + let returned = false; + const callback = function () { + if (returned) { + return; + } + returned = true; + + done(...arguments); + }; + + if (typeof message.on === 'function') { + message.on('error', err => callback(this._formatError(err, 'ESTREAM', false, 'API'))); + } + + const startTime = Date.now(); + this._setEnvelope(envelope, (err, info) => { + if (err) { + // create passthrough stream to consume to prevent OOM + const stream = new PassThrough(); + if (typeof message.pipe === 'function') { + message.pipe(stream); + } else { + stream.write(message); + stream.end(); + } + + return callback(err); + } + const envelopeTime = Date.now(); + const stream = this._createSendStream((err, str) => { + if (err) { + return callback(err); + } + + info.envelopeTime = envelopeTime - startTime; + info.messageTime = Date.now() - envelopeTime; + info.messageSize = stream.outByteCount; + info.response = str; + + return callback(null, info); + }); + if (typeof message.pipe === 'function') { + message.pipe(stream); + } else { + stream.write(message); + stream.end(); + } + }); + } + + /** + * Resets connection state + * + * @param {Function} callback Callback to return once connection is reset + */ + reset(callback) { + this._sendCommand('RSET'); + this._responseActions.push(str => { + if (str.charAt(0) !== '2') { + return callback(this._formatError('Could not reset session state. response=' + str, 'EPROTOCOL', str, 'RSET')); + } + this._envelope = false; + return callback(null, true); + }); + } + + /** + * Connection listener that is run when the connection to + * the server is opened + * + * @event + */ + _onConnect() { + clearTimeout(this._connectionTimeout); + + this.logger.info( + { + tnx: 'network', + localAddress: this._socket.localAddress, + localPort: this._socket.localPort, + remoteAddress: this._socket.remoteAddress, + remotePort: this._socket.remotePort + }, + '%s established to %s:%s', + this.secure ? 'Secure connection' : 'Connection', + this._socket.remoteAddress, + this._socket.remotePort + ); + + if (this._destroyed) { + // Connection was established after we already had canceled it + this.close(); + return; + } + + this.stage = 'connected'; + + // clear existing listeners for the socket + this._socket.removeListener('data', this._onSocketData); + this._socket.removeListener('timeout', this._onSocketTimeout); + this._socket.removeListener('close', this._onSocketClose); + this._socket.removeListener('end', this._onSocketEnd); + // Switch from connection-phase error handler to normal error handler + this._socket.removeListener('error', this._onConnectionSocketError); + + this._socket.on('error', this._onSocketError); + this._socket.on('data', this._onSocketData); + this._socket.once('close', this._onSocketClose); + this._socket.once('end', this._onSocketEnd); + + this._socket.setTimeout(this.options.socketTimeout || SOCKET_TIMEOUT); + this._socket.on('timeout', this._onSocketTimeout); + + this._greetingTimeout = setTimeout(() => { + // if still waiting for greeting, give up + if (this._socket && !this._destroyed && this._responseActions[0] === this._actionGreeting) { + this._onError('Greeting never received', 'ETIMEDOUT', false, 'CONN'); + } + }, this.options.greetingTimeout || GREETING_TIMEOUT); + + this._responseActions.push(this._actionGreeting); + + // we have a 'data' listener set up so resume socket if it was paused + this._socket.resume(); + } + + /** + * 'data' listener for data coming from the server + * + * @event + * @param {Buffer} chunk Data chunk coming from the server + */ + _onData(chunk) { + if (this._destroyed || !chunk || !chunk.length) { + return; + } + + let data = chunk.toString('binary'); + let lines = (this._remainder + data).split(/\r?\n/); + let lastline; + + this._remainder = lines.pop(); + + for (let i = 0, len = lines.length; i < len; i++) { + if (this._responseQueue.length) { + lastline = this._responseQueue[this._responseQueue.length - 1]; + if (/^\d+-/.test(lastline.split('\n').pop())) { + this._responseQueue[this._responseQueue.length - 1] += '\n' + lines[i]; + continue; + } + } + this._responseQueue.push(lines[i]); + } + + if (this._responseQueue.length) { + lastline = this._responseQueue[this._responseQueue.length - 1]; + if (/^\d+-/.test(lastline.split('\n').pop())) { + return; + } + } + + this._processResponse(); + } + + /** + * 'error' listener for the socket + * + * @event + * @param {Error} err Error object + * @param {String} type Error name + */ + _onError(err, type, data, command) { + clearTimeout(this._connectionTimeout); + clearTimeout(this._greetingTimeout); + + if (this._destroyed) { + // just ignore, already closed + // this might happen when a socket is canceled because of reached timeout + // but the socket timeout error itself receives only after + return; + } + + err = this._formatError(err, type, data, command); + + const transientCodes = ['ETIMEDOUT', 'ESOCKET', 'ECONNECTION']; + if (transientCodes.includes(err.code)) { + this.logger.warn(data, err.message); + } else { + this.logger.error(data, err.message); + } + + this.emit('error', err); + this.close(); + } + + _formatError(message, type, response, command) { + let err; + + if (/Error\]$/i.test(Object.prototype.toString.call(message))) { + err = message; + } else { + err = new Error(message); + } + + if (type && type !== 'Error') { + err.code = type; + } + + if (response) { + err.response = response; + err.message += ': ' + response; + } + + const responseCode = (typeof response === 'string' && Number((response.match(/^\d+/) || [])[0])) || false; + if (responseCode) { + err.responseCode = responseCode; + } + + if (command) { + err.command = command; + } + + return err; + } + + /** + * 'close' listener for the socket + * + * @event + */ + _onClose() { + let serverResponse = false; + + if (this._remainder && this._remainder.trim()) { + this.lastServerResponse = serverResponse = decodeServerResponse(this._remainder.trim()); + if (this.options.debug || this.options.transactionLog) { + this.logger.debug( + { + tnx: 'server' + }, + serverResponse + ); + } + } + + this.logger.info( + { + tnx: 'network' + }, + 'Connection closed' + ); + + if (this.upgrading && !this._destroyed) { + return this._onError(new Error('Connection closed unexpectedly'), 'ETLS', serverResponse, 'CONN'); + } else if (![this._actionGreeting, this.close].includes(this._responseActions[0]) && !this._destroyed) { + return this._onError(new Error('Connection closed unexpectedly'), 'ECONNECTION', serverResponse, 'CONN'); + } else if (/^[45]\d{2}\b/.test(serverResponse)) { + return this._onError(new Error('Connection closed unexpectedly'), 'ECONNECTION', serverResponse, 'CONN'); + } + + this._destroy(); + } + + /** + * 'end' listener for the socket + * + * @event + */ + _onEnd() { + if (this._socket && !this._socket.destroyed) { + // Peer sent FIN — finish our half of the close gracefully rather + // than destroying. 'close' fires after the OS finalizes teardown. + this._socket.end(); + } + } + + /** + * 'timeout' listener for the socket + * + * @event + */ + _onTimeout() { + return this._onError(new Error('Timeout'), 'ETIMEDOUT', false, 'CONN'); + } + + /** + * Destroys the client, emits 'end' + */ + _destroy() { + if (this._destroyed) { + return; + } + this._destroyed = true; + this.emit('end'); + } + + /** + * Upgrades the connection to TLS + * + * @param {Function} callback Callback function to run when the connection + * has been secured + */ + _upgradeConnection(callback) { + // do not remove all listeners or it breaks node v0.10 as there's + // apparently a 'finish' event set that would be cleared as well + + // we can safely keep 'error', 'end', 'close' etc. events + this._socket.removeListener('data', this._onSocketData); // incoming data is going to be gibberish from this point onwards + this._socket.removeListener('timeout', this._onSocketTimeout); // timeout will be re-set for the new socket object + + const socketPlain = this._socket; + const opts = Object.assign( + { + socket: this._socket, + host: this.host + }, + this.options.tls || {} + ); + + // ensure servername for SNI + if (this.servername && !opts.servername) { + opts.servername = this.servername; + } + + // Remove all listeners from the plain socket to allow proper garbage + // collection. Used on both the TLS-success path and the synchronous + // tls.connect() throw path; either way the plain socket is done. + const removePlainSocketListeners = () => { + socketPlain.removeListener('close', this._onSocketClose); + socketPlain.removeListener('end', this._onSocketEnd); + socketPlain.removeListener('error', this._onSocketError); + }; + + this.upgrading = true; + // tls.connect is not an asynchronous function however it may still throw errors and requires to be wrapped with try/catch + try { + this._socket = tls.connect(opts, () => { + this.secure = true; + this.upgrading = false; + this._socket.on('data', this._onSocketData); + + removePlainSocketListeners(); + + return callback(null, true); + }); + } catch (err) { + removePlainSocketListeners(); + return callback(err); + } + + this._socket.on('error', this._onSocketError); + this._socket.once('close', this._onSocketClose); + this._socket.once('end', this._onSocketEnd); + + this._socket.setTimeout(this.options.socketTimeout || SOCKET_TIMEOUT); // 10 min. + this._socket.on('timeout', this._onSocketTimeout); + + // resume in case the socket was paused + socketPlain.resume(); + } + + /** + * Processes queued responses from the server + * + * @param {Boolean} force If true, ignores _processing flag + */ + _processResponse() { + if (!this._responseQueue.length) { + return false; + } + + let str = (this.lastServerResponse = decodeServerResponse((this._responseQueue.shift() || '').toString())); + + if (/^\d+-/.test(str.split('\n').pop())) { + // keep waiting for the final part of multiline response + return; + } + + if (this.options.debug || this.options.transactionLog) { + this.logger.debug( + { + tnx: 'server' + }, + str.replace(/\r?\n$/, '') + ); + } + + if (!str.trim()) { + // skip unexpected empty lines + setImmediate(() => this._processResponse()); + } + + const action = this._responseActions.shift(); + + if (typeof action === 'function') { + action.call(this, str); + setImmediate(() => this._processResponse()); + } else { + return this._onError(new Error('Unexpected Response'), 'EPROTOCOL', str, 'CONN'); + } + } + + /** + * Send a command to the server, append \r\n + * + * @param {String} str String to be sent to the server + * @param {String} logStr Optional string to be used for logging instead of the actual string + */ + _sendCommand(str, logStr) { + if (this._destroyed) { + // Connection already closed, can't send any more data + return; + } + + if (this._socket.destroyed) { + return this.close(); + } + + if (this.options.debug || this.options.transactionLog) { + this.logger.debug( + { + tnx: 'client' + }, + (logStr || str || '').toString().replace(/\r?\n$/, '') + ); + } + + this._socket.write(Buffer.from(str + '\r\n', 'utf-8')); + } + + /** + * Initiates a new message by submitting envelope data, starting with + * MAIL FROM: command + * + * @param {Object} envelope Envelope object in the form of + * {from:'...', to:['...']} + * or + * {from:{address:'...',name:'...'}, to:[address:'...',name:'...']} + */ + _setEnvelope(envelope, callback) { + const args = []; + let useSmtpUtf8 = false; + + this._envelope = envelope || {}; + this._envelope.from = ((this._envelope.from && this._envelope.from.address) || this._envelope.from || '').toString().trim(); + + this._envelope.to = [].concat(this._envelope.to || []).map(to => ((to && to.address) || to || '').toString().trim()); + + if (!this._envelope.to.length) { + return callback(this._formatError('No recipients defined', 'EENVELOPE', false, 'API')); + } + + if (this._envelope.from && /[\r\n<>]/.test(this._envelope.from)) { + return callback(this._formatError('Invalid sender ' + JSON.stringify(this._envelope.from), 'EENVELOPE', false, 'API')); + } + + // check if the sender address uses only ASCII characters, + // otherwise require usage of SMTPUTF8 extension + if (/[\x80-\uFFFF]/.test(this._envelope.from)) { + useSmtpUtf8 = true; + } + + for (let i = 0, len = this._envelope.to.length; i < len; i++) { + if (!this._envelope.to[i] || /[\r\n<>]/.test(this._envelope.to[i])) { + return callback(this._formatError('Invalid recipient ' + JSON.stringify(this._envelope.to[i]), 'EENVELOPE', false, 'API')); + } + + // check if the recipients addresses use only ASCII characters, + // otherwise require usage of SMTPUTF8 extension + if (/[\x80-\uFFFF]/.test(this._envelope.to[i])) { + useSmtpUtf8 = true; + } + } + + // clone the recipients array for latter manipulation + this._envelope.rcptQueue = [].concat(this._envelope.to || []); + this._envelope.rejected = []; + this._envelope.rejectedErrors = []; + this._envelope.accepted = []; + + if (this._envelope.dsn) { + try { + this._envelope.dsn = this._setDsnEnvelope(this._envelope.dsn); + } catch (err) { + return callback(this._formatError('Invalid DSN ' + err.message, 'EENVELOPE', false, 'API')); + } + } + + this._responseActions.push(str => { + this._actionMAIL(str, callback); + }); + + // If the server supports SMTPUTF8 and the envelope includes an internationalized + // email address then append SMTPUTF8 keyword to the MAIL FROM command + if (useSmtpUtf8 && this._supportedExtensions.includes('SMTPUTF8')) { + args.push('SMTPUTF8'); + this._usingSmtpUtf8 = true; + } + + // If the server supports 8BITMIME and the message might contain non-ascii bytes + // then append the 8BITMIME keyword to the MAIL FROM command + if (this._envelope.use8BitMime && this._supportedExtensions.includes('8BITMIME')) { + args.push('BODY=8BITMIME'); + this._using8BitMime = true; + } + + if (this._envelope.size && this._supportedExtensions.includes('SIZE')) { + const sizeValue = Number(this._envelope.size) || 0; + if (sizeValue > 0) { + args.push('SIZE=' + sizeValue); + } + } + + // If the server supports DSN and the envelope includes an DSN prop + // then append DSN params to the MAIL FROM command + if (this._envelope.dsn && this._supportedExtensions.includes('DSN')) { + if (this._envelope.dsn.ret) { + args.push('RET=' + shared.encodeXText(this._envelope.dsn.ret)); + } + if (this._envelope.dsn.envid) { + args.push('ENVID=' + shared.encodeXText(this._envelope.dsn.envid)); + } + } + + // RFC 8689: If the envelope requests REQUIRETLS extension + // then append REQUIRETLS keyword to the MAIL FROM command + // Note: REQUIRETLS can only be used over TLS connections and requires server support + if (this._envelope.requireTLSExtensionEnabled) { + if (!this.secure) { + return callback( + this._formatError('REQUIRETLS can only be used over TLS connections (RFC 8689)', 'EREQUIRETLS', false, 'MAIL FROM') + ); + } + if (!this._supportedExtensions.includes('REQUIRETLS')) { + return callback( + this._formatError('Server does not support REQUIRETLS extension (RFC 8689)', 'EREQUIRETLS', false, 'MAIL FROM') + ); + } + args.push('REQUIRETLS'); + } + + this._sendCommand('MAIL FROM:<' + this._envelope.from + '>' + (args.length ? ' ' + args.join(' ') : '')); + } + + _setDsnEnvelope(params) { + let ret = (params.ret || params.return || '').toString().toUpperCase() || null; + if (ret) { + switch (ret) { + case 'HDRS': + case 'HEADERS': + ret = 'HDRS'; + break; + case 'FULL': + case 'BODY': + ret = 'FULL'; + break; + } + } + + if (ret && !['FULL', 'HDRS'].includes(ret)) { + throw new Error('ret: ' + JSON.stringify(ret)); + } + + const envid = (params.envid || params.id || '').toString() || null; + + let notify = params.notify || null; + if (notify) { + if (typeof notify === 'string') { + notify = notify.split(','); + } + notify = notify.map(n => n.trim().toUpperCase()); + const validNotify = ['NEVER', 'SUCCESS', 'FAILURE', 'DELAY']; + const invalidNotify = notify.filter(n => !validNotify.includes(n)); + if (invalidNotify.length || (notify.length > 1 && notify.includes('NEVER'))) { + throw new Error('notify: ' + JSON.stringify(notify.join(','))); + } + notify = notify.join(','); + } + + let orcpt = (params.recipient || params.orcpt || '').toString() || null; + if (orcpt && orcpt.indexOf(';') < 0) { + orcpt = 'rfc822;' + orcpt; + } + + return { + ret, + envid, + notify, + orcpt + }; + } + + _getDsnRcptToArgs() { + const args = []; + // If the server supports DSN and the envelope includes an DSN prop + // then append DSN params to the RCPT TO command + if (this._envelope.dsn && this._supportedExtensions.includes('DSN')) { + if (this._envelope.dsn.notify) { + args.push('NOTIFY=' + shared.encodeXText(this._envelope.dsn.notify)); + } + if (this._envelope.dsn.orcpt) { + args.push('ORCPT=' + shared.encodeXText(this._envelope.dsn.orcpt)); + } + } + return args.length ? ' ' + args.join(' ') : ''; + } + + _createSendStream(callback) { + const dataStream = new DataStream(); + + if (this.options.lmtp) { + this._envelope.accepted.forEach((recipient, i) => { + const final = i === this._envelope.accepted.length - 1; + this._responseActions.push(str => { + this._actionLMTPStream(recipient, final, str, callback); + }); + }); + } else { + this._responseActions.push(str => { + this._actionSMTPStream(str, callback); + }); + } + + this._currentDataStream = dataStream; + dataStream.pipe(this._socket, { + end: false + }); + + if (this.options.debug) { + const logStream = new PassThrough(); + logStream.on('readable', () => { + let chunk; + while ((chunk = logStream.read())) { + this.logger.debug( + { + tnx: 'message' + }, + chunk.toString('binary').replace(/\r?\n$/, '') + ); + } + }); + dataStream.pipe(logStream); + } + + dataStream.once('end', () => { + if (this._currentDataStream === dataStream) { + this._currentDataStream = false; + } + this.logger.info( + { + tnx: 'message', + inByteCount: dataStream.inByteCount, + outByteCount: dataStream.outByteCount + }, + '<%s bytes encoded mime message (source size %s bytes)>', + dataStream.outByteCount, + dataStream.inByteCount + ); + }); + + return dataStream; + } + + /** ACTIONS **/ + + /** + * Will be run after the connection is created and the server sends + * a greeting. If the incoming message starts with 220 initiate + * SMTP session by sending EHLO command + * + * @param {String} str Message from the server + */ + _actionGreeting(str) { + clearTimeout(this._greetingTimeout); + + if (str.substr(0, 3) !== '220') { + this._onError(new Error('Invalid greeting. response=' + str), 'EPROTOCOL', str, 'CONN'); + return; + } + + if (this.options.lmtp) { + this._responseActions.push(this._actionLHLO); + this._sendCommand('LHLO ' + this.name); + } else { + this._responseActions.push(this._actionEHLO); + this._sendCommand('EHLO ' + this.name); + } + } + + /** + * Handles server response for LHLO command. If it yielded in + * error, emit 'error', otherwise treat this as an EHLO response + * + * @param {String} str Message from the server + */ + _actionLHLO(str) { + if (str.charAt(0) !== '2') { + this._onError(new Error('Invalid LHLO. response=' + str), 'EPROTOCOL', str, 'LHLO'); + return; + } + + this._actionEHLO(str); + } + + /** + * Handles server response for EHLO command. If it yielded in + * error, try HELO instead, otherwise initiate TLS negotiation + * if STARTTLS is supported by the server or move into the + * authentication phase. + * + * @param {String} str Message from the server + */ + _actionEHLO(str) { + let match; + + if (str.substr(0, 3) === '421') { + this._onError(new Error('Server terminates connection. response=' + str), 'ECONNECTION', str, 'EHLO'); + return; + } + + if (str.charAt(0) !== '2') { + if (this.options.requireTLS) { + this._onError( + new Error('EHLO failed but HELO does not support required STARTTLS. response=' + str), + 'ECONNECTION', + str, + 'EHLO' + ); + return; + } + + // Try HELO instead + this._responseActions.push(this._actionHELO); + this._sendCommand('HELO ' + this.name); + return; + } + + this._ehloLines = str + .split(/\r?\n/) + .map(line => line.replace(/^\d+[ -]/, '').trim()) + .filter(line => line) + .slice(1); + + // Detect if the server supports STARTTLS + if (!this.secure && !this.options.ignoreTLS && (/[ -]STARTTLS\b/im.test(str) || this.options.requireTLS)) { + this._sendCommand('STARTTLS'); + this._responseActions.push(this._actionSTARTTLS); + return; + } + + // Detect if the server supports SMTPUTF8 + if (/[ -]SMTPUTF8\b/im.test(str)) { + this._supportedExtensions.push('SMTPUTF8'); + } + + // Detect if the server supports DSN + if (/[ -]DSN\b/im.test(str)) { + this._supportedExtensions.push('DSN'); + } + + // Detect if the server supports 8BITMIME + if (/[ -]8BITMIME\b/im.test(str)) { + this._supportedExtensions.push('8BITMIME'); + } + + // Detect if the server supports REQUIRETLS (RFC 8689) + if (/[ -]REQUIRETLS\b/im.test(str)) { + this._supportedExtensions.push('REQUIRETLS'); + } + + // Detect if the server supports PIPELINING + if (/[ -]PIPELINING\b/im.test(str)) { + this._supportedExtensions.push('PIPELINING'); + } + + // Detect if the server supports AUTH + if (/[ -]AUTH\b/i.test(str)) { + this.allowsAuth = true; + } + + // Detect if the server supports PLAIN auth + if (/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)PLAIN/i.test(str)) { + this._supportedAuth.push('PLAIN'); + } + + // Detect if the server supports LOGIN auth + if (/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)LOGIN/i.test(str)) { + this._supportedAuth.push('LOGIN'); + } + + // Detect if the server supports CRAM-MD5 auth + if (/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)CRAM-MD5/i.test(str)) { + this._supportedAuth.push('CRAM-MD5'); + } + + // Detect if the server supports XOAUTH2 auth + if (/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)XOAUTH2/i.test(str)) { + this._supportedAuth.push('XOAUTH2'); + } + + // Detect if the server supports SIZE extensions (and the max allowed size) + if ((match = str.match(/[ -]SIZE(?:[ \t]+(\d+))?/im))) { + this._supportedExtensions.push('SIZE'); + this._maxAllowedSize = Number(match[1]) || 0; + } + + this.emit('connect'); + } + + /** + * Handles server response for HELO command. If it yielded in + * error, emit 'error', otherwise move into the authentication phase. + * + * @param {String} str Message from the server + */ + _actionHELO(str) { + if (str.charAt(0) !== '2') { + this._onError(new Error('Invalid HELO. response=' + str), 'EPROTOCOL', str, 'HELO'); + return; + } + + // assume that authentication is enabled (most probably is not though) + this.allowsAuth = true; + + this.emit('connect'); + } + + /** + * Handles server response for STARTTLS command. If there's an error + * try HELO instead, otherwise initiate TLS upgrade. If the upgrade + * succeedes restart the EHLO + * + * @param {String} str Message from the server + */ + _actionSTARTTLS(str) { + if (str.charAt(0) !== '2') { + if (this.options.opportunisticTLS) { + this.logger.info( + { + tnx: 'smtp' + }, + 'Failed STARTTLS upgrade, continuing unencrypted' + ); + return this.emit('connect'); + } + this._onError(new Error('Error upgrading connection with STARTTLS'), 'ETLS', str, 'STARTTLS'); + return; + } + + this._upgradeConnection((err, secured) => { + if (err) { + this._onError(new Error('Error initiating TLS - ' + (err.message || err)), 'ETLS', false, 'STARTTLS'); + return; + } + + this.logger.info( + { + tnx: 'smtp' + }, + 'Connection upgraded with STARTTLS' + ); + + if (secured) { + // restart session + if (this.options.lmtp) { + this._responseActions.push(this._actionLHLO); + this._sendCommand('LHLO ' + this.name); + } else { + this._responseActions.push(this._actionEHLO); + this._sendCommand('EHLO ' + this.name); + } + } else { + this.emit('connect'); + } + }); + } + + /** + * Handle the response for AUTH LOGIN command. We are expecting + * '334 VXNlcm5hbWU6' (base64 for 'Username:'). Data to be sent as + * response needs to be base64 encoded username. We do not need + * exact match but settle with 334 response in general as some + * hosts invalidly use a longer message than VXNlcm5hbWU6 + * + * @param {String} str Message from the server + */ + _actionAUTH_LOGIN_USER(str, callback) { + if (!/^334[ -]/.test(str)) { + // expecting '334 VXNlcm5hbWU6' + callback(this._formatError('Invalid login sequence while waiting for "334 VXNlcm5hbWU6"', 'EAUTH', str, 'AUTH LOGIN')); + return; + } + + this._responseActions.push(str => { + this._actionAUTH_LOGIN_PASS(str, callback); + }); + + this._sendCommand(Buffer.from(this._auth.credentials.user + '', 'utf-8').toString('base64')); + } + + /** + * Handle the response for AUTH CRAM-MD5 command. We are expecting + * '334 '. Data to be sent as response needs to be + * base64 decoded challenge string, MD5 hashed using the password as + * a HMAC key, prefixed by the username and a space, and finally all + * base64 encoded again. + * + * @param {String} str Message from the server + */ + _actionAUTH_CRAM_MD5(str, callback) { + const challengeMatch = str.match(/^334\s+(.+)$/); + + if (!challengeMatch) { + return callback( + this._formatError('Invalid login sequence while waiting for server challenge string', 'EAUTH', str, 'AUTH CRAM-MD5') + ); + } + + // Decode from base64 + const base64decoded = Buffer.from(challengeMatch[1], 'base64').toString('ascii'); + const hmacMD5 = crypto.createHmac('md5', this._auth.credentials.pass); + + hmacMD5.update(base64decoded); + + const prepended = this._auth.credentials.user + ' ' + hmacMD5.digest('hex'); + + this._responseActions.push(str => { + this._actionAUTH_CRAM_MD5_PASS(str, callback); + }); + + this._sendCommand( + Buffer.from(prepended).toString('base64'), + // hidden hash for logs + Buffer.from(this._auth.credentials.user + ' /* secret */').toString('base64') + ); + } + + /** + * Handles the response to CRAM-MD5 authentication, if there's no error, + * the user can be considered logged in. Start waiting for a message to send + * + * @param {String} str Message from the server + */ + _actionAUTH_CRAM_MD5_PASS(str, callback) { + if (!str.match(/^235\s+/)) { + return callback(this._formatError('Invalid login sequence while waiting for "235"', 'EAUTH', str, 'AUTH CRAM-MD5')); + } + + this.logger.info( + { + tnx: 'smtp', + username: this._auth.user, + action: 'authenticated', + method: this._authMethod + }, + 'User %s authenticated', + JSON.stringify(this._auth.user) + ); + this.authenticated = true; + callback(null, true); + } + + /** + * Handle the response for AUTH LOGIN command. We are expecting + * '334 UGFzc3dvcmQ6' (base64 for 'Password:'). Data to be sent as + * response needs to be base64 encoded password. + * + * @param {String} str Message from the server + */ + _actionAUTH_LOGIN_PASS(str, callback) { + if (!/^334[ -]/.test(str)) { + // expecting '334 UGFzc3dvcmQ6' + return callback(this._formatError('Invalid login sequence while waiting for "334 UGFzc3dvcmQ6"', 'EAUTH', str, 'AUTH LOGIN')); + } + + this._responseActions.push(str => { + this._actionAUTHComplete(str, callback); + }); + + this._sendCommand( + Buffer.from((this._auth.credentials.pass || '').toString(), 'utf-8').toString('base64'), + // Hidden pass for logs + Buffer.from('/* secret */', 'utf-8').toString('base64') + ); + } + + /** + * Handles the response for authentication, if there's no error, + * the user can be considered logged in. Start waiting for a message to send + * + * @param {String} str Message from the server + */ + _actionAUTHComplete(str, isRetry, callback) { + if (!callback && typeof isRetry === 'function') { + callback = isRetry; + isRetry = false; + } + + if (str.substr(0, 3) === '334') { + this._responseActions.push(str => { + if (isRetry || this._authMethod !== 'XOAUTH2') { + this._actionAUTHComplete(str, true, callback); + } else { + // fetch a new OAuth2 access token + setImmediate(() => this._handleXOauth2Token(true, callback)); + } + }); + this._sendCommand(''); + return; + } + + if (str.charAt(0) !== '2') { + this.logger.info( + { + tnx: 'smtp', + username: this._auth.user, + action: 'authfail', + method: this._authMethod + }, + 'User %s failed to authenticate', + JSON.stringify(this._auth.user) + ); + return callback(this._formatError('Invalid login', 'EAUTH', str, 'AUTH ' + this._authMethod)); + } + + this.logger.info( + { + tnx: 'smtp', + username: this._auth.user, + action: 'authenticated', + method: this._authMethod + }, + 'User %s authenticated', + JSON.stringify(this._auth.user) + ); + this.authenticated = true; + callback(null, true); + } + + /** + * Handle response for a MAIL FROM: command + * + * @param {String} str Message from the server + */ + _actionMAIL(str, callback) { + if (Number(str.charAt(0)) !== 2) { + const message = + this._usingSmtpUtf8 && /^550 /.test(str) && /[\x80-\uFFFF]/.test(this._envelope.from) + ? 'Internationalized mailbox name not allowed' + : 'Mail command failed'; + return callback(this._formatError(message, 'EENVELOPE', str, 'MAIL FROM')); + } + + if (!this._envelope.rcptQueue.length) { + return callback(this._formatError("Can't send mail - no recipients defined", 'EENVELOPE', false, 'API')); + } + + this._recipientQueue = []; + const usePipelining = this._supportedExtensions.includes('PIPELINING'); + + do { + const curRecipient = this._envelope.rcptQueue.shift(); + this._recipientQueue.push(curRecipient); + this._responseActions.push(str => { + this._actionRCPT(str, callback); + }); + this._sendCommand('RCPT TO:<' + curRecipient + '>' + this._getDsnRcptToArgs()); + } while (usePipelining && this._envelope.rcptQueue.length); + } + + /** + * Handle response for a RCPT TO: command + * + * @param {String} str Message from the server + */ + _actionRCPT(str, callback) { + let err; + const curRecipient = this._recipientQueue.shift(); + if (Number(str.charAt(0)) !== 2) { + // this is a soft error + const message = + this._usingSmtpUtf8 && /^553 /.test(str) && /[\x80-\uFFFF]/.test(curRecipient) + ? 'Internationalized mailbox name not allowed' + : 'Recipient command failed'; + this._envelope.rejected.push(curRecipient); + // store error for the failed recipient + err = this._formatError(message, 'EENVELOPE', str, 'RCPT TO'); + err.recipient = curRecipient; + this._envelope.rejectedErrors.push(err); + } else { + this._envelope.accepted.push(curRecipient); + } + + if (!this._envelope.rcptQueue.length && !this._recipientQueue.length) { + if (this._envelope.rejected.length < this._envelope.to.length) { + this._responseActions.push(str => { + this._actionDATA(str, callback); + }); + this._sendCommand('DATA'); + } else { + err = this._formatError("Can't send mail - all recipients were rejected", 'EENVELOPE', str, 'RCPT TO'); + err.rejected = this._envelope.rejected; + err.rejectedErrors = this._envelope.rejectedErrors; + return callback(err); + } + } else if (this._envelope.rcptQueue.length) { + const nextRecipient = this._envelope.rcptQueue.shift(); + this._recipientQueue.push(nextRecipient); + this._responseActions.push(str => { + this._actionRCPT(str, callback); + }); + this._sendCommand('RCPT TO:<' + nextRecipient + '>' + this._getDsnRcptToArgs()); + } + } + + /** + * Handle response for a DATA command + * + * @param {String} str Message from the server + */ + _actionDATA(str, callback) { + // response should be 354 but according to this issue https://github.com/eleith/emailjs/issues/24 + // some servers might use 250 instead, so lets check for 2 or 3 as the first digit + if (!/^[23]/.test(str)) { + return callback(this._formatError('Data command failed', 'EENVELOPE', str, 'DATA')); + } + + const response = { + accepted: this._envelope.accepted, + rejected: this._envelope.rejected + }; + + if (this._ehloLines && this._ehloLines.length) { + response.ehlo = this._ehloLines; + } + + if (this._envelope.rejectedErrors.length) { + response.rejectedErrors = this._envelope.rejectedErrors; + } + + callback(null, response); + } + + /** + * Handle response for a DATA stream when using SMTP + * We expect a single response that defines if the sending succeeded or failed + * + * @param {String} str Message from the server + */ + _actionSMTPStream(str, callback) { + if (Number(str.charAt(0)) !== 2) { + return callback(this._formatError('Message failed', 'EMESSAGE', str, 'DATA')); + } + return callback(null, str); + } + + /** + * Handle response for a DATA stream + * We expect a separate response for every recipient. All recipients can either + * succeed or fail separately + * + * @param {String} recipient The recipient this response applies to + * @param {Boolean} final Is this the final recipient? + * @param {String} str Message from the server + */ + _actionLMTPStream(recipient, final, str, callback) { + let err; + if (Number(str.charAt(0)) !== 2) { + // Message failed + err = this._formatError('Message failed for recipient ' + recipient, 'EMESSAGE', str, 'DATA'); + err.recipient = recipient; + this._envelope.rejected.push(recipient); + this._envelope.rejectedErrors.push(err); + for (let i = 0, len = this._envelope.accepted.length; i < len; i++) { + if (this._envelope.accepted[i] === recipient) { + this._envelope.accepted.splice(i, 1); + } + } + } + if (final) { + return callback(null, str); + } + } + + _handleXOauth2Token(isRetry, callback) { + this._auth.oauth2.getToken(isRetry, (err, accessToken) => { + if (err) { + this.logger.info( + { + tnx: 'smtp', + username: this._auth.user, + action: 'authfail', + method: this._authMethod + }, + 'User %s failed to authenticate', + JSON.stringify(this._auth.user) + ); + return callback(this._formatError(err, 'EAUTH', false, 'AUTH XOAUTH2')); + } + this._responseActions.push(str => { + this._actionAUTHComplete(str, isRetry, callback); + }); + this._sendCommand( + 'AUTH XOAUTH2 ' + this._auth.oauth2.buildXOAuth2Token(accessToken), + // Hidden for logs + 'AUTH XOAUTH2 ' + this._auth.oauth2.buildXOAuth2Token('/* secret */') + ); + }); + } + + /** + * + * @param {string} command + * @private + */ + _isDestroyedMessage(command) { + if (this._destroyed) { + return 'Cannot ' + command + ' - smtp connection is already destroyed.'; + } + + if (this._socket) { + if (this._socket.destroyed) { + return 'Cannot ' + command + ' - smtp connection socket is already destroyed.'; + } + + if (!this._socket.writable) { + return 'Cannot ' + command + ' - smtp connection socket is already half-closed.'; + } + } + } + + _getHostname() { + // defaul hostname is machine hostname or [IP] + let defaultHostname; + try { + defaultHostname = os.hostname() || ''; + } catch (_err) { + // fails on windows 7 + defaultHostname = 'localhost'; + } + + // ignore if not FQDN + if (!defaultHostname || defaultHostname.indexOf('.') < 0) { + defaultHostname = '[127.0.0.1]'; + } + + // IP should be enclosed in [] + if (defaultHostname.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)) { + defaultHostname = '[' + defaultHostname + ']'; + } + + return defaultHostname; + } +} + +module.exports = SMTPConnection; diff --git a/node_modules/nodemailer/lib/smtp-pool/index.js b/node_modules/nodemailer/lib/smtp-pool/index.js new file mode 100644 index 0000000000000000000000000000000000000000..dd46d39342c01e0c272ed81be9ced59ef618ce10 --- /dev/null +++ b/node_modules/nodemailer/lib/smtp-pool/index.js @@ -0,0 +1,641 @@ +'use strict'; + +const EventEmitter = require('events'); +const PoolResource = require('./pool-resource'); +const SMTPConnection = require('../smtp-connection'); +const wellKnown = require('../well-known'); +const shared = require('../shared'); +const errors = require('../errors'); +const packageData = require('../../package.json'); + +/** + * Creates a SMTP pool transport object for Nodemailer + * + * @constructor + * @param {Object} options SMTP Connection options + */ +class SMTPPool extends EventEmitter { + constructor(options) { + super(); + + options = options || {}; + if (typeof options === 'string') { + options = { + url: options + }; + } + + let urlData; + let service = options.service; + + if (typeof options.getSocket === 'function') { + this.getSocket = options.getSocket; + } + + if (options.url) { + urlData = shared.parseConnectionUrl(options.url); + service = service || urlData.service; + } + + this.options = shared.assign( + false, // create new object + options, // regular options + urlData, // url options + service && wellKnown(service) // wellknown options + ); + + this.options.maxConnections = this.options.maxConnections || 5; + this.options.maxMessages = this.options.maxMessages || 100; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'smtp-pool' + }); + + this.name = 'SMTP (pool)'; + this.version = packageData.version + '[client:' + packageData.version + ']'; + + this._rateLimit = { + counter: 0, + timeout: null, + waiting: [], + checkpoint: false, + delta: Number(this.options.rateDelta) || 1000, + limit: Number(this.options.rateLimit) || 0 + }; + this._closed = false; + this._queue = []; + this._connections = []; + this._connectionCounter = 0; + + this.idling = true; + + setImmediate(() => { + if (this.idling) { + this.emit('idle'); + } + }); + } + + /** + * Placeholder function for creating proxy sockets. This method immediatelly returns + * without a socket + * + * @param {Object} options Connection options + * @param {Function} callback Callback function to run with the socket keys + */ + getSocket(options, callback) { + // return immediatelly + return setImmediate(() => callback(null, false)); + } + + /** + * Queues an e-mail to be sent using the selected settings + * + * @param {Object} mail Mail object + * @param {Function} callback Callback function + */ + send(mail, callback) { + if (this._closed) { + return false; + } + + this._queue.push({ + mail, + requeueAttempts: 0, + callback + }); + + if (this.idling && this._queue.length >= this.options.maxConnections) { + this.idling = false; + } + + setImmediate(() => this._processMessages()); + + return true; + } + + /** + * Closes all connections in the pool. If there is a message being sent, the connection + * is closed later + */ + close() { + let connection; + const len = this._connections.length; + this._closed = true; + + // clear rate limit timer if it exists + clearTimeout(this._rateLimit.timeout); + + if (!len && !this._queue.length) { + return; + } + + // remove all available connections + for (let i = len - 1; i >= 0; i--) { + if (this._connections[i] && this._connections[i].available) { + connection = this._connections[i]; + connection.close(); + this.logger.info( + { + tnx: 'connection', + cid: connection.id, + action: 'removed' + }, + 'Connection #%s removed', + connection.id + ); + } + } + + if (len && !this._connections.length) { + this.logger.debug( + { + tnx: 'connection' + }, + 'All connections removed' + ); + } + + if (!this._queue.length) { + return; + } + + // make sure that entire queue would be cleaned + const invokeCallbacks = () => { + if (!this._queue.length) { + this.logger.debug( + { + tnx: 'connection' + }, + 'Pending queue entries cleared' + ); + return; + } + const entry = this._queue.shift(); + if (entry && typeof entry.callback === 'function') { + try { + entry.callback(new Error('Connection pool was closed')); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'callback', + cid: connection.id + }, + 'Callback error for #%s: %s', + connection.id, + E.message + ); + } + } + setImmediate(invokeCallbacks); + }; + setImmediate(invokeCallbacks); + } + + /** + * Check the queue and available connections. If there is a message to be sent and there is + * an available connection, then use this connection to send the mail + */ + _processMessages() { + // do nothing if already closed + if (this._closed) { + return; + } + + // do nothing if queue is empty + if (!this._queue.length) { + if (!this.idling) { + // no pending jobs + this.idling = true; + this.emit('idle'); + } + return; + } + + // find first available connection + let connection = this._connections.find(c => c.available); + + if (!connection && this._connections.length < this.options.maxConnections) { + connection = this._createConnection(); + } + + if (!connection) { + // no more free connection slots available + this.idling = false; + return; + } + + // check if there is free space in the processing queue + if (!this.idling && this._queue.length < this.options.maxConnections) { + this.idling = true; + this.emit('idle'); + } + + const entry = (connection.queueEntry = this._queue.shift()); + entry.messageId = (connection.queueEntry.mail.message.getHeader('message-id') || '').replace(/[<>\s]/g, ''); + + connection.available = false; + + this.logger.debug( + { + tnx: 'pool', + cid: connection.id, + messageId: entry.messageId, + action: 'assign' + }, + 'Assigned message <%s> to #%s (%s)', + entry.messageId, + connection.id, + connection.messages + 1 + ); + + if (this._rateLimit.limit) { + this._rateLimit.counter++; + if (!this._rateLimit.checkpoint) { + this._rateLimit.checkpoint = Date.now(); + } + } + + connection.send(entry.mail, (err, info) => { + // only process callback if current handler is not changed + if (entry === connection.queueEntry) { + try { + entry.callback(err, info); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'callback', + cid: connection.id + }, + 'Callback error for #%s: %s', + connection.id, + E.message + ); + } + connection.queueEntry = false; + } + }); + } + + /** + * Creates a new pool resource + */ + _createConnection() { + const connection = new PoolResource(this); + + connection.id = ++this._connectionCounter; + + this.logger.info( + { + tnx: 'pool', + cid: connection.id, + action: 'conection' + }, + 'Created new pool resource #%s', + connection.id + ); + + // resource comes available + connection.on('available', () => { + this.logger.debug( + { + tnx: 'connection', + cid: connection.id, + action: 'available' + }, + 'Connection #%s became available', + connection.id + ); + + if (this._closed) { + // if already closed run close() that will remove this connections from connections list + this.close(); + } else { + // check if there's anything else to send + this._processMessages(); + } + }); + + // resource is terminated with an error + connection.once('error', err => { + if (err.code !== errors.EMAXLIMIT) { + this.logger.warn( + { + err, + tnx: 'pool', + cid: connection.id + }, + 'Pool Error for #%s: %s', + connection.id, + err.message + ); + } else { + this.logger.debug( + { + tnx: 'pool', + cid: connection.id, + action: 'maxlimit' + }, + 'Max messages limit exchausted for #%s', + connection.id + ); + } + + if (connection.queueEntry) { + try { + connection.queueEntry.callback(err); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'callback', + cid: connection.id + }, + 'Callback error for #%s: %s', + connection.id, + E.message + ); + } + connection.queueEntry = false; + } + + // remove the erroneus connection from connections list + this._removeConnection(connection); + + this._continueProcessing(); + }); + + connection.once('close', () => { + this.logger.info( + { + tnx: 'connection', + cid: connection.id, + action: 'closed' + }, + 'Connection #%s was closed', + connection.id + ); + + this._removeConnection(connection); + + if (connection.queueEntry) { + // If the connection closed when sending, add the message to the queue again + // if max number of requeues is not reached yet + // Note that we must wait a bit.. because the callback of the 'error' handler might be called + // in the next event loop + setTimeout(() => { + if (connection.queueEntry) { + if (this._shouldRequeuOnConnectionClose(connection.queueEntry)) { + this._requeueEntryOnConnectionClose(connection); + } else { + this._failDeliveryOnConnectionClose(connection); + } + } + this._continueProcessing(); + }, 50); + } else { + if (!this._closed && this.idling && !this._connections.length) { + this.emit('clear'); + } + + this._continueProcessing(); + } + }); + + this._connections.push(connection); + + return connection; + } + + _shouldRequeuOnConnectionClose(queueEntry) { + if (this.options.maxRequeues === undefined || this.options.maxRequeues < 0) { + return true; + } + + return queueEntry.requeueAttempts < this.options.maxRequeues; + } + + _failDeliveryOnConnectionClose(connection) { + if (connection.queueEntry && connection.queueEntry.callback) { + try { + connection.queueEntry.callback(new Error('Reached maximum number of retries after connection was closed')); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'callback', + messageId: connection.queueEntry.messageId, + cid: connection.id + }, + 'Callback error for #%s: %s', + connection.id, + E.message + ); + } + connection.queueEntry = false; + } + } + + _requeueEntryOnConnectionClose(connection) { + connection.queueEntry.requeueAttempts += 1; + this.logger.debug( + { + tnx: 'pool', + cid: connection.id, + messageId: connection.queueEntry.messageId, + action: 'requeue' + }, + 'Re-queued message <%s> for #%s. Attempt: #%s', + connection.queueEntry.messageId, + connection.id, + connection.queueEntry.requeueAttempts + ); + this._queue.unshift(connection.queueEntry); + connection.queueEntry = false; + } + + /** + * Continue to process message if the pool hasn't closed + */ + _continueProcessing() { + if (this._closed) { + this.close(); + } else { + setTimeout(() => this._processMessages(), 100); + } + } + + /** + * Remove resource from pool + * + * @param {Object} connection The PoolResource to remove + */ + _removeConnection(connection) { + const index = this._connections.indexOf(connection); + + if (index !== -1) { + this._connections.splice(index, 1); + } + } + + /** + * Checks if connections have hit current rate limit and if so, queues the availability callback + * + * @param {Function} callback Callback function to run once rate limiter has been cleared + */ + _checkRateLimit(callback) { + if (!this._rateLimit.limit) { + return callback(); + } + + const now = Date.now(); + + if (this._rateLimit.counter < this._rateLimit.limit) { + return callback(); + } + + this._rateLimit.waiting.push(callback); + + if (this._rateLimit.checkpoint <= now - this._rateLimit.delta) { + return this._clearRateLimit(); + } + + if (!this._rateLimit.timeout) { + this._rateLimit.timeout = setTimeout(() => this._clearRateLimit(), this._rateLimit.delta - (now - this._rateLimit.checkpoint)); + this._rateLimit.checkpoint = now; + } + } + + /** + * Clears current rate limit limitation and runs paused callback + */ + _clearRateLimit() { + clearTimeout(this._rateLimit.timeout); + this._rateLimit.timeout = null; + this._rateLimit.counter = 0; + this._rateLimit.checkpoint = false; + + // resume all paused connections + while (this._rateLimit.waiting.length) { + const cb = this._rateLimit.waiting.shift(); + setImmediate(cb); + } + } + + /** + * Returns true if there are free slots in the queue + */ + isIdle() { + return this.idling; + } + + /** + * Verifies SMTP configuration + * + * @param {Function} callback Callback function + */ + verify(callback) { + let promise; + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = shared.callbackPromise(resolve, reject); + }); + } + + const auth = new PoolResource(this).auth; + + this.getSocket(this.options, (err, socketOptions) => { + if (err) { + return callback(err); + } + + let options = this.options; + if (socketOptions && socketOptions.connection) { + this.logger.info( + { + tnx: 'proxy', + remoteAddress: socketOptions.connection.remoteAddress, + remotePort: socketOptions.connection.remotePort, + destHost: options.host || '', + destPort: options.port || '', + action: 'connected' + }, + 'Using proxied socket from %s:%s to %s:%s', + socketOptions.connection.remoteAddress, + socketOptions.connection.remotePort, + options.host || '', + options.port || '' + ); + options = Object.assign(shared.assign(false, options), socketOptions); + } + + const connection = new SMTPConnection(options); + let returned = false; + + connection.once('error', err => { + if (returned) { + return; + } + returned = true; + connection.close(); + return callback(err); + }); + + connection.once('end', () => { + if (returned) { + return; + } + returned = true; + return callback(new Error('Connection closed')); + }); + + const finalize = () => { + if (returned) { + return; + } + returned = true; + connection.quit(); + return callback(null, true); + }; + + connection.connect(() => { + if (returned) { + return; + } + + if (auth && (connection.allowsAuth || options.forceAuth)) { + connection.login(auth, err => { + if (returned) { + return; + } + + if (err) { + returned = true; + connection.close(); + return callback(err); + } + + finalize(); + }); + } else if (!auth && connection.allowsAuth && options.forceAuth) { + const err = new Error('Authentication info was not provided'); + err.code = errors.ENOAUTH; + + returned = true; + connection.close(); + return callback(err); + } else { + finalize(); + } + }); + }); + + return promise; + } +} + +// expose to the world +module.exports = SMTPPool; diff --git a/node_modules/nodemailer/lib/smtp-pool/pool-resource.js b/node_modules/nodemailer/lib/smtp-pool/pool-resource.js new file mode 100644 index 0000000000000000000000000000000000000000..c2bb26f6e3fa79c0fbd2aa53f5c4eabf97c3d225 --- /dev/null +++ b/node_modules/nodemailer/lib/smtp-pool/pool-resource.js @@ -0,0 +1,256 @@ +'use strict'; + +const SMTPConnection = require('../smtp-connection'); +const assign = require('../shared').assign; +const XOAuth2 = require('../xoauth2'); +const errors = require('../errors'); +const EventEmitter = require('events'); + +/** + * Creates an element for the pool + * + * @constructor + * @param {Object} options SMTPPool instance + */ +class PoolResource extends EventEmitter { + constructor(pool) { + super(); + + this.pool = pool; + this.options = pool.options; + this.logger = this.pool.logger; + + if (this.options.auth) { + switch ((this.options.auth.type || '').toString().toUpperCase()) { + case 'OAUTH2': { + const oauth2 = new XOAuth2(this.options.auth, this.logger); + oauth2.provisionCallback = + (this.pool.mailer && this.pool.mailer.get('oauth2_provision_cb')) || oauth2.provisionCallback; + this.auth = { + type: 'OAUTH2', + user: this.options.auth.user, + oauth2, + method: 'XOAUTH2' + }; + oauth2.on('token', token => this.pool.mailer.emit('token', token)); + oauth2.on('error', err => this.emit('error', err)); + break; + } + default: + if (!this.options.auth.user && !this.options.auth.pass) { + break; + } + this.auth = { + type: (this.options.auth.type || '').toString().toUpperCase() || 'LOGIN', + user: this.options.auth.user, + credentials: { + user: this.options.auth.user || '', + pass: this.options.auth.pass, + options: this.options.auth.options + }, + method: (this.options.auth.method || '').trim().toUpperCase() || this.options.authMethod || false + }; + } + } + + this._connection = false; + this._connected = false; + + this.messages = 0; + this.available = true; + } + + /** + * Initiates a connection to the SMTP server + * + * @param {Function} callback Callback function to run once the connection is established or failed + */ + connect(callback) { + this.pool.getSocket(this.options, (err, socketOptions) => { + if (err) { + return callback(err); + } + + let returned = false; + let options = this.options; + if (socketOptions && socketOptions.connection) { + this.logger.info( + { + tnx: 'proxy', + remoteAddress: socketOptions.connection.remoteAddress, + remotePort: socketOptions.connection.remotePort, + destHost: options.host || '', + destPort: options.port || '', + action: 'connected' + }, + 'Using proxied socket from %s:%s to %s:%s', + socketOptions.connection.remoteAddress, + socketOptions.connection.remotePort, + options.host || '', + options.port || '' + ); + + options = Object.assign(assign(false, options), socketOptions); + } + + this.connection = new SMTPConnection(options); + + this.connection.once('error', err => { + this.emit('error', err); + if (returned) { + return; + } + returned = true; + return callback(err); + }); + + this.connection.once('end', () => { + this.close(); + if (returned) { + return; + } + returned = true; + + const timer = setTimeout(() => { + if (returned) { + return; + } + // still have not returned, this means we have an unexpected connection close + const err = new Error('Unexpected socket close'); + if (this.connection && this.connection._socket && this.connection._socket.upgrading) { + // starttls connection errors + err.code = errors.ETLS; + } + callback(err); + }, 1000); + + try { + timer.unref(); + } catch (_E) { + // Ignore. Happens on envs with non-node timer implementation + } + }); + + this.connection.connect(() => { + if (returned) { + return; + } + + if (this.auth && (this.connection.allowsAuth || options.forceAuth)) { + this.connection.login(this.auth, err => { + if (returned) { + return; + } + returned = true; + + if (err) { + this.connection.close(); + this.emit('error', err); + return callback(err); + } + + this._connected = true; + callback(null, true); + }); + } else { + returned = true; + this._connected = true; + return callback(null, true); + } + }); + }); + } + + /** + * Sends an e-mail to be sent using the selected settings + * + * @param {Object} mail Mail object + * @param {Function} callback Callback function + */ + send(mail, callback) { + if (!this._connected) { + return this.connect(err => { + if (err) { + return callback(err); + } + return this.send(mail, callback); + }); + } + + const envelope = mail.message.getEnvelope(); + const messageId = mail.message.messageId(); + + const recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + this.logger.info( + { + tnx: 'send', + messageId, + cid: this.id + }, + 'Sending message %s using #%s to <%s>', + messageId, + this.id, + recipients.join(', ') + ); + + if (mail.data.dsn) { + envelope.dsn = mail.data.dsn; + } + + // RFC 8689: Pass requireTLSExtensionEnabled to envelope for MAIL FROM parameter + if (mail.data.requireTLSExtensionEnabled) { + envelope.requireTLSExtensionEnabled = mail.data.requireTLSExtensionEnabled; + } + + this.connection.send(envelope, mail.message.createReadStream(), (err, info) => { + this.messages++; + + if (err) { + this.connection.close(); + this.emit('error', err); + return callback(err); + } + + info.envelope = { + from: envelope.from, + to: envelope.to + }; + info.messageId = messageId; + + setImmediate(() => { + if (this.messages >= this.options.maxMessages) { + const err = new Error('Resource exhausted'); + err.code = errors.EMAXLIMIT; + this.connection.close(); + this.emit('error', err); + } else { + this.pool._checkRateLimit(() => { + this.available = true; + this.emit('available'); + }); + } + }); + + callback(null, info); + }); + } + + /** + * Closes the connection + */ + close() { + this._connected = false; + if (this.auth && this.auth.oauth2) { + this.auth.oauth2.removeAllListeners(); + } + if (this.connection) { + this.connection.close(); + } + this.emit('close'); + } +} + +module.exports = PoolResource; diff --git a/node_modules/nodemailer/lib/smtp-transport/index.js b/node_modules/nodemailer/lib/smtp-transport/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bc07616f10c6e47b46341a9f5db16c1b80df8c1c --- /dev/null +++ b/node_modules/nodemailer/lib/smtp-transport/index.js @@ -0,0 +1,429 @@ +'use strict'; + +const EventEmitter = require('events'); +const SMTPConnection = require('../smtp-connection'); +const wellKnown = require('../well-known'); +const shared = require('../shared'); +const XOAuth2 = require('../xoauth2'); +const errors = require('../errors'); +const packageData = require('../../package.json'); + +/** + * Creates a SMTP transport object for Nodemailer + * + * @constructor + * @param {Object} options Connection options + */ +class SMTPTransport extends EventEmitter { + constructor(options) { + super(); + + options = options || {}; + + if (typeof options === 'string') { + options = { + url: options + }; + } + + let urlData; + let service = options.service; + + if (typeof options.getSocket === 'function') { + this.getSocket = options.getSocket; + } + + if (options.url) { + urlData = shared.parseConnectionUrl(options.url); + service = service || urlData.service; + } + + this.options = shared.assign( + false, // create new object + options, // regular options + urlData, // url options + service && wellKnown(service) // wellknown options + ); + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'smtp-transport' + }); + + this.name = 'SMTP'; + this.version = packageData.version + '[client:' + packageData.version + ']'; + + if (this.options.auth) { + this.auth = this.getAuth({}); + } + } + + /** + * Placeholder function for creating proxy sockets. This method immediatelly returns + * without a socket + * + * @param {Object} options Connection options + * @param {Function} callback Callback function to run with the socket keys + */ + getSocket(options, callback) { + // return immediatelly + return setImmediate(() => callback(null, false)); + } + + getAuth(authOpts) { + if (!authOpts) { + if (this.auth && this.auth.oauth2 && this.mailer) { + // Transport-level auth is resolved in the constructor, before the Mail wrapper + // assigns `this.mailer`, so a provision callback registered with + // `transporter.set('oauth2_provision_cb', ...)` has to be re-checked here + this.auth.oauth2.provisionCallback = this.mailer.get('oauth2_provision_cb') || this.auth.oauth2.provisionCallback; + } + return this.auth; + } + + const authData = Object.assign( + {}, + this.options.auth && typeof this.options.auth === 'object' ? this.options.auth : {}, + typeof authOpts === 'object' ? authOpts : {} + ); + + if (Object.keys(authData).length === 0) { + return false; + } + + switch ((authData.type || '').toString().toUpperCase()) { + case 'OAUTH2': { + if (!authData.service && !authData.user) { + return false; + } + const oauth2 = new XOAuth2(authData, this.logger); + oauth2.provisionCallback = (this.mailer && this.mailer.get('oauth2_provision_cb')) || oauth2.provisionCallback; + oauth2.on('token', token => this.mailer.emit('token', token)); + oauth2.on('error', err => this.emit('error', err)); + return { + type: 'OAUTH2', + user: authData.user, + oauth2, + method: 'XOAUTH2' + }; + } + default: + return { + type: (authData.type || '').toString().toUpperCase() || 'LOGIN', + user: authData.user, + credentials: { + user: authData.user || '', + pass: authData.pass, + options: authData.options + }, + method: (authData.method || '').trim().toUpperCase() || this.options.authMethod || false + }; + } + } + + /** + * Sends an e-mail using the selected settings + * + * @param {Object} mail Mail object + * @param {Function} callback Callback function + */ + send(mail, callback) { + this.getSocket(this.options, (err, socketOptions) => { + if (err) { + return callback(err); + } + + let returned = false; + let options = this.options; + if (socketOptions && socketOptions.connection) { + this.logger.info( + { + tnx: 'proxy', + remoteAddress: socketOptions.connection.remoteAddress, + remotePort: socketOptions.connection.remotePort, + destHost: options.host || '', + destPort: options.port || '', + action: 'connected' + }, + 'Using proxied socket from %s:%s to %s:%s', + socketOptions.connection.remoteAddress, + socketOptions.connection.remotePort, + options.host || '', + options.port || '' + ); + + // only copy options if we need to modify it + options = Object.assign(shared.assign(false, options), socketOptions); + } + + const connection = new SMTPConnection(options); + + let perCallAuth; + const cleanupPerCallAuth = () => { + if (perCallAuth && perCallAuth !== this.auth && perCallAuth.oauth2) { + perCallAuth.oauth2.removeAllListeners(); + } + perCallAuth = null; + }; + + connection.once('error', err => { + if (returned) { + return; + } + returned = true; + cleanupPerCallAuth(); + connection.close(); + return callback(err); + }); + + connection.once('end', () => { + if (returned) { + return; + } + + const timer = setTimeout(() => { + if (returned) { + return; + } + returned = true; + cleanupPerCallAuth(); + // still have not returned, this means we have an unexpected connection close + const err = new Error('Unexpected socket close'); + if (connection && connection._socket && connection._socket.upgrading) { + // starttls connection errors + err.code = errors.ETLS; + } + callback(err); + }, 1000); + + try { + timer.unref(); + } catch (_E) { + // Ignore. Happens on envs with non-node timer implementation + } + }); + + const sendMessage = () => { + const envelope = mail.message.getEnvelope(); + const messageId = mail.message.messageId(); + + const recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + + if (mail.data.dsn) { + envelope.dsn = mail.data.dsn; + } + + // RFC 8689: Pass requireTLSExtensionEnabled to envelope for MAIL FROM parameter + if (mail.data.requireTLSExtensionEnabled) { + envelope.requireTLSExtensionEnabled = mail.data.requireTLSExtensionEnabled; + } + + this.logger.info( + { + tnx: 'send', + messageId + }, + 'Sending message %s to <%s>', + messageId, + recipients.join(', ') + ); + + connection.send(envelope, mail.message.createReadStream(), (err, info) => { + returned = true; + cleanupPerCallAuth(); + connection.close(); + if (err) { + this.logger.error( + { + err, + tnx: 'send' + }, + 'Send error for %s: %s', + messageId, + err.message + ); + return callback(err); + } + info.envelope = { + from: envelope.from, + to: envelope.to + }; + info.messageId = messageId; + try { + return callback(null, info); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'callback' + }, + 'Callback error for %s: %s', + messageId, + E.message + ); + } + }); + }; + + connection.connect(() => { + if (returned) { + return; + } + + perCallAuth = this.getAuth(mail.data.auth); + + if (perCallAuth && (connection.allowsAuth || options.forceAuth)) { + connection.login(perCallAuth, err => { + cleanupPerCallAuth(); + if (returned) { + return; + } + + if (err) { + returned = true; + connection.close(); + return callback(err); + } + + sendMessage(); + }); + } else { + sendMessage(); + } + }); + }); + } + + /** + * Verifies SMTP configuration + * + * @param {Function} callback Callback function + */ + verify(callback) { + let promise; + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = shared.callbackPromise(resolve, reject); + }); + } + + this.getSocket(this.options, (err, socketOptions) => { + if (err) { + return callback(err); + } + + let options = this.options; + if (socketOptions && socketOptions.connection) { + this.logger.info( + { + tnx: 'proxy', + remoteAddress: socketOptions.connection.remoteAddress, + remotePort: socketOptions.connection.remotePort, + destHost: options.host || '', + destPort: options.port || '', + action: 'connected' + }, + 'Using proxied socket from %s:%s to %s:%s', + socketOptions.connection.remoteAddress, + socketOptions.connection.remotePort, + options.host || '', + options.port || '' + ); + + options = Object.assign(shared.assign(false, options), socketOptions); + } + + const connection = new SMTPConnection(options); + let returned = false; + let perCallAuth; + const cleanupPerCallAuth = () => { + if (perCallAuth && perCallAuth !== this.auth && perCallAuth.oauth2) { + perCallAuth.oauth2.removeAllListeners(); + } + perCallAuth = null; + }; + + connection.once('error', err => { + if (returned) { + return; + } + returned = true; + cleanupPerCallAuth(); + connection.close(); + return callback(err); + }); + + connection.once('end', () => { + if (returned) { + return; + } + returned = true; + cleanupPerCallAuth(); + return callback(new Error('Connection closed')); + }); + + const finalize = () => { + if (returned) { + return; + } + returned = true; + cleanupPerCallAuth(); + connection.quit(); + return callback(null, true); + }; + + connection.connect(() => { + if (returned) { + return; + } + + perCallAuth = this.getAuth({}); + + if (perCallAuth && (connection.allowsAuth || options.forceAuth)) { + connection.login(perCallAuth, err => { + cleanupPerCallAuth(); + if (returned) { + return; + } + + if (err) { + returned = true; + connection.close(); + return callback(err); + } + + finalize(); + }); + } else if (!perCallAuth && connection.allowsAuth && options.forceAuth) { + const err = new Error('Authentication info was not provided'); + err.code = errors.ENOAUTH; + + returned = true; + cleanupPerCallAuth(); + connection.close(); + return callback(err); + } else { + finalize(); + } + }); + }); + + return promise; + } + + /** + * Releases resources + */ + close() { + if (this.auth && this.auth.oauth2) { + this.auth.oauth2.removeAllListeners(); + } + this.emit('close'); + } +} + +// expose to the world +module.exports = SMTPTransport; diff --git a/node_modules/nodemailer/lib/stream-transport/index.js b/node_modules/nodemailer/lib/stream-transport/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c000111fd10dc385163393cecc3f016b8e761726 --- /dev/null +++ b/node_modules/nodemailer/lib/stream-transport/index.js @@ -0,0 +1,144 @@ +'use strict'; + +const packageData = require('../../package.json'); +const shared = require('../shared'); +const LeWindows = require('../mime-node/le-windows'); +const LeUnix = require('../mime-node/le-unix'); + +/** + * Generates a Transport object for streaming + * + * Possible options can be the following: + * + * * **buffer** if true, then returns the message as a Buffer object instead of a stream + * * **newline** either 'windows' or 'unix' + * + * @constructor + * @param {Object} optional config parameter + */ +class StreamTransport { + constructor(options) { + options = options || {}; + + this.options = options; + + this.name = 'StreamTransport'; + this.version = packageData.version; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'stream-transport' + }); + + this.winbreak = ['win', 'windows', 'dos', '\r\n'].includes((options.newline || '').toString().toLowerCase()); + } + + /** + * Compiles a mailcomposer message and forwards it to handler that sends it + * + * @param {Object} emailMessage MailComposer object + * @param {Function} callback Callback function to run when the sending is completed + */ + send(mail, done) { + // We probably need this in the output + mail.message.keepBcc = true; + + const envelope = mail.data.envelope || mail.message.getEnvelope(); + const messageId = mail.message.messageId(); + + const recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + this.logger.info( + { + tnx: 'send', + messageId + }, + 'Sending message %s to <%s> using %s line breaks', + messageId, + recipients.join(', '), + this.winbreak ? '' : '' + ); + + setImmediate(() => { + let stream; + + try { + stream = mail.message.createReadStream(); + if (this.options.newline) { + // apply the transport-level line ending transform; the message-level + // `newline` option is handled by MimeNode in createReadStream() + const sourceStream = stream; + stream = sourceStream.pipe(this.winbreak ? new LeWindows() : new LeUnix()); + sourceStream.once('error', err => stream.emit('error', err)); + } + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'send', + messageId + }, + 'Creating send stream failed for %s. %s', + messageId, + E.message + ); + return done(E); + } + + if (!this.options.buffer) { + stream.once('error', err => { + this.logger.error( + { + err, + tnx: 'send', + messageId + }, + 'Failed creating message for %s. %s', + messageId, + err.message + ); + }); + return done(null, { + envelope, + messageId, + message: stream + }); + } + + const chunks = []; + let chunklen = 0; + stream.on('readable', () => { + let chunk; + while ((chunk = stream.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; + } + }); + + stream.once('error', err => { + this.logger.error( + { + err, + tnx: 'send', + messageId + }, + 'Failed creating message for %s. %s', + messageId, + err.message + ); + return done(err); + }); + + stream.on('end', () => + done(null, { + envelope, + messageId, + message: Buffer.concat(chunks, chunklen) + }) + ); + }); + } +} + +module.exports = StreamTransport; diff --git a/node_modules/nodemailer/lib/well-known/index.js b/node_modules/nodemailer/lib/well-known/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1d93a2bea7067da6e92a7dd8236610b96a6ef89e --- /dev/null +++ b/node_modules/nodemailer/lib/well-known/index.js @@ -0,0 +1,47 @@ +'use strict'; + +const services = require('./services.json'); +const normalized = {}; + +Object.keys(services).forEach(key => { + const service = services[key]; + const normalizedService = normalizeService(service); + + normalized[normalizeKey(key)] = normalizedService; + + [].concat(service.aliases || []).forEach(alias => { + normalized[normalizeKey(alias)] = normalizedService; + }); + + [].concat(service.domains || []).forEach(domain => { + normalized[normalizeKey(domain)] = normalizedService; + }); +}); + +function normalizeKey(key) { + return key.replace(/[^a-zA-Z0-9.-]/g, '').toLowerCase(); +} + +function normalizeService(service) { + const response = {}; + + Object.keys(service).forEach(key => { + if (!['domains', 'aliases'].includes(key)) { + response[key] = service[key]; + } + }); + + return response; +} + +/** + * Resolves SMTP config for given key. Key can be a name (like 'Gmail'), alias (like 'Google Mail') or + * an email address (like 'test@googlemail.com'). + * + * @param {String} key [description] + * @returns {Object} SMTP config or false if not found + */ +module.exports = function (key) { + key = normalizeKey(key.split('@').pop()); + return normalized[key] || false; +}; diff --git a/node_modules/nodemailer/lib/well-known/services.json b/node_modules/nodemailer/lib/well-known/services.json new file mode 100644 index 0000000000000000000000000000000000000000..99aff02a59277e2912ef3d7ffd2e7046829f3f90 --- /dev/null +++ b/node_modules/nodemailer/lib/well-known/services.json @@ -0,0 +1,619 @@ +{ + "1und1": { + "description": "1&1 Mail (German hosting provider)", + "host": "smtp.1und1.de", + "port": 465, + "secure": true, + "authMethod": "LOGIN" + }, + + "126": { + "description": "126 Mail (NetEase)", + "host": "smtp.126.com", + "port": 465, + "secure": true + }, + + "163": { + "description": "163 Mail (NetEase)", + "host": "smtp.163.com", + "port": 465, + "secure": true + }, + + "Aliyun": { + "description": "Alibaba Cloud Mail", + "domains": ["aliyun.com"], + "host": "smtp.aliyun.com", + "port": 465, + "secure": true + }, + + "AliyunQiye": { + "description": "Alibaba Cloud Enterprise Mail", + "host": "smtp.qiye.aliyun.com", + "port": 465, + "secure": true + }, + + "AOL": { + "description": "AOL Mail", + "domains": ["aol.com"], + "host": "smtp.aol.com", + "port": 587 + }, + + "Aruba": { + "description": "Aruba PEC (Italian email provider)", + "domains": ["aruba.it", "pec.aruba.it"], + "aliases": ["Aruba PEC"], + "host": "smtps.aruba.it", + "port": 465, + "secure": true, + "authMethod": "LOGIN" + }, + + "Bluewin": { + "description": "Bluewin (Swiss email provider)", + "host": "smtpauths.bluewin.ch", + "domains": ["bluewin.ch"], + "port": 465 + }, + + "BOL": { + "description": "BOL Mail (Brazilian provider)", + "domains": ["bol.com.br"], + "host": "smtp.bol.com.br", + "port": 587, + "requireTLS": true + }, + + "DebugMail": { + "description": "DebugMail (email testing service)", + "host": "debugmail.io", + "port": 25 + }, + + "Disroot": { + "description": "Disroot (privacy-focused provider)", + "domains": ["disroot.org"], + "host": "disroot.org", + "port": 587, + "secure": false, + "authMethod": "LOGIN" + }, + + "DynectEmail": { + "description": "Dyn Email Delivery", + "aliases": ["Dynect"], + "host": "smtp.dynect.net", + "port": 25 + }, + + "ElasticEmail": { + "description": "Elastic Email", + "aliases": ["Elastic Email"], + "host": "smtp.elasticemail.com", + "port": 465, + "secure": true + }, + + "Ethereal": { + "description": "Ethereal Email (email testing service)", + "aliases": ["ethereal.email"], + "host": "smtp.ethereal.email", + "port": 587 + }, + + "FastMail": { + "description": "FastMail", + "domains": ["fastmail.fm"], + "host": "smtp.fastmail.com", + "port": 465, + "secure": true + }, + + "Feishu Mail": { + "description": "Feishu Mail (Lark)", + "aliases": ["Feishu", "FeishuMail"], + "domains": ["www.feishu.cn"], + "host": "smtp.feishu.cn", + "port": 465, + "secure": true + }, + + "Forward Email": { + "description": "Forward Email (email forwarding service)", + "aliases": ["FE", "ForwardEmail"], + "domains": ["forwardemail.net"], + "host": "smtp.forwardemail.net", + "port": 465, + "secure": true + }, + + "GandiMail": { + "description": "Gandi Mail", + "aliases": ["Gandi", "Gandi Mail"], + "host": "mail.gandi.net", + "port": 587 + }, + + "Gmail": { + "description": "Gmail", + "aliases": ["Google Mail"], + "domains": ["gmail.com", "googlemail.com"], + "host": "smtp.gmail.com", + "port": 465, + "secure": true + }, + + "GmailWorkspace": { + "description": "Gmail Workspace", + "aliases": ["Google Workspace Mail"], + "host": "smtp-relay.gmail.com", + "port": 465, + "secure": true + }, + + "GMX": { + "description": "GMX Mail", + "domains": ["gmx.com", "gmx.net", "gmx.de"], + "host": "mail.gmx.com", + "port": 587 + }, + + "Godaddy": { + "description": "GoDaddy Email (US)", + "host": "smtpout.secureserver.net", + "port": 25 + }, + + "GodaddyAsia": { + "description": "GoDaddy Email (Asia)", + "host": "smtp.asia.secureserver.net", + "port": 25 + }, + + "GodaddyEurope": { + "description": "GoDaddy Email (Europe)", + "host": "smtp.europe.secureserver.net", + "port": 25 + }, + + "hot.ee": { + "description": "Hot.ee (Estonian email provider)", + "host": "mail.hot.ee" + }, + + "Hotmail": { + "description": "Outlook.com / Hotmail", + "aliases": ["Outlook", "Outlook.com", "Hotmail.com"], + "domains": ["hotmail.com", "outlook.com"], + "host": "smtp-mail.outlook.com", + "port": 587 + }, + + "iCloud": { + "description": "iCloud Mail", + "aliases": ["Me", "Mac"], + "domains": ["me.com", "mac.com"], + "host": "smtp.mail.me.com", + "port": 587 + }, + + "Infomaniak": { + "description": "Infomaniak Mail (Swiss hosting provider)", + "host": "mail.infomaniak.com", + "domains": ["ik.me", "ikmail.com", "etik.com"], + "port": 587 + }, + + "KolabNow": { + "description": "KolabNow (secure email service)", + "domains": ["kolabnow.com"], + "aliases": ["Kolab"], + "host": "smtp.kolabnow.com", + "port": 465, + "secure": true, + "authMethod": "LOGIN" + }, + + "Loopia": { + "description": "Loopia (Swedish hosting provider)", + "host": "mailcluster.loopia.se", + "port": 465 + }, + + "Loops": { + "description": "Loops", + "host": "smtp.loops.so", + "port": 587 + }, + + "mail.ee": { + "description": "Mail.ee (Estonian email provider)", + "host": "smtp.mail.ee" + }, + + "Mail.ru": { + "description": "Mail.ru", + "host": "smtp.mail.ru", + "port": 465, + "secure": true + }, + + "Mailcatch.app": { + "description": "Mailcatch (email testing service)", + "host": "sandbox-smtp.mailcatch.app", + "port": 2525 + }, + + "Maildev": { + "description": "MailDev (local email testing)", + "port": 1025, + "ignoreTLS": true + }, + + "MailerSend": { + "description": "MailerSend", + "host": "smtp.mailersend.net", + "port": 587 + }, + + "Mailgun": { + "description": "Mailgun", + "host": "smtp.mailgun.org", + "port": 465, + "secure": true + }, + + "Mailjet": { + "description": "Mailjet", + "host": "in.mailjet.com", + "port": 587 + }, + + "Mailosaur": { + "description": "Mailosaur (email testing service)", + "host": "mailosaur.io", + "port": 25 + }, + + "Mailtrap": { + "description": "Mailtrap", + "host": "live.smtp.mailtrap.io", + "port": 587 + }, + + "Mandrill": { + "description": "Mandrill (by Mailchimp)", + "host": "smtp.mandrillapp.com", + "port": 587 + }, + + "Naver": { + "description": "Naver Mail (Korean email provider)", + "host": "smtp.naver.com", + "port": 587 + }, + + "OhMySMTP": { + "description": "OhMySMTP (email delivery service)", + "host": "smtp.ohmysmtp.com", + "port": 587, + "secure": false + }, + + "One": { + "description": "One.com Email", + "host": "send.one.com", + "port": 465, + "secure": true + }, + + "OpenMailBox": { + "description": "OpenMailBox", + "aliases": ["OMB", "openmailbox.org"], + "host": "smtp.openmailbox.org", + "port": 465, + "secure": true + }, + + "Outlook365": { + "description": "Microsoft 365 / Office 365", + "host": "smtp.office365.com", + "port": 587, + "secure": false + }, + + "Postmark": { + "description": "Postmark", + "aliases": ["PostmarkApp"], + "host": "smtp.postmarkapp.com", + "port": 2525 + }, + + "Proton": { + "description": "Proton Mail", + "aliases": ["ProtonMail", "Proton.me", "Protonmail.com", "Protonmail.ch"], + "domains": ["proton.me", "protonmail.com", "pm.me", "protonmail.ch"], + "host": "smtp.protonmail.ch", + "port": 587, + "requireTLS": true + }, + + "qiye.aliyun": { + "description": "Alibaba Mail Enterprise Edition", + "host": "smtp.mxhichina.com", + "port": "465", + "secure": true + }, + + "QQ": { + "description": "QQ Mail", + "domains": ["qq.com"], + "host": "smtp.qq.com", + "port": 465, + "secure": true + }, + + "QQex": { + "description": "QQ Enterprise Mail", + "aliases": ["QQ Enterprise"], + "domains": ["exmail.qq.com"], + "host": "smtp.exmail.qq.com", + "port": 465, + "secure": true + }, + + "Resend": { + "description": "Resend", + "host": "smtp.resend.com", + "port": 465, + "secure": true + }, + + "Runbox": { + "description": "Runbox (Norwegian email provider)", + "domains": ["runbox.com"], + "host": "smtp.runbox.com", + "port": 465, + "secure": true + }, + + "SendCloud": { + "description": "SendCloud (Chinese email delivery)", + "host": "smtp.sendcloud.net", + "port": 2525 + }, + + "SendGrid": { + "description": "SendGrid", + "host": "smtp.sendgrid.net", + "port": 587 + }, + + "SendinBlue": { + "description": "Brevo (formerly Sendinblue)", + "aliases": ["Brevo"], + "host": "smtp-relay.brevo.com", + "port": 587 + }, + + "SendPulse": { + "description": "SendPulse", + "host": "smtp-pulse.com", + "port": 465, + "secure": true + }, + + "SES": { + "description": "AWS SES US East (N. Virginia)", + "host": "email-smtp.us-east-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-AP-NORTHEAST-1": { + "description": "AWS SES Asia Pacific (Tokyo)", + "host": "email-smtp.ap-northeast-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-AP-NORTHEAST-2": { + "description": "AWS SES Asia Pacific (Seoul)", + "host": "email-smtp.ap-northeast-2.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-AP-NORTHEAST-3": { + "description": "AWS SES Asia Pacific (Osaka)", + "host": "email-smtp.ap-northeast-3.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-AP-SOUTH-1": { + "description": "AWS SES Asia Pacific (Mumbai)", + "host": "email-smtp.ap-south-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-AP-SOUTHEAST-1": { + "description": "AWS SES Asia Pacific (Singapore)", + "host": "email-smtp.ap-southeast-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-AP-SOUTHEAST-2": { + "description": "AWS SES Asia Pacific (Sydney)", + "host": "email-smtp.ap-southeast-2.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-CA-CENTRAL-1": { + "description": "AWS SES Canada (Central)", + "host": "email-smtp.ca-central-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-EU-CENTRAL-1": { + "description": "AWS SES Europe (Frankfurt)", + "host": "email-smtp.eu-central-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-EU-NORTH-1": { + "description": "AWS SES Europe (Stockholm)", + "host": "email-smtp.eu-north-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-EU-WEST-1": { + "description": "AWS SES Europe (Ireland)", + "host": "email-smtp.eu-west-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-EU-WEST-2": { + "description": "AWS SES Europe (London)", + "host": "email-smtp.eu-west-2.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-EU-WEST-3": { + "description": "AWS SES Europe (Paris)", + "host": "email-smtp.eu-west-3.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-SA-EAST-1": { + "description": "AWS SES South America (São Paulo)", + "host": "email-smtp.sa-east-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-US-EAST-1": { + "description": "AWS SES US East (N. Virginia)", + "host": "email-smtp.us-east-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-US-EAST-2": { + "description": "AWS SES US East (Ohio)", + "host": "email-smtp.us-east-2.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-US-GOV-EAST-1": { + "description": "AWS SES GovCloud (US-East)", + "host": "email-smtp.us-gov-east-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-US-GOV-WEST-1": { + "description": "AWS SES GovCloud (US-West)", + "host": "email-smtp.us-gov-west-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-US-WEST-1": { + "description": "AWS SES US West (N. California)", + "host": "email-smtp.us-west-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-US-WEST-2": { + "description": "AWS SES US West (Oregon)", + "host": "email-smtp.us-west-2.amazonaws.com", + "port": 465, + "secure": true + }, + + "Seznam": { + "description": "Seznam Email (Czech email provider)", + "aliases": ["Seznam Email"], + "domains": ["seznam.cz", "email.cz", "post.cz", "spoluzaci.cz"], + "host": "smtp.seznam.cz", + "port": 465, + "secure": true + }, + + "SMTP2GO": { + "description": "SMTP2GO", + "host": "mail.smtp2go.com", + "port": 2525 + }, + + "Sparkpost": { + "description": "SparkPost", + "aliases": ["SparkPost", "SparkPost Mail"], + "domains": ["sparkpost.com"], + "host": "smtp.sparkpostmail.com", + "port": 587, + "secure": false + }, + + "Tipimail": { + "description": "Tipimail (email delivery service)", + "host": "smtp.tipimail.com", + "port": 587 + }, + + "Tutanota": { + "description": "Tutanota (Tuta Mail)", + "domains": ["tutanota.com", "tuta.com", "tutanota.de", "tuta.io"], + "host": "smtp.tutanota.com", + "port": 465, + "secure": true + }, + + "Yahoo": { + "description": "Yahoo Mail", + "domains": ["yahoo.com"], + "host": "smtp.mail.yahoo.com", + "port": 465, + "secure": true + }, + + "Yandex": { + "description": "Yandex Mail", + "domains": ["yandex.ru"], + "host": "smtp.yandex.ru", + "port": 465, + "secure": true + }, + + "Zimbra": { + "description": "Zimbra Mail Server", + "aliases": ["Zimbra Collaboration"], + "host": "smtp.zimbra.com", + "port": 587, + "requireTLS": true + }, + + "Zoho": { + "description": "Zoho Mail", + "host": "smtp.zoho.com", + "port": 465, + "secure": true, + "authMethod": "LOGIN" + } +} diff --git a/node_modules/nodemailer/lib/xoauth2/index.js b/node_modules/nodemailer/lib/xoauth2/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a1e5601b6fff0516da8ff529ab51f576d0915b0f --- /dev/null +++ b/node_modules/nodemailer/lib/xoauth2/index.js @@ -0,0 +1,449 @@ +'use strict'; + +const { Stream } = require('stream'); +const nmfetch = require('../fetch'); +const crypto = require('crypto'); +const shared = require('../shared'); +const errors = require('../errors'); + +/** + * XOAUTH2 access_token generator for Gmail. + * Create client ID for web applications in Google API console to use it. + * See Offline Access for receiving the needed refreshToken for an user + * https://developers.google.com/accounts/docs/OAuth2WebServer#offline + * + * Usage for generating access tokens with a custom method using provisionCallback: + * provisionCallback(user, renew, callback) + * * user is the username to get the token for + * * renew is a boolean that if true indicates that existing token failed and needs to be renewed + * * callback is the callback to run with (error, accessToken [, expires]) + * * accessToken is a string + * * expires is an optional expire time in milliseconds + * If provisionCallback is used, then Nodemailer does not try to attempt generating the token by itself + * + * @constructor + * @param {Object} options Client information for token generation + * @param {String} options.user User e-mail address + * @param {String} options.clientId Client ID value + * @param {String} options.clientSecret Client secret value + * @param {String} options.refreshToken Refresh token for an user + * @param {String} options.accessUrl Endpoint for token generation, defaults to 'https://accounts.google.com/o/oauth2/token' + * @param {String} options.accessToken An existing valid accessToken + * @param {String} options.privateKey Private key for JSW + * @param {Number} options.expires Optional Access Token expire time in ms + * @param {Number} options.timeout Optional TTL for Access Token in seconds + * @param {Function} options.provisionCallback Function to run when a new access token is required + * @param {Object} options.tls Optional TLS options forwarded to the HTTPS token request. Defaults to strict cert validation; supply { rejectUnauthorized: false } only for self-hosted OAuth providers on private CAs. + */ +class XOAuth2 extends Stream { + constructor(options, logger) { + super(); + + this.options = options || {}; + + if (options && options.serviceClient) { + if (!options.privateKey || !options.user) { + const err = new Error('Options "privateKey" and "user" are required for service account!'); + err.code = errors.EOAUTH2; + setImmediate(() => this.emit('error', err)); + return; + } + + const serviceRequestTimeout = Math.min(Math.max(Number(this.options.serviceRequestTimeout) || 0, 0), 3600); + this.options.serviceRequestTimeout = serviceRequestTimeout || 5 * 60; + } + + this.logger = shared.getLogger( + { + logger + }, + { + component: this.options.component || 'OAuth2' + } + ); + + this.provisionCallback = typeof this.options.provisionCallback === 'function' ? this.options.provisionCallback : false; + + this.options.accessUrl = this.options.accessUrl || 'https://accounts.google.com/o/oauth2/token'; + this.options.customHeaders = this.options.customHeaders || {}; + this.options.customParams = this.options.customParams || {}; + + this.accessToken = this.options.accessToken || false; + + if (this.options.expires && Number(this.options.expires)) { + this.expires = this.options.expires; + } else { + const timeout = Math.max(Number(this.options.timeout) || 0, 0); + this.expires = (timeout && Date.now() + timeout * 1000) || 0; + } + + this.renewing = false; // Track if renewal is in progress + this.renewalQueue = []; // Queue for pending requests during renewal + } + + /** + * Returns or generates (if previous has expired) a XOAuth2 token + * + * @param {Boolean} renew If false then use cached access token (if available) + * @param {Function} callback Callback function with error object and token string + */ + getToken(renew, callback) { + if (!renew && this.accessToken && (!this.expires || this.expires > Date.now())) { + this.logger.debug( + { + tnx: 'OAUTH2', + user: this.options.user, + action: 'reuse' + }, + 'Reusing existing access token for %s', + this.options.user + ); + return callback(null, this.accessToken); + } + + // check if it is possible to renew, if not, return the current token or error + if (!this.provisionCallback && !this.options.refreshToken && !this.options.serviceClient) { + if (this.accessToken) { + this.logger.debug( + { + tnx: 'OAUTH2', + user: this.options.user, + action: 'reuse' + }, + 'Reusing existing access token (no refresh capability) for %s', + this.options.user + ); + return callback(null, this.accessToken); + } + this.logger.error( + { + tnx: 'OAUTH2', + user: this.options.user, + action: 'renew' + }, + 'Cannot renew access token for %s: No refresh mechanism available', + this.options.user + ); + const err = new Error("Can't create new access token for user"); + err.code = errors.EOAUTH2; + return callback(err); + } + + // If renewal already in progress, queue this request instead of starting another + if (this.renewing) { + return this.renewalQueue.push({ renew, callback }); + } + + this.renewing = true; + + // Handles token renewal completion - processes queued requests and cleans up + const generateCallback = (err, accessToken) => { + this.renewalQueue.forEach(item => item.callback(err, accessToken)); + this.renewalQueue = []; + this.renewing = false; + + if (err) { + this.logger.error( + { + err, + tnx: 'OAUTH2', + user: this.options.user, + action: 'renew' + }, + 'Failed generating new Access Token for %s', + this.options.user + ); + } else { + this.logger.info( + { + tnx: 'OAUTH2', + user: this.options.user, + action: 'renew' + }, + 'Generated new Access Token for %s', + this.options.user + ); + } + // Complete original request + callback(err, accessToken); + }; + + if (this.provisionCallback) { + this.provisionCallback(this.options.user, !!renew, (err, accessToken, expires) => { + if (!err && accessToken) { + this.accessToken = accessToken; + this.expires = expires || 0; + } + generateCallback(err, accessToken); + }); + } else { + this.generateToken(generateCallback); + } + } + + /** + * Updates token values + * + * @param {String} accessToken New access token + * @param {Number} timeout Access token lifetime in seconds + * + * Emits 'token': { user: User email-address, accessToken: the new accessToken, timeout: TTL in seconds} + */ + updateToken(accessToken, timeout) { + this.accessToken = accessToken; + timeout = Math.max(Number(timeout) || 0, 0); + this.expires = (timeout && Date.now() + timeout * 1000) || 0; + + this.emit('token', { + user: this.options.user, + accessToken: accessToken || '', + expires: this.expires + }); + } + + /** + * Generates a new XOAuth2 token with the credentials provided at initialization + * + * @param {Function} callback Callback function with error object and token string + */ + generateToken(callback) { + let urlOptions; + let loggedUrlOptions; + if (this.options.serviceClient) { + // service account - https://developers.google.com/identity/protocols/OAuth2ServiceAccount + const iat = Math.floor(Date.now() / 1000); // unix time + const tokenData = { + iss: this.options.serviceClient, + scope: this.options.scope || 'https://mail.google.com/', + sub: this.options.user, + aud: this.options.accessUrl, + iat, + exp: iat + this.options.serviceRequestTimeout + }; + let token; + try { + token = this.jwtSignRS256(tokenData); + } catch (_err) { + const err = new Error("Can't generate token. Check your auth options"); + err.code = errors.EOAUTH2; + return callback(err); + } + + urlOptions = { + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion: token + }; + + loggedUrlOptions = { + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion: tokenData + }; + } else { + if (!this.options.refreshToken) { + const err = new Error("Can't create new access token for user"); + err.code = errors.EOAUTH2; + return callback(err); + } + + // web app - https://developers.google.com/identity/protocols/OAuth2WebServer + urlOptions = { + client_id: this.options.clientId || '', + client_secret: this.options.clientSecret || '', + refresh_token: this.options.refreshToken, + grant_type: 'refresh_token' + }; + + loggedUrlOptions = { + client_id: this.options.clientId || '', + client_secret: (this.options.clientSecret || '').substr(0, 6) + '...', + refresh_token: (this.options.refreshToken || '').substr(0, 6) + '...', + grant_type: 'refresh_token' + }; + } + + Object.assign(urlOptions, this.options.customParams); + Object.assign(loggedUrlOptions, this.options.customParams); + + this.logger.debug( + { + tnx: 'OAUTH2', + user: this.options.user, + action: 'generate' + }, + 'Requesting token using: %s', + JSON.stringify(loggedUrlOptions) + ); + + this.postRequest(this.options.accessUrl, urlOptions, this.options, (error, body) => { + let data; + + if (error) { + return callback(error); + } + + try { + data = JSON.parse(body.toString()); + } catch (E) { + return callback(E); + } + + if (!data || typeof data !== 'object') { + this.logger.debug( + { + tnx: 'OAUTH2', + user: this.options.user, + action: 'post' + }, + 'Response: %s', + (body || '').toString() + ); + const err = new Error('Invalid authentication response'); + err.code = errors.EOAUTH2; + return callback(err); + } + + const logData = Object.assign({}, data); + if (logData.access_token) { + logData.access_token = (logData.access_token || '').toString().substr(0, 6) + '...'; + } + + this.logger.debug( + { + tnx: 'OAUTH2', + user: this.options.user, + action: 'post' + }, + 'Response: %s', + JSON.stringify(logData) + ); + + if (data.error) { + // Error Response : https://tools.ietf.org/html/rfc6749#section-5.2 + let errorMessage = data.error; + if (data.error_description) { + errorMessage += ': ' + data.error_description; + } + if (data.error_uri) { + errorMessage += ' (' + data.error_uri + ')'; + } + const err = new Error(errorMessage); + err.code = errors.EOAUTH2; + return callback(err); + } + + if (data.access_token) { + this.updateToken(data.access_token, data.expires_in); + return callback(null, this.accessToken); + } + + const err = new Error('No access token'); + err.code = errors.EOAUTH2; + return callback(err); + }); + } + + /** + * Converts an access_token and user id into a base64 encoded XOAuth2 token + * + * @param {String} [accessToken] Access token string + * @return {String} Base64 encoded token for IMAP or SMTP login + */ + buildXOAuth2Token(accessToken) { + const authData = ['user=' + (this.options.user || ''), 'auth=Bearer ' + (accessToken || this.accessToken), '', '']; + return Buffer.from(authData.join('\x01'), 'utf-8').toString('base64'); + } + + /** + * Custom POST request handler. + * This is only needed to keep paths short in Windows – usually this module + * is a dependency of a dependency and if it tries to require something + * like the request module the paths get way too long to handle for Windows. + * As we do only a simple POST request we do not actually require complicated + * logic support (no redirects, no nothing) anyway. + * + * @param {String} url Url to POST to + * @param {String|Buffer} payload Payload to POST + * @param {Function} callback Callback function with (err, buff) + */ + postRequest(url, payload, params, callback) { + let returned = false; + + const chunks = []; + let chunklen = 0; + + const fetchOptions = { + method: 'post', + headers: params.customHeaders, + body: payload, + allowErrorResponse: true + }; + + // OAuth2 token endpoints are credential-bearing. lib/fetch defaults to + // rejectUnauthorized:false (intentional for self-signed attachment + // hosts), so opt back in to strict cert validation here when the + // access URL is HTTPS. params.tls (the user's options.tls) is layered + // on top so callers with a self-hosted provider on a private CA can + // still override. + if (/^https:/i.test(url)) { + fetchOptions.tls = Object.assign({ rejectUnauthorized: true }, params.tls || {}); + } + + const req = nmfetch(url, fetchOptions); + + req.on('readable', () => { + let chunk; + while ((chunk = req.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; + } + }); + + req.once('error', err => { + if (returned) { + return; + } + returned = true; + return callback(err); + }); + + req.once('end', () => { + if (returned) { + return; + } + returned = true; + return callback(null, Buffer.concat(chunks, chunklen)); + }); + } + + /** + * Encodes a buffer or a string into Base64url format + * + * @param {Buffer|String} data The data to convert + * @return {String} The encoded string + */ + toBase64URL(data) { + if (typeof data === 'string') { + data = Buffer.from(data); + } + + return data + .toString('base64') + .replace(/[=]+/g, '') // remove '='s + .replace(/\+/g, '-') // '+' → '-' + .replace(/\//g, '_'); // '/' → '_' + } + + /** + * Creates a JSON Web Token signed with RS256 (SHA256 + RSA) + * + * @param {Object} payload The payload to include in the generated token + * @return {String} The generated and signed token + */ + jwtSignRS256(payload) { + payload = ['{"alg":"RS256","typ":"JWT"}', JSON.stringify(payload)].map(val => this.toBase64URL(val)).join('.'); + const signature = crypto.createSign('RSA-SHA256').update(payload).sign(this.options.privateKey); + return payload + '.' + this.toBase64URL(signature); + } +} + +module.exports = XOAuth2; diff --git a/node_modules/nodemailer/package.json b/node_modules/nodemailer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d19be43ac261f409c1dadff13b9fd485ba08eed9 --- /dev/null +++ b/node_modules/nodemailer/package.json @@ -0,0 +1,47 @@ +{ + "name": "nodemailer", + "version": "8.0.11", + "description": "Easy as cake e-mail sending from your Node.js applications", + "main": "lib/nodemailer.js", + "scripts": { + "test": "node --test --test-concurrency=1 $(find test \\( -name '*-test.js' -o -name '*.test.js' \\))", + "test:coverage": "c8 node --test --test-concurrency=1 $(find test \\( -name '*-test.js' -o -name '*.test.js' \\))", + "format": "prettier --write \"**/*.{js,json,md}\"", + "format:check": "prettier --check \"**/*.{js,json,md}\"", + "lint": "eslint .", + "lint:fix": "eslint . --fix", + "update": "rm -rf node_modules/ package-lock.json && ncu -u && npm install", + "test:syntax": "docker run --rm -v \"$PWD:/app:ro\" -w /app node:6-alpine node test/syntax-compat.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/nodemailer/nodemailer.git" + }, + "keywords": [ + "Nodemailer" + ], + "author": "Andris Reinman", + "license": "MIT-0", + "bugs": { + "url": "https://github.com/nodemailer/nodemailer/issues" + }, + "homepage": "https://nodemailer.com/", + "devDependencies": { + "@aws-sdk/client-sesv2": "3.1065.0", + "bunyan": "1.8.15", + "c8": "11.0.0", + "eslint": "10.4.1", + "eslint-config-prettier": "10.1.8", + "globals": "17.6.0", + "libbase64": "1.3.0", + "libmime": "5.3.8", + "libqp": "2.1.1", + "prettier": "3.8.4", + "proxy": "1.0.2", + "proxy-test-server": "1.0.0", + "smtp-server": "3.18.5" + }, + "engines": { + "node": ">=6.0.0" + } +} diff --git a/node_modules/nodemon/.prettierrc.json b/node_modules/nodemon/.prettierrc.json new file mode 100644 index 0000000000000000000000000000000000000000..544138be45652abc7bc3873341deacd3f4f90c61 --- /dev/null +++ b/node_modules/nodemon/.prettierrc.json @@ -0,0 +1,3 @@ +{ + "singleQuote": true +} diff --git a/node_modules/nodemon/LICENSE b/node_modules/nodemon/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..19c91a2f3ba9a1b12b0b232adcabbf9cf2a131c3 --- /dev/null +++ b/node_modules/nodemon/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2010 - present, Remy Sharp, https://remysharp.com + +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. diff --git a/node_modules/nodemon/README.md b/node_modules/nodemon/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ce94710b9cbf58bbd3c8febfcc12ce4b643d598a --- /dev/null +++ b/node_modules/nodemon/README.md @@ -0,0 +1,439 @@ +

+ Nodemon Logo +

+ +# nodemon + +nodemon is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected. + +nodemon does **not** require *any* additional changes to your code or method of development. nodemon is a replacement wrapper for `node`. To use `nodemon`, replace the word `node` on the command line when executing your script. + +[![NPM version](https://badge.fury.io/js/nodemon.svg)](https://npmjs.org/package/nodemon) +[![Backers on Open Collective](https://opencollective.com/nodemon/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/nodemon/sponsors/badge.svg)](#sponsors) + +# Installation + +Either through cloning with git or by using [npm](http://npmjs.org) (the recommended way): + +```bash +npm install -g nodemon # or using yarn: yarn global add nodemon +``` + +And nodemon will be installed globally to your system path. + +You can also install nodemon as a development dependency: + +```bash +npm install --save-dev nodemon # or using yarn: yarn add nodemon -D +``` + +With a local installation, nodemon will not be available in your system path or you can't use it directly from the command line. Instead, the local installation of nodemon can be run by calling it from within an npm script (such as `npm start`) or using `npx nodemon`. + +# Usage + +nodemon wraps your application, so you can pass all the arguments you would normally pass to your app: + +```bash +nodemon [your node app] +``` + +For CLI options, use the `-h` (or `--help`) argument: + +```bash +nodemon -h +``` + +Using nodemon is simple, if my application accepted a host and port as the arguments, I would start it as so: + +```bash +nodemon ./server.js localhost 8080 +``` + +Any output from this script is prefixed with `[nodemon]`, otherwise all output from your application, errors included, will be echoed out as expected. + +You can also pass the `inspect` flag to node through the command line as you would normally: + +```bash +nodemon --inspect ./server.js 80 +``` + +If you have a `package.json` file for your app, you can omit the main script entirely and nodemon will read the `package.json` for the `main` property and use that value as the app ([ref](https://github.com/remy/nodemon/issues/14)). + +nodemon will also search for the `scripts.start` property in `package.json` (as of nodemon 1.1.x). + +Also check out the [FAQ](https://github.com/remy/nodemon/blob/master/faq.md) or [issues](https://github.com/remy/nodemon/issues) for nodemon. + +## Automatic re-running + +nodemon was originally written to restart hanging processes such as web servers, but now supports apps that cleanly exit. If your script exits cleanly, nodemon will continue to monitor the directory (or directories) and restart the script if there are any changes. + +## Manual restarting + +Whilst nodemon is running, if you need to manually restart your application, instead of stopping and restart nodemon, you can type `rs` with a carriage return, and nodemon will restart your process. + +## Config files + +nodemon supports local and global configuration files. These are usually named `nodemon.json` and can be located in the current working directory or in your home directory. An alternative local configuration file can be specified with the `--config ` option. + +The specificity is as follows, so that a command line argument will always override the config file settings: + +- command line arguments +- local config +- global config + +A config file can take any of the command line arguments as JSON key values, for example: + +```json +{ + "verbose": true, + "ignore": ["*.test.js", "**/fixtures/**"], + "execMap": { + "rb": "ruby", + "pde": "processing --sketch={{pwd}} --run" + } +} +``` + +The above `nodemon.json` file might be my global config so that I have support for ruby files and processing files, and I can run `nodemon demo.pde` and nodemon will automatically know how to run the script even though out of the box support for processing scripts. + +A further example of options can be seen in [sample-nodemon.md](https://github.com/remy/nodemon/blob/master/doc/sample-nodemon.md) + +### package.json + +If you want to keep all your package configurations in one place, nodemon supports using `package.json` for configuration. +Specify the config in the same format as you would for a config file but under `nodemonConfig` in the `package.json` file, for example, take the following `package.json`: + +```json +{ + "name": "nodemon", + "homepage": "http://nodemon.io", + "...": "... other standard package.json values", + "nodemonConfig": { + "ignore": ["**/test/**", "**/docs/**"], + "delay": 2500 + } +} +``` + +Note that if you specify a `--config` file or provide a local `nodemon.json` any `package.json` config is ignored. + +*This section needs better documentation, but for now you can also see `nodemon --help config` ([also here](https://github.com/remy/nodemon/blob/master/doc/cli/config.txt))*. + +## Using nodemon as a module + +Please see [doc/requireable.md](doc/requireable.md) + +## Using nodemon as child process + +Please see [doc/events.md](doc/events.md#Using_nodemon_as_child_process) + +## Running non-node scripts + +nodemon can also be used to execute and monitor other programs. nodemon will read the file extension of the script being run and monitor that extension instead of `.js` if there's no `nodemon.json`: + +```bash +nodemon --exec "python -v" ./app.py +``` + +Now nodemon will run `app.py` with python in verbose mode (note that if you're not passing args to the exec program, you don't need the quotes), and look for new or modified files with the `.py` extension. + +### Default executables + +Using the `nodemon.json` config file, you can define your own default executables using the `execMap` property. This is particularly useful if you're working with a language that isn't supported by default by nodemon. + +To add support for nodemon to know about the `.pl` extension (for Perl), the `nodemon.json` file would add: + +```json +{ + "execMap": { + "pl": "perl" + } +} +``` + +Now running the following, nodemon will know to use `perl` as the executable: + +```bash +nodemon script.pl +``` + +It's generally recommended to use the global `nodemon.json` to add your own `execMap` options. However, if there's a common default that's missing, this can be merged in to the project so that nodemon supports it by default, by changing [default.js](https://github.com/remy/nodemon/blob/master/lib/config/defaults.js) and sending a pull request. + +## Monitoring multiple directories + +By default nodemon monitors the current working directory. If you want to take control of that option, use the `--watch` option to add specific paths: + +```bash +nodemon --watch app --watch libs app/server.js +``` + +Now nodemon will only restart if there are changes in the `./app` or `./libs` directory. By default nodemon will traverse sub-directories, so there's no need in explicitly including sub-directories. + +Nodemon also supports unix globbing, e.g `--watch './lib/*'`. The globbing pattern must be quoted. For advanced globbing, [see `picomatch` documentation](https://github.com/micromatch/picomatch#advanced-globbing), the library that nodemon uses through `chokidar` (which in turn uses it through `anymatch`). + +## Specifying extension watch list + +By default, nodemon looks for files with the `.js`, `.mjs`, `.coffee`, `.litcoffee`, and `.json` extensions. If you use the `--exec` option and monitor `app.py` nodemon will monitor files with the extension of `.py`. However, you can specify your own list with the `-e` (or `--ext`) switch like so: + +```bash +nodemon -e js,pug +``` + +Now nodemon will restart on any changes to files in the directory (or subdirectories) with the extensions `.js`, `.pug`. + +## Ignoring files + +By default, nodemon will only restart when a `.js` JavaScript file changes. In some cases you will want to ignore some specific files, directories or file patterns, to prevent nodemon from prematurely restarting your application. + +This can be done via the command line: + +```bash +nodemon --ignore lib/ --ignore tests/ +``` + +Or specific files can be ignored: + +```bash +nodemon --ignore lib/app.js +``` + +Patterns can also be ignored (but be sure to quote the arguments): + +```bash +nodemon --ignore 'lib/*.js' +``` + +**Important** the ignore rules are patterns matched to the full absolute path, and this determines how many files are monitored. If using a wild card glob pattern, it needs to be used as `**` or omitted entirely. For example, `nodemon --ignore '**/test/**'` will work, whereas `--ignore '*/test/*'` will not. + +Note that by default, nodemon will ignore the `.git`, `node_modules`, `bower_components`, `.nyc_output`, `coverage` and `.sass-cache` directories and *add* your ignored patterns to the list. If you want to indeed watch a directory like `node_modules`, you need to [override the underlying default ignore rules](https://github.com/remy/nodemon/blob/master/faq.md#overriding-the-underlying-default-ignore-rules). + +## Application isn't restarting + +In some networked environments (such as a container running nodemon reading across a mounted drive), you will need to use the `legacyWatch: true` which enables Chokidar's polling. + +Via the CLI, use either `--legacy-watch` or `-L` for short: + +```bash +nodemon -L +``` + +Though this should be a last resort as it will poll every file it can find. + +## Delaying restarting + +In some situations, you may want to wait until a number of files have changed. The timeout before checking for new file changes is 1 second. If you're uploading a number of files and it's taking some number of seconds, this could cause your app to restart multiple times unnecessarily. + +To add an extra throttle, or delay restarting, use the `--delay` command: + +```bash +nodemon --delay 10 server.js +``` + +For more precision, milliseconds can be specified. Either as a float: + +```bash +nodemon --delay 2.5 server.js +``` + +Or using the time specifier (ms): + +```bash +nodemon --delay 2500ms server.js +``` + +The delay figure is number of seconds (or milliseconds, if specified) to delay before restarting. So nodemon will only restart your app the given number of seconds after the *last* file change. + +If you are setting this value in `nodemon.json`, the value will always be interpreted in milliseconds. E.g., the following are equivalent: + +```bash +nodemon --delay 2.5 + +{ + "delay": 2500 +} +``` + +## Gracefully reloading down your script + +It is possible to have nodemon send any signal that you specify to your application. + +```bash +nodemon --signal SIGHUP server.js +``` + +Your application can handle the signal as follows. + +```js +process.on("SIGHUP", function () { + reloadSomeConfiguration(); + process.kill(process.pid, "SIGTERM"); +}) +``` + +Please note that nodemon will send this signal to every process in the process tree. + +If you are using `cluster`, then each workers (as well as the master) will receive the signal. If you wish to terminate all workers on receiving a `SIGHUP`, a common pattern is to catch the `SIGHUP` in the master, and forward `SIGTERM` to all workers, while ensuring that all workers ignore `SIGHUP`. + +```js +if (cluster.isMaster) { + process.on("SIGHUP", function () { + for (const worker of Object.values(cluster.workers)) { + worker.process.kill("SIGTERM"); + } + }); +} else { + process.on("SIGHUP", function() {}) +} +``` + +## Controlling shutdown of your script + +nodemon sends a kill signal to your application when it sees a file update. If you need to clean up on shutdown inside your script you can capture the kill signal and handle it yourself. + +The following example will listen once for the `SIGUSR2` signal (used by nodemon to restart), run the clean up process and then kill itself for nodemon to continue control: + +```js +// important to use `on` and not `once` as nodemon can re-send the kill signal +process.on('SIGUSR2', function () { + gracefulShutdown(function () { + process.kill(process.pid, 'SIGTERM'); + }); +}); +``` + +Note that the `process.kill` is *only* called once your shutdown jobs are complete. Hat tip to [Benjie Gillam](http://www.benjiegillam.com/2011/08/node-js-clean-restart-and-faster-development-with-nodemon/) for writing this technique up. + +## Triggering events when nodemon state changes + +If you want growl like notifications when nodemon restarts or to trigger an action when an event happens, then you can either `require` nodemon or add event actions to your `nodemon.json` file. + +For example, to trigger a notification on a Mac when nodemon restarts, `nodemon.json` looks like this: + +```json +{ + "events": { + "restart": "osascript -e 'display notification \"app restarted\" with title \"nodemon\"'" + } +} +``` + +A full list of available events is listed on the [event states wiki](https://github.com/remy/nodemon/wiki/Events#states). Note that you can bind to both states and messages. + +## Pipe output to somewhere else + +```js +nodemon({ + script: ..., + stdout: false // important: this tells nodemon not to output to console +}).on('readable', function() { // the `readable` event indicates that data is ready to pick up + this.stdout.pipe(fs.createWriteStream('output.txt')); + this.stderr.pipe(fs.createWriteStream('err.txt')); +}); +``` + +## Using nodemon in your gulp workflow + +Check out the [gulp-nodemon](https://github.com/JacksonGariety/gulp-nodemon) plugin to integrate nodemon with the rest of your project's gulp workflow. + +## Using nodemon in your Grunt workflow + +Check out the [grunt-nodemon](https://github.com/ChrisWren/grunt-nodemon) plugin to integrate nodemon with the rest of your project's grunt workflow. + +## Pronunciation + +> nodemon, is it pronounced: node-mon, no-demon or node-e-mon (like pokémon)? + +Well...I've been asked this many times before. I like that I've been asked this before. There's been bets as to which one it actually is. + +The answer is simple, but possibly frustrating. I'm not saying (how I pronounce it). It's up to you to call it as you like. All answers are correct :) + +## Design principles + +- Fewer flags is better +- Works across all platforms +- Fewer features +- Let individuals build on top of nodemon +- Offer all CLI functionality as an API +- Contributions must have and pass tests + +Nodemon is not perfect, and CLI arguments has sprawled beyond where I'm completely happy, but perhaps it can be reduced a little one day. + +## FAQ + +See the [FAQ](https://github.com/remy/nodemon/blob/master/faq.md) and please add your own questions if you think they would help others. + +## Backers + +Thank you to all [our backers](https://opencollective.com/nodemon#backer)! 🙏 + +[![nodemon backers](https://opencollective.com/nodemon/backers.svg?width=890)](https://opencollective.com/nodemon#backers) + +## Sponsors + +Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Sponsor this project today ❤️](https://opencollective.com/nodemon#sponsor) + +
Netpositive +Best online casinos not on GamStop in the UK +TheCasinoDB +Goread.io +Best Australian online casinos. Reviewed by Correct Casinos. +Website dedicated to finding the best and safest licensed online casinos in India +nongamstopcasinos.net +Buy Instagram Likes +OnlineCasinosSpelen +Beoordelen van nieuwe online casino's 2023 +CasinoZonderRegistratie.net - Nederlandse Top Casino's +Buy real Instagram followers from Twicsy starting at only $2.97. Twicsy has been voted the best site to buy followers from the likes of US Magazine. +SocialWick offers the best Instagram Followers in the market. If you are looking to boost your organic growth, buy Instagram followers from SocialWick +Buy Telegram Members +We review the entire iGaming industry from A to Z +CryptoCasinos.online +No deposit casino promo Codes 2024 - The best online Casinos websites. No deposit bonus codes, Free Spins and Promo Codes. Stake, Roobet, Jackpotcity and more. +Online casino. +Boost your social media presence effortlessly with top-quality Instagram and TikTok followers and likes. +Social Media Management and all kinds of followers +Betwinner is an online bookmaker offering sports betting, casino games, and more. +At Buzzoid, you can buy Instagram followers quickly, safely, and easily with just a few clicks. Rated world's #1 IG service since 2012. +Zamsino.com +Reviewing and comparing online casinos available to Finnish players. In addition, we publish relevant news and blog posts about the world of iGaming. +Buzzvoice is your one-stop shop for all your social media marketing needs. With Buzzvoice, you can buy followers, comments, likes, video views and more! + +SocialBoosting: Buy Instagram & TikTok Followers, Likes, Views +Ігрові автомати онлайн +Kasinohai.com +Casino Online Chile +casino online chile +Vanguard Media évalue les casinos en ligne pour joueurs français, testant les sites en France. Nos classements stricts garantissent des casinos fiables et sûrs. +Bei Releaf erhalten Sie schnell und diskret Ihr Cannabis Rezept online. Unsere Ärzte prüfen Ihre Angaben und stellen bei Eignung das Rezept aus. Anschließend können Sie legal und sicher medizinisches Cannabis über unsere Partnerapotheken kaufen. +Analysis of online casinos with the best payouts +Download multithreaded HEIC to JPG converter software for Windows 10/11 +We specialize in the online gambling industry, helping players access reliable and verified information about the best online casinos and pokies in Australia. Our team tests casinos and games, collects user reviews from Trustpilot, and organizes them in o +Wolf Winner Casino +AUCrazyVegas +iDealeCasinos + +BetPokies.co.nz is your New Zealand guide in the world of online gambling. Our site was created by gamblers for gamblers. +one x bet - Arabic betting site +Online Casino Zonder Registratie +We test dozens of casinos every month and select the coolest ones for Australian players. +Buy Instagram Followers +Pokies Reviews +Buy TikTok Comments +Mi misión es la educación y transparencia en el mundo de los casinos online +Spreading knowledge about $ETH + +Best online sports betting and casino company. +bestecasinozondercruks +Best online sports betting company in Thailand. +Best online sports betting company in Vietnam. +We testen elke maand tientallen casino’s en kiezen de beste uit voor Nederlandse spelers. +ThePokies Net +Aviator Game Online +Plinko Game +
+ +Please note that links to the sponsors above are not direct endorsements nor affiliated with any of contributors of the nodemon project. + +# License + +MIT [http://rem.mit-license.org](http://rem.mit-license.org) diff --git a/node_modules/nodemon/bin/nodemon.js b/node_modules/nodemon/bin/nodemon.js new file mode 100644 index 0000000000000000000000000000000000000000..3d490f140dd264f98dfb50ab820456c88fe92a64 --- /dev/null +++ b/node_modules/nodemon/bin/nodemon.js @@ -0,0 +1,16 @@ +#!/usr/bin/env node + +const cli = require('../lib/cli'); +const nodemon = require('../lib/'); +const options = cli.parse(process.argv); + +nodemon(options); + +const fs = require('fs'); + +// checks for available update and returns an instance +const pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json')); + +if (pkg.version.indexOf('0.0.0') !== 0 && options.noUpdateNotifier !== true) { + require('simple-update-notifier')({ pkg }); +} diff --git a/node_modules/nodemon/bin/windows-kill.exe b/node_modules/nodemon/bin/windows-kill.exe new file mode 100644 index 0000000000000000000000000000000000000000..98d7d7f7ed95fd8662f82dda3d16203f0d76e580 Binary files /dev/null and b/node_modules/nodemon/bin/windows-kill.exe differ diff --git a/node_modules/nodemon/doc/cli/authors.txt b/node_modules/nodemon/doc/cli/authors.txt new file mode 100644 index 0000000000000000000000000000000000000000..6c77a12aeee2f68df8895db02c3d4b24eb489396 --- /dev/null +++ b/node_modules/nodemon/doc/cli/authors.txt @@ -0,0 +1,8 @@ + + Remy Sharp - author and maintainer + https://github.com/remy + https://twitter.com/rem + + Contributors: https://github.com/remy/nodemon/graphs/contributors ❤︎ + + Please help make nodemon better: https://github.com/remy/nodemon/ diff --git a/node_modules/nodemon/doc/cli/config.txt b/node_modules/nodemon/doc/cli/config.txt new file mode 100644 index 0000000000000000000000000000000000000000..5de9bba5745c38ec8b756a934ada8bce90ef6b27 --- /dev/null +++ b/node_modules/nodemon/doc/cli/config.txt @@ -0,0 +1,44 @@ + + Typically the options to control nodemon are passed in via the CLI and are + listed under: nodemon --help options + + nodemon can also be configured via a local and global config file: + + * $HOME/nodemon.json + * $PWD/nodemon.json OR --config + * nodemonConfig in package.json + + All config options in the .json file map 1-to-1 with the CLI options, so a + config could read as: + + { + "ext": "*.pde", + "verbose": true, + "exec": "processing --sketch=game --run" + } + + There are a limited number of variables available in the config (since you + could use backticks on the CLI to use a variable, backticks won't work in + the .json config). + + * {{pwd}} - the current directory + * {{filename}} - the filename you pass to nodemon + + For example: + + { + "ext": "*.pde", + "verbose": true, + "exec": "processing --sketch={{pwd}} --run" + } + + The global config file is useful for setting up default executables + instead of repeating the same option in each of your local configs: + + { + "verbose": true, + "execMap": { + "rb": "ruby", + "pde": "processing --sketch={{pwd}} --run" + } + } diff --git a/node_modules/nodemon/doc/cli/help.txt b/node_modules/nodemon/doc/cli/help.txt new file mode 100644 index 0000000000000000000000000000000000000000..7ba4ff2a393f67640413a75cc7ff066922b1b956 --- /dev/null +++ b/node_modules/nodemon/doc/cli/help.txt @@ -0,0 +1,29 @@ + Usage: nodemon [options] [script.js] [args] + + Options: + + --config file ............ alternate nodemon.json config file to use + -e, --ext ................ extensions to look for, ie. js,pug,hbs. + -x, --exec app ........... execute script with "app", ie. -x "python -v". + -w, --watch path ......... watch directory "path" or files. use once for + each directory or file to watch. + -i, --ignore ............. ignore specific files or directories. + -V, --verbose ............ show detail on what is causing restarts. + -- ........... to tell nodemon stop slurping arguments. + + Note: if the script is omitted, nodemon will try to read "main" from + package.json and without a nodemon.json, nodemon will monitor .js, .mjs, .coffee, + .litcoffee, and .json by default. + + For advanced nodemon configuration use nodemon.json: nodemon --help config + See also the sample: https://github.com/remy/nodemon/wiki/Sample-nodemon.json + + Examples: + + $ nodemon server.js + $ nodemon -w ../foo server.js apparg1 apparg2 + $ nodemon --exec python app.py + $ nodemon --exec "make build" -e "styl hbs" + $ nodemon app.js -- --config # pass config to app.js + + \x1B[1mAll options are documented under: \x1B[4mnodemon --help options\x1B[0m diff --git a/node_modules/nodemon/doc/cli/logo.txt b/node_modules/nodemon/doc/cli/logo.txt new file mode 100644 index 0000000000000000000000000000000000000000..150f97f591cc291a3bf128d4ab25db9679ab0e4e --- /dev/null +++ b/node_modules/nodemon/doc/cli/logo.txt @@ -0,0 +1,20 @@ + ; ; + kO. x0 + KMX, .:x0kc. 'KMN + 0MMM0: 'oKMMMMMMMXd, ;OMMMX + oMMMMMWKOONMMMMMMMMMMMMMWOOKWMMMMMx + OMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMK. + .oWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMd. + KMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN + KMMMMMMMMMMMMMMW0k0WMMMMMMMMMMMMMMW + KMMMMMMMMMMMNk:. :xNMMMMMMMMMMMW + KMMMMMMMMMMK OMMMMMMMMMMW + KMMMMMMMMMMO xMMMMMMMMMMN + KMMMMMMMMMMO xMMMMMMMMMMN + KMMMMMMMMMMO xMMMMMMMMMMN + KMMMMMMMMMMO xMMMMMMMMMMN + KMMMMMMMMMMO xMMMMMMMMMMN + KMMMMMMMMMNc ;NMMMMMMMMMN + KMMMMMW0o' .lOWMMMMMN + KMMKd; ,oKMMN + kX: ,K0 \ No newline at end of file diff --git a/node_modules/nodemon/doc/cli/options.txt b/node_modules/nodemon/doc/cli/options.txt new file mode 100644 index 0000000000000000000000000000000000000000..598ae63ba310e212a9cac7b2f5449cbd91e9a34f --- /dev/null +++ b/node_modules/nodemon/doc/cli/options.txt @@ -0,0 +1,36 @@ + +Configuration + --config .......... alternate nodemon.json config file to use + --exitcrash .............. exit on crash, allows nodemon to work with other watchers + -i, --ignore ............. ignore specific files or directories + --no-colors .............. disable color output + --signal ........ use specified kill signal instead of default (ex. SIGTERM) + -w, --watch path ......... watch directory "dir" or files. use once for each + directory or file to watch + --no-update-notifier ..... opt-out of update version check + +Execution + -C, --on-change-only ..... execute script on change only, not startup + --cwd .............. change into before running the script + -e, --ext ................ extensions to look for, ie. "js,pug,hbs" + -I, --no-stdin ........... nodemon passes stdin directly to child process + --spawn .................. force nodemon to use spawn (over fork) [node only] + -x, --exec app ........... execute script with "app", ie. -x "python -v" + -- ........... to tell nodemon stop slurping arguments + +Watching + -d, --delay n ............ debounce restart for "n" seconds + -L, --legacy-watch ....... use polling to watch for changes (typically needed + when watching over a network/Docker) + -P, --polling-interval ... combined with -L, milliseconds to poll for (default 100) + +Information + --dump ................... print full debug configuration + -h, --help ............... default help + --help ........... help on a specific feature. Try "--help topics" + -q, --quiet .............. minimise nodemon messages to start/stop only + -v, --version ............ current nodemon version + -V, --verbose ............ show detail on what is causing restarts + + +> Note that any unrecognised arguments are passed to the executing command. diff --git a/node_modules/nodemon/doc/cli/topics.txt b/node_modules/nodemon/doc/cli/topics.txt new file mode 100644 index 0000000000000000000000000000000000000000..9fe3e2b5996cbd408c82d28c3788de95aac0e530 --- /dev/null +++ b/node_modules/nodemon/doc/cli/topics.txt @@ -0,0 +1,8 @@ + + options .................. show all available nodemon options + config ................... default config options using nodemon.json + authors .................. contributors to this project + logo ..................... <3 + whoami ................... I, AM, NODEMON \o/ + + Please support https://github.com/remy/nodemon/ diff --git a/node_modules/nodemon/doc/cli/usage.txt b/node_modules/nodemon/doc/cli/usage.txt new file mode 100644 index 0000000000000000000000000000000000000000..bca98b5e614e6f74f98e19b39384a8f694ae7370 --- /dev/null +++ b/node_modules/nodemon/doc/cli/usage.txt @@ -0,0 +1,3 @@ + Usage: nodemon [nodemon options] [script.js] [args] + + See "nodemon --help" for more. diff --git a/node_modules/nodemon/doc/cli/whoami.txt b/node_modules/nodemon/doc/cli/whoami.txt new file mode 100644 index 0000000000000000000000000000000000000000..efc3382ef38e269516d61e813c49a8d4539688c9 --- /dev/null +++ b/node_modules/nodemon/doc/cli/whoami.txt @@ -0,0 +1,9 @@ +__/\\\\\_____/\\\_______/\\\\\_______/\\\\\\\\\\\\_____/\\\\\\\\\\\\\\\__/\\\\____________/\\\\_______/\\\\\_______/\\\\\_____/\\\_ + _\/\\\\\\___\/\\\_____/\\\///\\\____\/\\\////////\\\__\/\\\///////////__\/\\\\\\________/\\\\\\_____/\\\///\\\____\/\\\\\\___\/\\\_ + _\/\\\/\\\__\/\\\___/\\\/__\///\\\__\/\\\______\//\\\_\/\\\_____________\/\\\//\\\____/\\\//\\\___/\\\/__\///\\\__\/\\\/\\\__\/\\\_ + _\/\\\//\\\_\/\\\__/\\\______\//\\\_\/\\\_______\/\\\_\/\\\\\\\\\\\_____\/\\\\///\\\/\\\/_\/\\\__/\\\______\//\\\_\/\\\//\\\_\/\\\_ + _\/\\\\//\\\\/\\\_\/\\\_______\/\\\_\/\\\_______\/\\\_\/\\\///////______\/\\\__\///\\\/___\/\\\_\/\\\_______\/\\\_\/\\\\//\\\\/\\\_ + _\/\\\_\//\\\/\\\_\//\\\______/\\\__\/\\\_______\/\\\_\/\\\_____________\/\\\____\///_____\/\\\_\//\\\______/\\\__\/\\\_\//\\\/\\\_ + _\/\\\__\//\\\\\\__\///\\\__/\\\____\/\\\_______/\\\__\/\\\_____________\/\\\_____________\/\\\__\///\\\__/\\\____\/\\\__\//\\\\\\_ + _\/\\\___\//\\\\\____\///\\\\\/_____\/\\\\\\\\\\\\/___\/\\\\\\\\\\\\\\\_\/\\\_____________\/\\\____\///\\\\\/_____\/\\\___\//\\\\\_ + _\///_____\/////_______\/////_______\////////////_____\///////////////__\///______________\///_______\/////_______\///_____\/////__ \ No newline at end of file diff --git a/node_modules/nodemon/index.d.ts b/node_modules/nodemon/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..42be595dd8cb30388518d304966831ab7451afdc --- /dev/null +++ b/node_modules/nodemon/index.d.ts @@ -0,0 +1,124 @@ +import type { WatchOptions } from 'chokidar'; + +export type NodemonEventHandler = + | 'start' + | 'crash' + | 'exit' + | 'quit' + | 'restart' + | 'config:update' + | 'log' + | 'readable' + | 'stdout' + | 'stderr'; + +export type NodemonEventListener = { + on(event: 'start' | 'crash' | 'readable', listener: () => void): Nodemon; + on(event: 'log', listener: (e: NodemonEventLog) => void): Nodemon; + on(event: 'stdout' | 'stderr', listener: (e: string) => void): Nodemon; + on(event: 'restart', listener: (files?: string[]) => void): Nodemon; + on(event: 'quit', listener: (e?: NodemonEventQuit) => void): Nodemon; + on(event: 'exit', listener: (e?: number) => void): Nodemon; + on( + event: 'config:update', + listener: (e?: NodemonEventConfig) => void, + ): Nodemon; +}; + +export type NodemonEventLog = { + /** + - detail: what you get with nodemon --verbose. + - status: subprocess starting, restarting. + - fail: is the subprocess crashing. + - error: is a nodemon system error. + */ + type: 'detail' | 'log' | 'status' | 'error' | 'fail'; + /** the plain text message */ + message: string; + /** contains the terminal escape codes to add colour, plus the "[nodemon]" prefix */ + colour: string; +}; + +export type NodemonEventQuit = 143 | 130; + +export type NodemonEventConfig = { + run: boolean; + system: { + cwd: string; + }; + required: boolean; + dirs: string[]; + timeout: number; + options: NodemonConfig; + lastStarted: number; + loaded: string[]; + load: ( + settings: NodemonSettings, + ready: (config: NodemonEventConfig) => void, + ) => void; + reset: () => void; +}; + +export interface NodemonExecOptions { + script: string; + scriptPosition?: number; + args?: string[]; + ext?: string; // "js,mjs" etc (should really support an array of strings, but I don't think it does right now) + exec?: string; // node, python, etc + execArgs?: string[]; // args passed to node, etc, + nodeArgs?: string[]; // args passed to node, etc, +} + +export interface NodemonConfig { + /** restartable defaults to "rs" as a string the user enters */ + restartable?: false | string; + colours?: boolean; + execMap?: { [key: string]: string }; + ignoreRoot?: string[]; + watch?: string[]; + ignore?: string[]; + stdin?: boolean; + runOnChangeOnly?: boolean; + verbose?: boolean; + signal?: string; + stdout?: boolean; + watchOptions?: WatchOptions; + help?: string; + version?: boolean; + cwd?: string; + dump?: boolean; + delay?: number; + monitor?: string[]; + spawn?: boolean; + noUpdateNotifier?: boolean; + legacyWatch?: boolean; + pollingInterval?: number; + /** @deprecated as this is "on" by default */ + js?: boolean; + quiet?: boolean; + configFile?: string; + exitCrash?: boolean; + execOptions?: NodemonExecOptions; +} + +export interface NodemonSettings extends NodemonConfig, NodemonExecOptions { + events?: Record; + env?: Record; +} + +export type Nodemon = { + (settings: NodemonSettings): Nodemon; + removeAllListeners(event: NodemonEventHandler): Nodemon; + emit(type: NodemonEventHandler, event?: any): Nodemon; + reset(callback: Function): Nodemon; + restart(): Nodemon; + config: NodemonSettings; +} & NodemonEventListener & { + [K in keyof NodemonEventListener as 'addListener']: NodemonEventListener[K]; + } & { + [K in keyof NodemonEventListener as 'once']: NodemonEventListener[K]; + }; + +declare const nodemon: Nodemon; + +export = nodemon; diff --git a/node_modules/nodemon/jsconfig.json b/node_modules/nodemon/jsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d77141cb5f4b08384f3a69650fd702e6d8f094a7 --- /dev/null +++ b/node_modules/nodemon/jsconfig.json @@ -0,0 +1,7 @@ +{ + "compilerOptions": { + "typeRoots": ["./index.d.ts", "./node_modules/@types"], + "checkJs": true + }, + "exclude": ["node_modules"] +} diff --git a/node_modules/nodemon/lib/cli/index.js b/node_modules/nodemon/lib/cli/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bf9e80991e4e0a553866499b96877328a2b96042 --- /dev/null +++ b/node_modules/nodemon/lib/cli/index.js @@ -0,0 +1,49 @@ +var parse = require('./parse'); + +/** + * Converts a string to command line args, in particular + * groups together quoted values. + * This is a utility function to allow calling nodemon as a required + * library, but with the CLI args passed in (instead of an object). + * + * @param {String} string + * @return {Array} + */ +function stringToArgs(string) { + var args = []; + + var parts = string.split(' '); + var length = parts.length; + var i = 0; + var open = false; + var grouped = ''; + var lead = ''; + + for (; i < length; i++) { + lead = parts[i].substring(0, 1); + if (lead === '"' || lead === '\'') { + open = lead; + grouped = parts[i].substring(1); + } else if (open && parts[i].slice(-1) === open) { + open = false; + grouped += ' ' + parts[i].slice(0, -1); + args.push(grouped); + } else if (open) { + grouped += ' ' + parts[i]; + } else { + args.push(parts[i]); + } + } + + return args; +} + +module.exports = { + parse: function (argv) { + if (typeof argv === 'string') { + argv = stringToArgs(argv); + } + + return parse(argv); + }, +}; \ No newline at end of file diff --git a/node_modules/nodemon/lib/cli/parse.js b/node_modules/nodemon/lib/cli/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..560cc71534e0439ae591ea994ab0338796565fb2 --- /dev/null +++ b/node_modules/nodemon/lib/cli/parse.js @@ -0,0 +1,230 @@ +/* + +nodemon is a utility for node, and replaces the use of the executable +node. So the user calls `nodemon foo.js` instead. + +nodemon can be run in a number of ways: + +`nodemon` - tries to use package.json#main property to run +`nodemon` - if no package, looks for index.js +`nodemon app.js` - runs app.js +`nodemon --arg app.js --apparg` - eats arg1, and runs app.js with apparg +`nodemon --apparg` - as above, but passes apparg to package.json#main (or + index.js) +`nodemon --debug app.js + +*/ + +var fs = require('fs'); +var path = require('path'); +var existsSync = fs.existsSync || path.existsSync; + +module.exports = parse; + +/** + * Parses the command line arguments `process.argv` and returns the + * nodemon options, the user script and the executable script. + * + * @param {Array | string} argv full process arguments, including `node` leading arg + * @return {Object} { options, script, args } + */ +function parse(argv) { + if (typeof argv === 'string') { + argv = argv.split(' '); + } + + var eat = function (i, args) { + if (i <= args.length) { + return args.splice(i + 1, 1).pop(); + } + }; + + var args = argv.slice(2); + var script = null; + var nodemonOptions = { scriptPosition: null }; + + var nodemonOpt = nodemonOption.bind(null, nodemonOptions); + var lookForArgs = true; + + // move forward through the arguments + for (var i = 0; i < args.length; i++) { + // if the argument looks like a file, then stop eating + if (!script) { + if (args[i] === '.' || existsSync(args[i])) { + script = args.splice(i, 1).pop(); + + // we capture the position of the script because we'll reinsert it in + // the right place in run.js:command (though I'm not sure we should even + // take it out of the array in the first place, but this solves passing + // arguments to the exec process for now). + nodemonOptions.scriptPosition = i; + i--; + continue; + } + } + + if (lookForArgs) { + // respect the standard way of saying: hereafter belongs to my script + if (args[i] === '--') { + args.splice(i, 1); + nodemonOptions.scriptPosition = i; + // cycle back one argument, as we just ate this one up + i--; + + // ignore all further nodemon arguments + lookForArgs = false; + + // move to the next iteration + continue; + } + + if (nodemonOpt(args[i], eat.bind(null, i, args)) !== false) { + args.splice(i, 1); + // cycle back one argument, as we just ate this one up + i--; + } + } + } + + nodemonOptions.script = script; + nodemonOptions.args = args; + + return nodemonOptions; +} + + +/** + * Given an argument (ie. from process.argv), sets nodemon + * options and can eat up the argument value + * + * @param {import('../..').NodemonSettings} options object that will be updated + * @param {String} arg current argument from argv + * @param {Function} eatNext the callback to eat up the next argument in argv + * @return {Boolean} false if argument was not a nodemon arg + */ +function nodemonOption(options, arg, eatNext) { + // line separation on purpose to help legibility + if (arg === '--help' || arg === '-h' || arg === '-?') { + var help = eatNext(); + options.help = help ? help : true; + } else + + if (arg === '--version' || arg === '-v') { + options.version = true; + } else + + if (arg === '--no-update-notifier') { + options.noUpdateNotifier = true; + } else + + if (arg === '--spawn') { + options.spawn = true; + } else + + if (arg === '--dump') { + options.dump = true; + } else + + if (arg === '--verbose' || arg === '-V') { + options.verbose = true; + } else + + if (arg === '--legacy-watch' || arg === '-L') { + options.legacyWatch = true; + } else + + if (arg === '--polling-interval' || arg === '-P') { + options.pollingInterval = parseInt(eatNext(), 10); + } else + + // Depricated as this is "on" by default + if (arg === '--js') { + options.js = true; + } else + + if (arg === '--quiet' || arg === '-q') { + options.quiet = true; + } else + + if (arg === '--config') { + options.configFile = eatNext(); + } else + + if (arg === '--watch' || arg === '-w') { + if (!options.watch) { options.watch = []; } + options.watch.push(eatNext()); + } else + + if (arg === '--ignore' || arg === '-i') { + if (!options.ignore) { options.ignore = []; } + options.ignore.push(eatNext()); + } else + + if (arg === '--exitcrash') { + options.exitCrash = true; + } else + + if (arg === '--delay' || arg === '-d') { + options.delay = parseDelay(eatNext()); + } else + + if (arg === '--exec' || arg === '-x') { + options.exec = eatNext(); + } else + + if (arg === '--no-stdin' || arg === '-I') { + options.stdin = false; + } else + + if (arg === '--on-change-only' || arg === '-C') { + options.runOnChangeOnly = true; + } else + + if (arg === '--ext' || arg === '-e') { + options.ext = eatNext(); + } else + + if (arg === '--no-colours' || arg === '--no-colors') { + options.colours = false; + } else + + if (arg === '--signal' || arg === '-s') { + options.signal = eatNext(); + } else + + if (arg === '--cwd') { + options.cwd = eatNext(); + + // go ahead and change directory. This is primarily for nodemon tools like + // grunt-nodemon - we're doing this early because it will affect where the + // user script is searched for. + process.chdir(path.resolve(options.cwd)); + } else { + + // this means we didn't match + return false; + } +} + +/** + * Given an argument (ie. from nodemonOption()), will parse and return the + * equivalent millisecond value or 0 if the argument cannot be parsed + * + * @param {String} value argument value given to the --delay option + * @return {Number} millisecond equivalent of the argument + */ +function parseDelay(value) { + var millisPerSecond = 1000; + var millis = 0; + + if (value.match(/^\d*ms$/)) { + // Explicitly parse for milliseconds when using ms time specifier + millis = parseInt(value, 10); + } else { + // Otherwise, parse for seconds, with or without time specifier then convert + millis = parseFloat(value) * millisPerSecond; + } + + return isNaN(millis) ? 0 : millis; +} + diff --git a/node_modules/nodemon/lib/config/command.js b/node_modules/nodemon/lib/config/command.js new file mode 100644 index 0000000000000000000000000000000000000000..9839b5c7cba45e7df6217b23fe82bcb5cefc7dcd --- /dev/null +++ b/node_modules/nodemon/lib/config/command.js @@ -0,0 +1,43 @@ +module.exports = command; + +/** + * command constructs the executable command to run in a shell including the + * user script, the command arguments. + * + * @param {Object} settings Object as: + * { execOptions: { + * exec: String, + * [script: String], + * [scriptPosition: Number], + * [execArgs: Array] + * } + * } + * @return {Object} an object with the node executable and the + * arguments to the command + */ +function command(settings) { + var options = settings.execOptions; + var executable = options.exec; + var args = []; + + // after "executable" go the exec args (like --debug, etc) + if (options.execArgs) { + [].push.apply(args, options.execArgs); + } + + // then goes the user's script arguments + if (options.args) { + [].push.apply(args, options.args); + } + + // after the "executable" goes the user's script + if (options.script) { + args.splice((options.scriptPosition || 0) + + options.execArgs.length, 0, options.script); + } + + return { + executable: executable, + args: args, + }; +} diff --git a/node_modules/nodemon/lib/config/defaults.js b/node_modules/nodemon/lib/config/defaults.js new file mode 100644 index 0000000000000000000000000000000000000000..dc95d346bf505e6edbf54a839e45ef76ad934dd4 --- /dev/null +++ b/node_modules/nodemon/lib/config/defaults.js @@ -0,0 +1,34 @@ +var ignoreRoot = require('ignore-by-default').directories(); + +// default options for config.options +const defaults = { + restartable: 'rs', + colours: true, + execMap: { + py: 'python', + rb: 'ruby', + ts: 'ts-node', + // more can be added here such as ls: lsc - but please ensure it's cross + // compatible with linux, mac and windows, or make the default.js + // dynamically append the `.cmd` for node based utilities + }, + ignoreRoot: ignoreRoot.map((_) => `**/${_}/**`), + watch: ['*.*'], + stdin: true, + runOnChangeOnly: false, + verbose: false, + signal: 'SIGUSR2', + // 'stdout' refers to the default behaviour of a required nodemon's child, + // but also includes stderr. If this is false, data is still dispatched via + // nodemon.on('stdout/stderr') + stdout: true, + watchOptions: {}, +}; + +const nodeOptions = process.env.NODE_OPTIONS || ''; // ? + +if (/--(loader|import)\b/.test(nodeOptions)) { + delete defaults.execMap.ts; +} + +module.exports = defaults; diff --git a/node_modules/nodemon/lib/config/exec.js b/node_modules/nodemon/lib/config/exec.js new file mode 100644 index 0000000000000000000000000000000000000000..249742a210fd2dcf25a09c4902c6f40bf29c9a11 --- /dev/null +++ b/node_modules/nodemon/lib/config/exec.js @@ -0,0 +1,240 @@ +const path = require('path'); +const fs = require('fs'); +const existsSync = fs.existsSync; +const utils = require('../utils'); + +module.exports = exec; +module.exports.expandScript = expandScript; + +/** + * Reads the cwd/package.json file and looks to see if it can load a script + * and possibly an exec first from package.main, then package.start. + * + * @return {Object} exec & script if found + */ +function execFromPackage() { + // doing a try/catch because we can't use the path.exist callback pattern + // or we could, but the code would get messy, so this will do exactly + // what we're after - if the file doesn't exist, it'll throw. + try { + // note: this isn't nodemon's package, it's the user's cwd package + var pkg = require(path.join(process.cwd(), 'package.json')); + if (pkg.main !== undefined) { + // no app found to run - so give them a tip and get the feck out + return { exec: null, script: pkg.main }; + } + + if (pkg.scripts && pkg.scripts.start) { + const parts = pkg.scripts.start.split(' '); + + // fixes a loop issue where the script repeats over and over #2258 + if (parts.includes('nodemon')) { + return null; + } + return { exec: pkg.scripts.start }; + } + } catch (e) {} + + return null; +} + +function replace(map, str) { + var re = new RegExp('{{(' + Object.keys(map).join('|') + ')}}', 'g'); + return str.replace(re, function (all, m) { + return map[m] || all || ''; + }); +} + +function expandScript(script, ext) { + if (!ext) { + ext = '.js'; + } + if (script.indexOf(ext) !== -1) { + return script; + } + + if (existsSync(path.resolve(script))) { + return script; + } + + if (existsSync(path.resolve(script + ext))) { + return script + ext; + } + + return script; +} + +/** + * Discovers all the options required to run the script + * and if a custom exec has been passed in, then it will + * also try to work out what extensions to monitor and + * whether there's a special way of running that script. + * + * @param {Object} nodemonOptions + * @param {Object} execMap + * @return {Object} new and updated version of nodemonOptions + */ +function exec(nodemonOptions, execMap) { + if (!execMap) { + execMap = {}; + } + + var options = utils.clone(nodemonOptions || {}); + var script; + + // if there's no script passed, try to get it from the first argument + if (!options.script && (options.args || []).length) { + script = expandScript( + options.args[0], + options.ext && '.' + (options.ext || 'js').split(',')[0] + ); + + // if the script was found, shift it off our args + if (script !== options.args[0]) { + options.script = script; + options.args.shift(); + } + } + + // if there's no exec found yet, then try to read it from the local + // package.json this logic used to sit in the cli/parse, but actually the cli + // should be parsed first, then the user options (via nodemon.json) then + // finally default down to pot shots at the directory via package.json + if (!options.exec && !options.script) { + var found = execFromPackage(); + if (found !== null) { + if (found.exec) { + options.exec = found.exec; + } + if (!options.script) { + options.script = found.script; + } + if (Array.isArray(options.args) && options.scriptPosition === null) { + options.scriptPosition = options.args.length; + } + } + } + + // var options = utils.clone(nodemonOptions || {}); + script = path.basename(options.script || ''); + + var scriptExt = path.extname(script).slice(1); + + var extension = options.ext; + if (extension === undefined) { + var isJS = scriptExt === 'js' || scriptExt === 'mjs' || scriptExt === 'cjs'; + extension = isJS || !scriptExt ? 'js,mjs,cjs' : scriptExt; + extension += ',json'; // Always watch JSON files + } + + var execDefined = !!options.exec; + + // allows the user to simplify cli usage: + // https://github.com/remy/nodemon/issues/195 + // but always give preference to the user defined argument + if (!options.exec && execMap[scriptExt] !== undefined) { + options.exec = execMap[scriptExt]; + execDefined = true; + } + + options.execArgs = nodemonOptions.execArgs || []; + + if (Array.isArray(options.exec)) { + options.execArgs = options.exec; + options.exec = options.execArgs.shift(); + } + + if (options.exec === undefined) { + options.exec = 'node'; + } else { + // allow variable substitution for {{filename}} and {{pwd}} + var substitution = replace.bind(null, { + filename: options.script, + pwd: process.cwd(), + }); + + var newExec = substitution(options.exec); + if ( + newExec !== options.exec && + options.exec.indexOf('{{filename}}') !== -1 + ) { + options.script = null; + } + options.exec = newExec; + + var newExecArgs = options.execArgs.map(substitution); + if (newExecArgs.join('') !== options.execArgs.join('')) { + options.execArgs = newExecArgs; + delete options.script; + } + } + + if (options.exec === 'node' && options.nodeArgs && options.nodeArgs.length) { + options.execArgs = options.execArgs.concat(options.nodeArgs); + } + + // note: indexOf('coffee') handles both .coffee and .litcoffee + if ( + !execDefined && + options.exec === 'node' && + scriptExt.indexOf('coffee') !== -1 + ) { + options.exec = 'coffee'; + + // we need to get execArgs set before the script + // for example, in `nodemon --debug my-script.coffee --my-flag`, debug is an + // execArg, while my-flag is a script arg + var leadingArgs = (options.args || []).splice(0, options.scriptPosition); + options.execArgs = options.execArgs.concat(leadingArgs); + options.scriptPosition = 0; + + if (options.execArgs.length > 0) { + // because this is the coffee executable, we need to combine the exec args + // into a single argument after the nodejs flag + options.execArgs = ['--nodejs', options.execArgs.join(' ')]; + } + } + + if (options.exec === 'coffee') { + // don't override user specified extension tracking + if (options.ext === undefined) { + if (extension) { + extension += ','; + } + extension += 'coffee,litcoffee'; + } + + // because windows can't find 'coffee', it needs the real file 'coffee.cmd' + if (utils.isWindows) { + options.exec += '.cmd'; + } + } + + // allow users to make a mistake on the extension to monitor + // converts .js, pug => js,pug + // BIG NOTE: user can't do this: nodemon -e *.js + // because the terminal will automatically expand the glob against + // the file system :( + extension = (extension.match(/[^,*\s]+/g) || []) + .map((ext) => ext.replace(/^\./, '')) + .join(','); + + options.ext = extension; + + if (options.script) { + options.script = expandScript( + options.script, + extension && '.' + extension.split(',')[0] + ); + } + + options.env = {}; + // make sure it's an object (and since we don't have ) + if ({}.toString.apply(nodemonOptions.env) === '[object Object]') { + options.env = utils.clone(nodemonOptions.env); + } else if (nodemonOptions.env !== undefined) { + throw new Error('nodemon env values must be an object: { PORT: 8000 }'); + } + + return options; +} diff --git a/node_modules/nodemon/lib/config/index.js b/node_modules/nodemon/lib/config/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c78c435cdda56d7f231dbaea7ca13b32459f58d0 --- /dev/null +++ b/node_modules/nodemon/lib/config/index.js @@ -0,0 +1,93 @@ +/** + * Manages the internal config of nodemon, checking for the state of support + * with fs.watch, how nodemon can watch files (using find or fs methods). + * + * This is *not* the user's config. + */ +var debug = require('debug')('nodemon'); +var load = require('./load'); +var rules = require('../rules'); +var utils = require('../utils'); +var pinVersion = require('../version').pin; +var command = require('./command'); +var rulesToMonitor = require('../monitor/match').rulesToMonitor; +var bus = utils.bus; + +function reset() { + rules.reset(); + + config.dirs = []; + config.options = { ignore: [], watch: [], monitor: [] }; + config.lastStarted = 0; + config.loaded = []; +} + +var config = { + run: false, + system: { + cwd: process.cwd(), + }, + required: false, + dirs: [], + timeout: 1000, + options: {}, +}; + +/** + * Take user defined settings, then detect the local machine capability, then + * look for local and global nodemon.json files and merge together the final + * settings with the config for nodemon. + * + * @param {Object} settings user defined settings for nodemon (typically on + * the cli) + * @param {Function} ready callback fired once the config is loaded + */ +config.load = function (settings, ready) { + reset(); + var config = this; + load(settings, config.options, config, function (options) { + config.options = options; + + if (options.watch.length === 0) { + // this is to catch when the watch is left blank + options.watch.push('*.*'); + } + + if (options['watch_interval']) { // jshint ignore:line + options.watchInterval = options['watch_interval']; // jshint ignore:line + } + + config.watchInterval = options.watchInterval || null; + if (options.signal) { + config.signal = options.signal; + } + + var cmd = command(config.options); + config.command = { + raw: cmd, + string: utils.stringify(cmd.executable, cmd.args), + }; + + // now run automatic checks on system adding to the config object + options.monitor = rulesToMonitor(options.watch, options.ignore, config); + + var cwd = process.cwd(); + debug('config: dirs', config.dirs); + if (config.dirs.length === 0) { + config.dirs.unshift(cwd); + } + + bus.emit('config:update', config); + pinVersion().then(function () { + ready(config); + }).catch(e => { + // this doesn't help testing, but does give exposure on syntax errors + console.error(e.stack); + setTimeout(() => { throw e; }, 0); + }); + }); +}; + +config.reset = reset; + +module.exports = config; diff --git a/node_modules/nodemon/lib/config/load.js b/node_modules/nodemon/lib/config/load.js new file mode 100644 index 0000000000000000000000000000000000000000..7c57d32306f04986477f4777431b7200d938c81b --- /dev/null +++ b/node_modules/nodemon/lib/config/load.js @@ -0,0 +1,225 @@ +var debug = require('debug')('nodemon'); +var fs = require('fs'); +var path = require('path'); +var exists = fs.exists || path.exists; +var utils = require('../utils'); +var rules = require('../rules'); +var parse = require('../rules/parse'); +var exec = require('./exec'); +var defaults = require('./defaults'); + +module.exports = load; +module.exports.mutateExecOptions = mutateExecOptions; + +var existsSync = fs.existsSync || path.existsSync; + +function findAppScript() { + // nodemon has been run alone, so try to read the package file + // or try to read the index.js file + + var pkg = + existsSync(path.join(process.cwd(), 'package.json')) && + require(path.join(process.cwd(), 'package.json')); + if ((!pkg || pkg.main == undefined) && existsSync('./index.js')) { + return 'index.js'; + } +} + +/** + * Load the nodemon config, first reading the global root/nodemon.json, then + * the local nodemon.json to the exec and then overwriting using any user + * specified settings (i.e. from the cli) + * + * @param {Object} settings user defined settings + * @param {Object} options global options + * @param {Object} config the config object to be updated + * @param {Function} callback that receives complete config + */ +function load(settings, options, config, callback) { + config.loaded = []; + // first load the root nodemon.json + loadFile(options, config, utils.home, function (options) { + // then load the user's local configuration file + if (settings.configFile) { + options.configFile = path.resolve(settings.configFile); + } + loadFile(options, config, process.cwd(), function (options) { + // Then merge over with the user settings (parsed from the cli). + // Note that merge protects and favours existing values over new values, + // and thus command line arguments get priority + options = utils.merge(settings, options); + + // legacy support + if (!Array.isArray(options.ignore)) { + options.ignore = [options.ignore]; + } + + if (!options.ignoreRoot) { + options.ignoreRoot = defaults.ignoreRoot; + } + + // blend the user ignore and the default ignore together + if (options.ignoreRoot && options.ignore) { + if (!Array.isArray(options.ignoreRoot)) { + options.ignoreRoot = [options.ignoreRoot]; + } + options.ignore = options.ignoreRoot.concat(options.ignore); + } else { + options.ignore = defaults.ignore.concat(options.ignore); + } + + // add in any missing defaults + options = utils.merge(options, defaults); + + if (!options.script && !options.exec) { + var found = findAppScript(); + if (found) { + if (!options.args) { + options.args = []; + } + // if the script is found as a result of not being on the command + // line, then we move any of the pre double-dash args in execArgs + const n = + options.scriptPosition === null + ? options.args.length + : options.scriptPosition; + + options.execArgs = (options.execArgs || []).concat( + options.args.splice(0, n) + ); + options.scriptPosition = null; + + options.script = found; + } + } + + mutateExecOptions(options); + + if (options.quiet) { + utils.quiet(); + } + + if (options.verbose) { + utils.debug = true; + } + + // simplify the ready callback to be called after the rules are normalised + // from strings to regexp through the rules lib. Note that this gets + // created *after* options is overwritten twice in the lines above. + var ready = function (options) { + normaliseRules(options, callback); + }; + + ready(options); + }); + }); +} + +function normaliseRules(options, ready) { + // convert ignore and watch options to rules/regexp + rules.watch.add(options.watch); + rules.ignore.add(options.ignore); + + // normalise the watch and ignore arrays + options.watch = options.watch === false ? false : rules.rules.watch; + options.ignore = rules.rules.ignore; + + ready(options); +} + +/** + * Looks for a config in the current working directory, and a config in the + * user's home directory, merging the two together, giving priority to local + * config. This can then be overwritten later by command line arguments + * + * @param {Function} ready callback to pass loaded settings to + */ +function loadFile(options, config, dir, ready) { + if (!ready) { + ready = function () {}; + } + + var callback = function (settings) { + // prefer the local nodemon.json and fill in missing items using + // the global options + ready(utils.merge(settings, options)); + }; + + if (!dir) { + return callback({}); + } + + var filename = options.configFile || path.join(dir, 'nodemon.json'); + + if (config.loaded.indexOf(filename) !== -1) { + // don't bother re-parsing the same config file + return callback({}); + } + + fs.readFile(filename, 'utf8', function (err, data) { + if (err) { + if (err.code === 'ENOENT') { + if (!options.configFile && dir !== utils.home) { + // if no specified local config file and local nodemon.json + // doesn't exist, try the package.json + return loadPackageJSON(config, callback); + } + } + return callback({}); + } + + var settings = {}; + + try { + settings = JSON.parse(data.toString('utf8').replace(/^\uFEFF/, '')); + if (!filename.endsWith('package.json') || settings.nodemonConfig) { + config.loaded.push(filename); + } + } catch (e) { + utils.log.fail('Failed to parse config ' + filename); + console.error(e); + process.exit(1); + } + + // options values will overwrite settings + callback(settings); + }); +} + +function loadPackageJSON(config, ready) { + if (!ready) { + ready = () => {}; + } + + const dir = process.cwd(); + const filename = path.join(dir, 'package.json'); + const packageLoadOptions = { configFile: filename }; + return loadFile(packageLoadOptions, config, dir, (settings) => { + ready(settings.nodemonConfig || {}); + }); +} + +function mutateExecOptions(options) { + // work out the execOptions based on the final config we have + options.execOptions = exec( + { + script: options.script, + exec: options.exec, + args: options.args, + scriptPosition: options.scriptPosition, + nodeArgs: options.nodeArgs, + execArgs: options.execArgs, + ext: options.ext, + env: options.env, + }, + options.execMap + ); + + // clean up values that we don't need at the top level + delete options.scriptPosition; + delete options.script; + delete options.args; + delete options.ext; + + return options; +} diff --git a/node_modules/nodemon/lib/help/index.js b/node_modules/nodemon/lib/help/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1054b60253704f876ad69c746fae40e81e2bcff9 --- /dev/null +++ b/node_modules/nodemon/lib/help/index.js @@ -0,0 +1,27 @@ +var fs = require('fs'); +var path = require('path'); +const supportsColor = require('supports-color'); + +module.exports = help; + +const highlight = supportsColor.stdout ? '\x1B\[$1m' : ''; + +function help(item) { + if (!item) { + item = 'help'; + } else if (item === true) { // if used with -h or --help and no args + item = 'help'; + } + + // cleanse the filename to only contain letters + // aka: /\W/g but figured this was eaiser to read + item = item.replace(/[^a-z]/gi, ''); + + try { + var dir = path.join(__dirname, '..', '..', 'doc', 'cli', item + '.txt'); + var body = fs.readFileSync(dir, 'utf8'); + return body.replace(/\\x1B\[(.)m/g, highlight); + } catch (e) { + return '"' + item + '" help can\'t be found'; + } +} diff --git a/node_modules/nodemon/lib/index.js b/node_modules/nodemon/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0eca5c457d357f6528e263deba131848e4380154 --- /dev/null +++ b/node_modules/nodemon/lib/index.js @@ -0,0 +1 @@ +module.exports = require('./nodemon'); \ No newline at end of file diff --git a/node_modules/nodemon/lib/monitor/index.js b/node_modules/nodemon/lib/monitor/index.js new file mode 100644 index 0000000000000000000000000000000000000000..89db029b09e005e9e102a085c93f2b261eeb88b7 --- /dev/null +++ b/node_modules/nodemon/lib/monitor/index.js @@ -0,0 +1,4 @@ +module.exports = { + run: require('./run'), + watch: require('./watch').watch, +}; diff --git a/node_modules/nodemon/lib/monitor/match.js b/node_modules/nodemon/lib/monitor/match.js new file mode 100644 index 0000000000000000000000000000000000000000..bfa4f0b425db55f53c2e0557c144932968a11c8d --- /dev/null +++ b/node_modules/nodemon/lib/monitor/match.js @@ -0,0 +1,288 @@ +const { minimatch } = require('minimatch'); +const path = require('path'); +const fs = require('fs'); +const debug = require('debug')('nodemon:match'); +const utils = require('../utils'); + +module.exports = match; +module.exports.rulesToMonitor = rulesToMonitor; + +function rulesToMonitor(watch, ignore, config) { + var monitor = []; + + if (!Array.isArray(ignore)) { + if (ignore) { + ignore = [ignore]; + } else { + ignore = []; + } + } + + if (!Array.isArray(watch)) { + if (watch) { + watch = [watch]; + } else { + watch = []; + } + } + + if (watch && watch.length) { + monitor = utils.clone(watch); + } + + if (ignore) { + [].push.apply( + monitor, + (ignore || []).map(function (rule) { + return '!' + rule; + }) + ); + } + + var cwd = process.cwd(); + + // next check if the monitored paths are actual directories + // or just patterns - and expand the rule to include *.* + monitor = monitor.map(function (rule) { + var not = rule.slice(0, 1) === '!'; + + if (not) { + rule = rule.slice(1); + } + + if (rule === '.' || rule === '.*') { + rule = '*.*'; + } + + var dir = path.resolve(cwd, rule); + + try { + var stat = fs.statSync(dir); + if (stat.isDirectory()) { + rule = dir; + if (rule.slice(-1) !== '/') { + rule += '/'; + } + rule += '**/*'; + + // `!not` ... sorry. + if (!not) { + config.dirs.push(dir); + } + } else { + // ensures we end up in the check that tries to get a base directory + // and then adds it to the watch list + throw new Error(); + } + } catch (e) { + var base = tryBaseDir(dir); + if (!not && base) { + if (config.dirs.indexOf(base) === -1) { + config.dirs.push(base); + } + } + } + + if (rule.slice(-1) === '/') { + // just slap on a * anyway + rule += '*'; + } + + // if the url ends with * but not **/* and not *.* + // then convert to **/* - somehow it was missed :-\ + if ( + rule.slice(-4) !== '**/*' && + rule.slice(-1) === '*' && + rule.indexOf('*.') === -1 + ) { + if (rule.slice(-2) !== '**') { + rule += '*/*'; + } + } + + return (not ? '!' : '') + rule; + }); + + return monitor; +} + +function tryBaseDir(dir) { + var stat; + if (/[?*\{\[]+/.test(dir)) { + // if this is pattern, then try to find the base + try { + var base = path.dirname(dir.replace(/([?*\{\[]+.*$)/, 'foo')); + stat = fs.statSync(base); + if (stat.isDirectory()) { + return base; + } + } catch (error) { + // console.log(error); + } + } else { + try { + stat = fs.statSync(dir); + // if this path is actually a single file that exists, then just monitor + // that, *specifically*. + if (stat.isFile() || stat.isDirectory()) { + return dir; + } + } catch (e) { } + } + + return false; +} + +function match(files, monitor, ext) { + // sort the rules by highest specificity (based on number of slashes) + // ignore rules (!) get sorted highest as they take precedent + const cwd = process.cwd(); + var rules = monitor + .sort(function (a, b) { + var r = b.split(path.sep).length - a.split(path.sep).length; + var aIsIgnore = a.slice(0, 1) === '!'; + var bIsIgnore = b.slice(0, 1) === '!'; + + if (aIsIgnore || bIsIgnore) { + if (aIsIgnore) { + return -1; + } + + return 1; + } + + if (r === 0) { + return b.length - a.length; + } + return r; + }) + .map(function (s) { + var prefix = s.slice(0, 1); + + if (prefix === '!') { + if (s.indexOf('!' + cwd) === 0) { + return s; + } + + // if it starts with a period, then let's get the relative path + if (s.indexOf('!.') === 0) { + return '!' + path.resolve(cwd, s.substring(1)); + } + + return '!**' + (prefix !== path.sep ? path.sep : '') + s.slice(1); + } + + // if it starts with a period, then let's get the relative path + if (s.indexOf('.') === 0) { + return path.resolve(cwd, s); + } + + if (s.indexOf(cwd) === 0) { + return s; + } + + return '**' + (prefix !== path.sep ? path.sep : '') + s; + }); + + debug('rules', rules); + + var good = []; + var whitelist = []; // files that we won't check against the extension + var ignored = 0; + var watched = 0; + var usedRules = []; + var minimatchOpts = { + dot: true, + }; + + // enable case-insensitivity on Windows + if (utils.isWindows) { + minimatchOpts.nocase = true; + minimatchOpts.windowsPathsNoEscape = true; + } + + files.forEach(function (file) { + file = path.resolve(cwd, file); + + var matched = false; + for (var i = 0; i < rules.length; i++) { + if (rules[i].slice(0, 1) === '!') { + if (!minimatch(file, rules[i], minimatchOpts)) { + debug('ignored', file, 'rule:', rules[i]); + ignored++; + matched = true; + break; + } + } else { + debug('matched', file, 'rule:', rules[i]); + if (minimatch(file, rules[i], minimatchOpts)) { + watched++; + + // don't repeat the output if a rule is matched + if (usedRules.indexOf(rules[i]) === -1) { + usedRules.push(rules[i]); + utils.log.detail('matched rule: ' + rules[i]); + } + + // if the rule doesn't match the WATCH EVERYTHING + // but *does* match a rule that ends with *.*, then + // white list it - in that we don't run it through + // the extension check too. + if ( + rules[i] !== '**' + path.sep + '*.*' && + rules[i].slice(-3) === '*.*' + ) { + whitelist.push(file); + } else if (path.basename(file) === path.basename(rules[i])) { + // if the file matches the actual rule, then it's put on whitelist + whitelist.push(file); + } else { + good.push(file); + } + matched = true; + } else { + // utils.log.detail('no match: ' + rules[i], file); + } + } + } + if (!matched) { + ignored++; + } + }); + + // finally check the good files against the extensions that we're monitoring + if (ext) { + if (ext.indexOf(',') === -1) { + ext = '**/*.' + ext; + } else { + ext = '**/*.{' + ext + '}'; + } + + good = good.filter(function (file) { + // only compare the filename to the extension test + return minimatch(path.basename(file), ext, minimatchOpts); + }); + debug('good (filtered by ext)', good); + } else { + // else assume *.* + debug('good', good); + } + + if (whitelist.length) debug('whitelist', whitelist); + + var result = good.concat(whitelist); + + if (utils.isWindows) { + // fix for windows testing - I *think* this is okay to do + result = result.map(function (file) { + return file.slice(0, 1).toLowerCase() + file.slice(1); + }); + } + + return { + result: result, + ignored: ignored, + watched: watched, + total: files.length, + }; +} diff --git a/node_modules/nodemon/lib/monitor/run.js b/node_modules/nodemon/lib/monitor/run.js new file mode 100644 index 0000000000000000000000000000000000000000..5fa7f45ad215c29c9591ac5b0b7a7fc094f7dec9 --- /dev/null +++ b/node_modules/nodemon/lib/monitor/run.js @@ -0,0 +1,562 @@ +var debug = require('debug')('nodemon:run'); +const statSync = require('fs').statSync; +var utils = require('../utils'); +var bus = utils.bus; +var childProcess = require('child_process'); +var spawn = childProcess.spawn; +var exec = childProcess.exec; +var execSync = childProcess.execSync; +var fork = childProcess.fork; +var watch = require('./watch').watch; +var config = require('../config'); +var child = null; // the actual child process we spawn +var killedAfterChange = false; +var noop = () => {}; +var restart = null; +var psTree = require('pstree.remy'); +var path = require('path'); +var signals = require('./signals'); +const undefsafe = require('undefsafe'); +const osRelease = parseInt(require('os').release().split('.')[0], 10); + +function run(options) { + var cmd = config.command.raw; + // moved up + // we need restart function below in the global scope for run.kill + /*jshint validthis:true*/ + restart = run.bind(this, options); + run.restart = restart; + + // binding options with instance of run + // so that we can use it in run.kill + run.options = options; + + var runCmd = !options.runOnChangeOnly || config.lastStarted !== 0; + if (runCmd) { + utils.log.status('starting `' + config.command.string + '`'); + } else { + // should just watch file if command is not to be run + // had another alternate approach + // to stop process being forked/spawned in the below code + // but this approach does early exit and makes code cleaner + debug('start watch on: %s', config.options.watch); + if (config.options.watch !== false) { + watch(); + return; + } + } + + config.lastStarted = Date.now(); + + var stdio = ['pipe', 'pipe', 'pipe']; + + if (config.options.stdout) { + stdio = ['pipe', process.stdout, process.stderr]; + } + + if (config.options.stdin === false) { + stdio = [process.stdin, process.stdout, process.stderr]; + } + + var sh = 'sh'; + var shFlag = '-c'; + + const binPath = process.cwd() + '/node_modules/.bin'; + + const spawnOptions = { + env: Object.assign({}, options.execOptions.env, process.env, { + PATH: + binPath + + path.delimiter + + (undefsafe(options, '.execOptions.env.PATH') || process.env.PATH), + }), + stdio: stdio, + }; + + var executable = cmd.executable; + + if (utils.isWindows) { + // if the exec includes a forward slash, reverse it for windows compat + // but *only* apply to the first command, and none of the arguments. + // ref #1251 and #1236 + if (executable.indexOf('/') !== -1) { + executable = executable + .split(' ') + .map((e, i) => { + if (i === 0) { + return path.normalize(e); + } + return e; + }) + .join(' '); + } + // taken from npm's cli: https://git.io/vNFD4 + sh = process.env.comspec || 'cmd'; + shFlag = '/d /s /c'; + spawnOptions.windowsVerbatimArguments = true; + spawnOptions.windowsHide = true; + } + + var args = runCmd ? utils.stringify(executable, cmd.args) : ':'; + var spawnArgs = [sh, [shFlag, args], spawnOptions]; + + const firstArg = cmd.args[0] || ''; + + var inBinPath = false; + try { + inBinPath = statSync(`${binPath}/${executable}`).isFile(); + } catch (e) {} + + // hasStdio allows us to correctly handle stdin piping + // see: https://git.io/vNtX3 + const hasStdio = utils.satisfies('>= 6.4.0 || < 5'); + + // forking helps with sub-process handling and tends to clean up better + // than spawning, but it should only be used under specific conditions + const shouldFork = + !config.options.spawn && + !inBinPath && + !(firstArg.indexOf('-') === 0) && // don't fork if there's a node exec arg + firstArg !== 'inspect' && // don't fork it's `inspect` debugger + executable === 'node' && // only fork if node + utils.version.major > 4; // only fork if node version > 4 + + if (shouldFork) { + // this assumes the first argument is the script and slices it out, since + // we're forking + var forkArgs = cmd.args.slice(1); + var env = utils.merge(options.execOptions.env, process.env); + stdio.push('ipc'); + const forkOptions = { + env: env, + stdio: stdio, + silent: !hasStdio, + }; + if (utils.isWindows) { + forkOptions.windowsHide = true; + } + child = fork(options.execOptions.script, forkArgs, forkOptions); + utils.log.detail('forking'); + debug('fork', sh, shFlag, args); + } else { + utils.log.detail('spawning'); + child = spawn.apply(null, spawnArgs); + debug('spawn', sh, shFlag, args); + } + + if (config.required) { + var emit = { + stdout: function (data) { + bus.emit('stdout', data); + }, + stderr: function (data) { + bus.emit('stderr', data); + }, + }; + + // now work out what to bind to... + if (config.options.stdout) { + child.on('stdout', emit.stdout).on('stderr', emit.stderr); + } else { + child.stdout.on('data', emit.stdout); + child.stderr.on('data', emit.stderr); + + bus.stdout = child.stdout; + bus.stderr = child.stderr; + } + + if (shouldFork) { + child.on('message', function (message, sendHandle) { + bus.emit('message', message, sendHandle); + }); + } + } + + bus.emit('start'); + + utils.log.detail('child pid: ' + child.pid); + + child.on('error', function (error) { + bus.emit('error', error); + if (error.code === 'ENOENT') { + utils.log.error('unable to run executable: "' + cmd.executable + '"'); + process.exit(1); + } else { + utils.log.error('failed to start child process: ' + error.code); + throw error; + } + }); + + child.on('exit', function (code, signal) { + if (child && child.stdin) { + process.stdin.unpipe(child.stdin); + } + + if (code === 127) { + utils.log.error( + 'failed to start process, "' + cmd.executable + '" exec not found' + ); + bus.emit('error', code); + process.exit(); + } + + // If the command failed with code 2, it may or may not be a syntax error + // See: http://git.io/fNOAR + // We will only assume a parse error, if the child failed quickly + if (code === 2 && Date.now() < config.lastStarted + 500) { + utils.log.error('process failed, unhandled exit code (2)'); + utils.log.error(''); + utils.log.error('Either the command has a syntax error,'); + utils.log.error('or it is exiting with reserved code 2.'); + utils.log.error(''); + utils.log.error('To keep nodemon running even after a code 2,'); + utils.log.error('add this to the end of your command: || exit 1'); + utils.log.error(''); + utils.log.error('Read more here: https://git.io/fNOAG'); + utils.log.error(''); + utils.log.error('nodemon will stop now so that you can fix the command.'); + utils.log.error(''); + bus.emit('error', code); + process.exit(); + } + + // In case we killed the app ourselves, set the signal thusly + if (killedAfterChange) { + killedAfterChange = false; + signal = config.signal; + } + // this is nasty, but it gives it windows support + if (utils.isWindows && signal === 'SIGTERM') { + signal = config.signal; + } + + if (signal === config.signal || code === 0) { + // this was a clean exit, so emit exit, rather than crash + debug('bus.emit(exit) via ' + config.signal); + bus.emit('exit', signal); + + // exit the monitor, but do it gracefully + if (signal === config.signal) { + return restart(); + } + + if (code === 0) { + // clean exit - wait until file change to restart + if (runCmd) { + utils.log.status('clean exit - waiting for changes before restart'); + } + child = null; + } + } else { + bus.emit('crash'); + + // support the old syntax of `exitcrash` - 2024-12-13 + if (options.exitcrash) { + options.exitCrash = true; + delete options.exitcrash; + } + + if (options.exitCrash) { + utils.log.fail('app crashed'); + if (!config.required) { + process.exit(1); + } + } else { + utils.log.fail( + 'app crashed - waiting for file changes before' + ' starting...' + ); + child = null; + } + } + + if (config.options.restartable) { + // stdin needs to kick in again to be able to listen to the + // restart command + process.stdin.resume(); + } + }); + + // moved the run.kill outside to handle both the cases + // intial start + // no start + + // connect stdin to the child process (options.stdin is on by default) + if (options.stdin) { + process.stdin.resume(); + // FIXME decide whether or not we need to decide the encoding + // process.stdin.setEncoding('utf8'); + + // swallow the stdin error if it happens + // ref: https://github.com/remy/nodemon/issues/1195 + if (hasStdio) { + child.stdin.on('error', () => {}); + process.stdin.pipe(child.stdin); + } else { + if (child.stdout) { + child.stdout.pipe(process.stdout); + } else { + utils.log.error( + 'running an unsupported version of node ' + process.version + ); + utils.log.error( + 'nodemon may not work as expected - ' + + 'please consider upgrading to LTS' + ); + } + } + + bus.once('exit', function () { + if (child && process.stdin.unpipe) { + // node > 0.8 + process.stdin.unpipe(child.stdin); + } + }); + } + + debug('start watch on: %s', config.options.watch); + if (config.options.watch !== false) { + watch(); + } +} + +function waitForSubProcesses(pid, callback) { + debug('checking ps tree for pids of ' + pid); + psTree(pid, (err, pids) => { + if (!pids.length) { + return callback(); + } + + utils.log.status( + `still waiting for ${pids.length} sub-process${ + pids.length > 2 ? 'es' : '' + } to finish...` + ); + setTimeout(() => waitForSubProcesses(pid, callback), 1000); + }); +} + +function kill(child, signal, callback) { + if (!callback) { + callback = noop; + } + + if (utils.isWindows) { + const taskKill = () => { + try { + exec('taskkill /pid ' + child.pid + ' /T /F'); + } catch (e) { + utils.log.error('Could not shutdown sub process cleanly'); + } + }; + + // We are handling a 'SIGKILL' , 'SIGUSR2' and 'SIGUSR1' POSIX signal under Windows the + // same way it is handled on a UNIX system: We are performing + // a hard shutdown without waiting for the process to clean-up. + if ( + signal === 'SIGKILL' || + osRelease < 10 || + signal === 'SIGUSR2' || + signal === 'SIGUSR1' + ) { + debug('terminating process group by force: %s', child.pid); + + // We are using the taskkill utility to terminate the whole + // process group ('/t') of the child ('/pid') by force ('/f'). + // We need to end all sub processes, because the 'child' + // process in this context is actually a cmd.exe wrapper. + taskKill(); + callback(); + return; + } + + try { + // We are using the Windows Management Instrumentation Command-line + // (wmic.exe) to resolve the sub-child process identifier, because the + // 'child' process in this context is actually a cmd.exe wrapper. + // We want to send the termination signal directly to the node process. + // The '2> nul' silences the no process found error message. + const resultBuffer = execSync( + `wmic process where (ParentProcessId=${child.pid}) get ProcessId 2> nul` + ); + const result = resultBuffer.toString().match(/^[0-9]+/m); + + // If there is no sub-child process we fall back to the child process. + const processId = Array.isArray(result) ? result[0] : child.pid; + + debug('sending kill signal SIGINT to process: %s', processId); + + // We are using the standalone 'windows-kill' executable to send the + // standard POSIX signal 'SIGINT' to the node process. This fixes #1720. + const windowsKill = path.normalize( + `${__dirname}/../../bin/windows-kill.exe` + ); + + // We have to detach the 'windows-kill' execution completely from this + // process group to avoid terminating the nodemon process itself. + // See: https://github.com/alirdn/windows-kill#how-it-works--limitations + // + // Therefore we are using 'start' to create a new cmd.exe context. + // The '/min' option hides the new terminal window and the '/wait' + // option lets the process wait for the command to finish. + + execSync( + `start "windows-kill" /min /wait "${windowsKill}" -SIGINT ${processId}` + ); + } catch (e) { + taskKill(); + } + callback(); + } else { + // we use psTree to kill the full subtree of nodemon, because when + // spawning processes like `coffee` under the `--debug` flag, it'll spawn + // it's own child, and that can't be killed by nodemon, so psTree gives us + // an array of PIDs that have spawned under nodemon, and we send each the + // configured signal (default: SIGUSR2) signal, which fixes #335 + // note that psTree also works if `ps` is missing by looking in /proc + let sig = signal.replace('SIG', ''); + + psTree(child.pid, function (err, pids) { + // if ps isn't native to the OS, then we need to send the numeric value + // for the signal during the kill, `signals` is a lookup table for that. + if (!psTree.hasPS) { + sig = signals[signal]; + } + + // the sub processes need to be killed from smallest to largest + debug('sending kill signal to ' + pids.join(', ')); + + child.kill(signal); + + pids.sort().forEach((pid) => exec(`kill -${sig} ${pid}`, noop)); + + waitForSubProcesses(child.pid, () => { + // finally kill the main user process + exec(`kill -${sig} ${child.pid}`, callback); + }); + }); + } +} + +run.kill = function (noRestart, callback) { + // I hate code like this :( - Remy (author of said code) + if (typeof noRestart === 'function') { + callback = noRestart; + noRestart = false; + } + + if (!callback) { + callback = noop; + } + + if (child !== null) { + // if the stdin piping is on, we need to unpipe, but also close stdin on + // the child, otherwise linux can throw EPIPE or ECONNRESET errors. + if (run.options.stdin) { + process.stdin.unpipe(child.stdin); + } + + // For the on('exit', ...) handler above the following looks like a + // crash, so we set the killedAfterChange flag if a restart is planned + if (!noRestart) { + killedAfterChange = true; + } + + /* Now kill the entire subtree of processes belonging to nodemon */ + var oldPid = child.pid; + if (child) { + kill(child, config.signal, function () { + // this seems to fix the 0.11.x issue with the "rs" restart command, + // though I'm unsure why. it seems like more data is streamed in to + // stdin after we close. + if (child && run.options.stdin && child.stdin && oldPid === child.pid) { + child.stdin.end(); + } + callback(); + }); + } + } else if (!noRestart) { + // if there's no child, then we need to manually start the process + // this is because as there was no child, the child.on('exit') event + // handler doesn't exist which would normally trigger the restart. + bus.once('start', callback); + run.restart(); + } else { + callback(); + } +}; + +run.restart = noop; + +bus.on('quit', function onQuit(code) { + if (code === undefined) { + code = 0; + } + + // remove event listener + var exitTimer = null; + var exit = function () { + clearTimeout(exitTimer); + exit = noop; // null out in case of race condition + child = null; + if (!config.required) { + // Execute all other quit listeners. + bus.listeners('quit').forEach(function (listener) { + if (listener !== onQuit) { + listener(); + } + }); + process.exit(code); + } else { + bus.emit('exit'); + } + }; + + // if we're not running already, don't bother with trying to kill + if (config.run === false) { + return exit(); + } + + // immediately try to stop any polling + config.run = false; + + if (child) { + // give up waiting for the kids after 10 seconds + exitTimer = setTimeout(exit, 10 * 1000); + child.removeAllListeners('exit'); + child.once('exit', exit); + + kill(child, 'SIGINT'); + } else { + exit(); + } +}); + +bus.on('restart', function () { + // run.kill will send a SIGINT to the child process, which will cause it + // to terminate, which in turn uses the 'exit' event handler to restart + run.kill(); +}); + +// remove the child file on exit +process.on('exit', function () { + utils.log.detail('exiting'); + if (child) { + child.kill(); + } +}); + +// because windows borks when listening for the SIG* events +if (!utils.isWindows) { + bus.once('boot', () => { + // usual suspect: ctrl+c exit + process.once('SIGINT', () => bus.emit('quit', 130)); + process.once('SIGTERM', () => { + bus.emit('quit', 143); + if (child) { + child.kill('SIGTERM'); + } + }); + }); +} + +module.exports = run; diff --git a/node_modules/nodemon/lib/monitor/signals.js b/node_modules/nodemon/lib/monitor/signals.js new file mode 100644 index 0000000000000000000000000000000000000000..daff6e05389aedf0b669bbcb32554599692cb121 --- /dev/null +++ b/node_modules/nodemon/lib/monitor/signals.js @@ -0,0 +1,34 @@ +module.exports = { + SIGHUP: 1, + SIGINT: 2, + SIGQUIT: 3, + SIGILL: 4, + SIGTRAP: 5, + SIGABRT: 6, + SIGBUS: 7, + SIGFPE: 8, + SIGKILL: 9, + SIGUSR1: 10, + SIGSEGV: 11, + SIGUSR2: 12, + SIGPIPE: 13, + SIGALRM: 14, + SIGTERM: 15, + SIGSTKFLT: 16, + SIGCHLD: 17, + SIGCONT: 18, + SIGSTOP: 19, + SIGTSTP: 20, + SIGTTIN: 21, + SIGTTOU: 22, + SIGURG: 23, + SIGXCPU: 24, + SIGXFSZ: 25, + SIGVTALRM: 26, + SIGPROF: 27, + SIGWINCH: 28, + SIGIO: 29, + SIGPWR: 30, + SIGSYS: 31, + SIGRTMIN: 35, +} diff --git a/node_modules/nodemon/lib/monitor/watch.js b/node_modules/nodemon/lib/monitor/watch.js new file mode 100644 index 0000000000000000000000000000000000000000..d0ac7fe14f65bcafebe0ae971834fa4d6beb28e4 --- /dev/null +++ b/node_modules/nodemon/lib/monitor/watch.js @@ -0,0 +1,244 @@ +module.exports.watch = watch; +module.exports.resetWatchers = resetWatchers; + +var debug = require('debug')('nodemon:watch'); +var debugRoot = require('debug')('nodemon'); +var chokidar = require('chokidar'); +var undefsafe = require('undefsafe'); +var config = require('../config'); +var path = require('path'); +var utils = require('../utils'); +var bus = utils.bus; +var match = require('./match'); +var watchers = []; +var debouncedBus; + +bus.on('reset', resetWatchers); + +function resetWatchers() { + debugRoot('resetting watchers'); + watchers.forEach(function (watcher) { + watcher.close(); + }); + watchers = []; +} + +function watch() { + if (watchers.length) { + debug('early exit on watch, still watching (%s)', watchers.length); + return; + } + + var dirs = [].slice.call(config.dirs); + + debugRoot('start watch on: %s', dirs.join(', ')); + const rootIgnored = config.options.ignore; + debugRoot('ignored', rootIgnored); + + var watchedFiles = []; + + const promise = new Promise(function (resolve) { + const dotFilePattern = /[/\\]\./; + var ignored = match.rulesToMonitor( + [], // not needed + Array.from(rootIgnored), + config + ).map(pattern => pattern.slice(1)); + + const addDotFile = dirs.filter(dir => dir.match(dotFilePattern)); + + // don't ignore dotfiles if explicitly watched. + if (addDotFile.length === 0) { + ignored.push(dotFilePattern); + } + + var watchOptions = { + ignorePermissionErrors: true, + ignored: ignored, + persistent: true, + usePolling: config.options.legacyWatch || false, + interval: config.options.pollingInterval, + // note to future developer: I've gone back and forth on adding `cwd` + // to the props and in some cases it fixes bugs but typically it causes + // bugs elsewhere (since nodemon is used is so many ways). the final + // decision is to *not* use it at all and work around it + // cwd: ... + }; + + if (utils.isWindows) { + watchOptions.disableGlobbing = true; + } + + if (utils.isIBMi) { + watchOptions.usePolling = true; + } + + if (process.env.TEST) { + watchOptions.useFsEvents = false; + } + + var watcher = chokidar.watch( + dirs, + Object.assign({}, watchOptions, config.options.watchOptions || {}) + ); + + watcher.ready = false; + + var total = 0; + + watcher.on('change', filterAndRestart); + watcher.on('unlink', filterAndRestart); + watcher.on('add', function (file) { + if (watcher.ready) { + return filterAndRestart(file); + } + + watchedFiles.push(file); + bus.emit('watching', file); + debug('chokidar watching: %s', file); + }); + watcher.on('ready', function () { + watchedFiles = Array.from(new Set(watchedFiles)); // ensure no dupes + total = watchedFiles.length; + watcher.ready = true; + resolve(total); + debugRoot('watch is complete'); + }); + + watcher.on('error', function (error) { + if (error.code === 'EINVAL') { + utils.log.error( + 'Internal watch failed. Likely cause: too many ' + + 'files being watched (perhaps from the root of a drive?\n' + + 'See https://github.com/paulmillr/chokidar/issues/229 for details' + ); + } else { + utils.log.error('Internal watch failed: ' + error.message); + process.exit(1); + } + }); + + watchers.push(watcher); + }); + + return promise.catch(e => { + // this is a core error and it should break nodemon - so I have to break + // out of a promise using the setTimeout + setTimeout(() => { + throw e; + }); + }).then(function () { + utils.log.detail(`watching ${watchedFiles.length} file${ + watchedFiles.length === 1 ? '' : 's'}`); + return watchedFiles; + }); +} + +function filterAndRestart(files) { + if (!Array.isArray(files)) { + files = [files]; + } + + if (files.length) { + var cwd = process.cwd(); + if (this.options && this.options.cwd) { + cwd = this.options.cwd; + } + + utils.log.detail( + 'files triggering change check: ' + + files + .map(file => { + const res = path.relative(cwd, file); + return res; + }) + .join(', ') + ); + + // make sure the path is right and drop an empty + // filenames (sometimes on windows) + files = files.filter(Boolean).map(file => { + return path.relative(process.cwd(), path.relative(cwd, file)); + }); + + if (utils.isWindows) { + // ensure the drive letter is in uppercase (c:\foo -> C:\foo) + files = files.map(f => { + if (f.indexOf(':') === -1) { return f; } + return f[0].toUpperCase() + f.slice(1); + }); + } + + + debug('filterAndRestart on', files); + + var matched = match( + files, + config.options.monitor, + undefsafe(config, 'options.execOptions.ext') + ); + + debug('matched?', JSON.stringify(matched)); + + // if there's no matches, then test to see if the changed file is the + // running script, if so, let's allow a restart + if (config.options.execOptions && config.options.execOptions.script) { + const script = path.resolve(config.options.execOptions.script); + if (matched.result.length === 0 && script) { + const length = script.length; + files.find(file => { + if (file.substr(-length, length) === script) { + matched = { + result: [file], + total: 1, + }; + return true; + } + }); + } + } + + utils.log.detail( + 'changes after filters (before/after): ' + + [files.length, matched.result.length].join('/') + ); + + // reset the last check so we're only looking at recently modified files + config.lastStarted = Date.now(); + + if (matched.result.length) { + if (config.options.delay > 0) { + utils.log.detail('delaying restart for ' + config.options.delay + 'ms'); + if (debouncedBus === undefined) { + debouncedBus = debounce(restartBus, config.options.delay); + } + debouncedBus(matched); + } else { + return restartBus(matched); + } + } + } +} + +function restartBus(matched) { + utils.log.status('restarting due to changes...'); + matched.result.map(file => { + utils.log.detail(path.relative(process.cwd(), file)); + }); + + if (config.options.verbose) { + utils.log._log(''); + } + + bus.emit('restart', matched.result); +} + +function debounce(fn, delay) { + var timer = null; + return function () { + const context = this; + const args = arguments; + clearTimeout(timer); + timer = setTimeout(() =>fn.apply(context, args), delay); + }; +} diff --git a/node_modules/nodemon/lib/nodemon.js b/node_modules/nodemon/lib/nodemon.js new file mode 100644 index 0000000000000000000000000000000000000000..75619ba40184df7761f8a2677633d9669d990a3c --- /dev/null +++ b/node_modules/nodemon/lib/nodemon.js @@ -0,0 +1,317 @@ +var debug = require('debug')('nodemon'); +var path = require('path'); +var monitor = require('./monitor'); +var cli = require('./cli'); +var version = require('./version'); +var util = require('util'); +var utils = require('./utils'); +var bus = utils.bus; +var help = require('./help'); +/** @type {import('..').NodemonEventConfig} */ +var config = require('./config'); +var spawn = require('./spawn'); +const defaults = require('./config/defaults') +var eventHandlers = {}; + +// this is fairly dirty, but theoretically sound since it's part of the +// stable module API +config.required = utils.isRequired; + +/** + * @param {import('..').NodemonSettings | string} settings + * @returns {import('..').Nodemon} + */ +function nodemon(settings) { + bus.emit('boot'); + nodemon.reset(); + + /** @type {import('..').NodemonSettings} */ + let options + + // allow the cli string as the argument to nodemon, and allow for + // `node nodemon -V app.js` or just `-V app.js` + if (typeof settings === 'string') { + settings = settings.trim(); + if (settings.indexOf('node') !== 0) { + if (settings.indexOf('nodemon') !== 0) { + settings = 'nodemon ' + settings; + } + settings = 'node ' + settings; + } + options = cli.parse(settings); + } else options = settings; + + // set the debug flag as early as possible to get all the detailed logging + if (options.verbose) { + utils.debug = true; + } + + if (options.help) { + if (process.stdout.isTTY) { + process.stdout._handle.setBlocking(true); // nodejs/node#6456 + } + console.log(help(options.help)); + if (!config.required) { + process.exit(0); + } + } + + if (options.version) { + version().then(function (v) { + console.log(v); + if (!config.required) { + process.exit(0); + } + }); + return; + } + + // nodemon tools like grunt-nodemon. This affects where + // the script is being run from, and will affect where + // nodemon looks for the nodemon.json files + if (options.cwd) { + // this is protection to make sure we haven't dont the chdir already... + // say like in cli/parse.js (which is where we do this once already!) + if (process.cwd() !== path.resolve(config.system.cwd, options.cwd)) { + process.chdir(options.cwd); + } + } + + config.load(options, function (config) { + if (!config.options.dump && !config.options.execOptions.script && + config.options.execOptions.exec === 'node') { + if (!config.required) { + console.log(help('usage')); + process.exit(); + } + return; + } + + // before we print anything, update the colour setting on logging + utils.colours = config.options.colours; + + // always echo out the current version + utils.log.info(version.pinned); + + const cwd = process.cwd(); + + if (config.options.cwd) { + utils.log.detail('process root: ' + cwd); + } + + config.loaded.map(file => file.replace(cwd, '.')).forEach(file => { + utils.log.detail('reading config ' + file); + }); + + if (config.options.stdin && config.options.restartable) { + // allow nodemon to restart when the use types 'rs\n' + process.stdin.resume(); + process.stdin.setEncoding('utf8'); + process.stdin.on('data', data => { + const str = data.toString().trim().toLowerCase(); + + // if the keys entered match the restartable value, then restart! + if (str === config.options.restartable) { + bus.emit('restart'); + } else if (data.charCodeAt(0) === 12) { // ctrl+l + console.clear(); + } + }); + } else if (config.options.stdin) { + // so let's make sure we don't eat the key presses + // but also, since we're wrapping, watch out for + // special keys, like ctrl+c x 2 or '.exit' or ctrl+d or ctrl+l + var ctrlC = false; + var buffer = ''; + + process.stdin.on('data', function (data) { + data = data.toString(); + buffer += data; + const chr = data.charCodeAt(0); + + // if restartable, echo back + if (chr === 3) { + if (ctrlC) { + process.exit(0); + } + + ctrlC = true; + return; + } else if (buffer === '.exit' || chr === 4) { // ctrl+d + process.exit(); + } else if (chr === 13 || chr === 10) { // enter / carriage return + buffer = ''; + } else if (chr === 12) { // ctrl+l + console.clear(); + buffer = ''; + } + ctrlC = false; + }); + if (process.stdin.setRawMode) { + process.stdin.setRawMode(true); + } + } + + if (config.options.restartable) { + utils.log.info('to restart at any time, enter `' + + config.options.restartable + '`'); + } + + if (!config.required) { + const restartSignal = config.options.signal === 'SIGUSR2' ? 'SIGHUP' : 'SIGUSR2'; + process.on(restartSignal, nodemon.restart); + utils.bus.on('error', () => { + utils.log.fail((new Error().stack)); + }); + utils.log.detail((config.options.restartable ? 'or ' : '') + 'send ' + + restartSignal + ' to ' + process.pid + ' to restart'); + } + + const ignoring = config.options.monitor.map(function (rule) { + if (rule.slice(0, 1) !== '!') { + return false; + } + + rule = rule.slice(1); + + // don't notify of default ignores + if (defaults.ignoreRoot.indexOf(rule) !== -1) { + return false; + // return rule.slice(3).slice(0, -3); + } + + if (rule.startsWith(cwd)) { + return rule.replace(cwd, '.'); + } + + return rule; + }).filter(Boolean).join(' '); + if (ignoring) utils.log.detail('ignoring: ' + ignoring); + + utils.log.info('watching path(s): ' + config.options.monitor.map(function (rule) { + if (rule.slice(0, 1) !== '!') { + try { + rule = path.relative(process.cwd(), rule); + } catch (e) {} + + return rule; + } + + return false; + }).filter(Boolean).join(' ')); + + utils.log.info('watching extensions: ' + (config.options.execOptions.ext || '(all)')); + + if (config.options.dump) { + utils.log._log('log', '--------------'); + utils.log._log('log', 'node: ' + process.version); + utils.log._log('log', 'nodemon: ' + version.pinned); + utils.log._log('log', 'command: ' + process.argv.join(' ')); + utils.log._log('log', 'cwd: ' + cwd); + utils.log._log('log', ['OS:', process.platform, process.arch].join(' ')); + utils.log._log('log', '--------------'); + utils.log._log('log', util.inspect(config, { depth: null })); + utils.log._log('log', '--------------'); + if (!config.required) { + process.exit(); + } + + return; + } + + config.run = true; + + if (config.options.stdout === false) { + nodemon.on('start', function () { + nodemon.stdout = bus.stdout; + nodemon.stderr = bus.stderr; + + bus.emit('readable'); + }); + } + + if (config.options.events && Object.keys(config.options.events).length) { + Object.keys(config.options.events).forEach(function (key) { + utils.log.detail('bind ' + key + ' -> `' + + config.options.events[key] + '`'); + nodemon.on(key, function () { + if (config.options && config.options.events) { + spawn(config.options.events[key], config, + [].slice.apply(arguments)); + } + }); + }); + } + + monitor.run(config.options); + + }); + + return nodemon; +} + +nodemon.restart = function () { + utils.log.status('restarting child process'); + bus.emit('restart'); + return nodemon; +}; + +nodemon.addListener = nodemon.on = function (event, handler) { + if (!eventHandlers[event]) { eventHandlers[event] = []; } + eventHandlers[event].push(handler); + bus.on(event, handler); + return nodemon; +}; + +nodemon.once = function (event, handler) { + if (!eventHandlers[event]) { eventHandlers[event] = []; } + eventHandlers[event].push(handler); + bus.once(event, function () { + debug('bus.once(%s)', event); + eventHandlers[event].splice(eventHandlers[event].indexOf(handler), 1); + handler.apply(this, arguments); + }); + return nodemon; +}; + +nodemon.emit = function () { + bus.emit.apply(bus, [].slice.call(arguments)); + return nodemon; +}; + +nodemon.removeAllListeners = function (event) { + // unbind only the `nodemon.on` event handlers + Object.keys(eventHandlers).filter(function (e) { + return event ? e === event : true; + }).forEach(function (event) { + eventHandlers[event].forEach(function (handler) { + bus.removeListener(event, handler); + eventHandlers[event].splice(eventHandlers[event].indexOf(handler), 1); + }); + }); + + return nodemon; +}; + +nodemon.reset = function (done) { + bus.emit('reset', done); +}; + +bus.on('reset', function (done) { + debug('reset'); + nodemon.removeAllListeners(); + monitor.run.kill(true, function () { + utils.reset(); + config.reset(); + config.run = false; + if (done) { + done(); + } + }); +}); + +// expose the full config +nodemon.config = config; + +module.exports = nodemon; + diff --git a/node_modules/nodemon/lib/rules/add.js b/node_modules/nodemon/lib/rules/add.js new file mode 100644 index 0000000000000000000000000000000000000000..11f1fd714a2c866e863d47794802cd7b1a8a6837 --- /dev/null +++ b/node_modules/nodemon/lib/rules/add.js @@ -0,0 +1,89 @@ +'use strict'; + +var utils = require('../utils'); + +// internal +var reEscComments = /\\#/g; +// note that '^^' is used in place of escaped comments +var reUnescapeComments = /\^\^/g; +var reComments = /#.*$/; +var reEscapeChars = /[.|\-[\]()\\]/g; +var reAsterisk = /\*/g; + +module.exports = add; + +/** + * Converts file patterns or regular expressions to nodemon + * compatible RegExp matching rules. Note: the `rules` argument + * object is modified to include the new rule and new RegExp + * + * ### Example: + * + * var rules = { watch: [], ignore: [] }; + * add(rules, 'watch', '*.js'); + * add(rules, 'ignore', '/public/'); + * add(rules, 'watch', ':(\d)*\.js'); // note: string based regexp + * add(rules, 'watch', /\d*\.js/); + * + * @param {Object} rules containing `watch` and `ignore`. Also updated during + * execution + * @param {String} which must be either "watch" or "ignore" + * @param {String|RegExp} rule the actual rule. + */ +function add(rules, which, rule) { + if (!{ ignore: 1, watch: 1}[which]) { + throw new Error('rules/index.js#add requires "ignore" or "watch" as the ' + + 'first argument'); + } + + if (Array.isArray(rule)) { + rule.forEach(function (rule) { + add(rules, which, rule); + }); + return; + } + + // support the rule being a RegExp, but reformat it to + // the custom : format that we're working with. + if (rule instanceof RegExp) { + // rule = ':' + rule.toString().replace(/^\/(.*?)\/$/g, '$1'); + utils.log.error('RegExp format no longer supported, but globs are.'); + return; + } + + // remove comments and trim lines + // this mess of replace methods is escaping "\#" to allow for emacs temp files + + // first up strip comments and remove blank head or tails + rule = (rule || '').replace(reEscComments, '^^') + .replace(reComments, '') + .replace(reUnescapeComments, '#').trim(); + + var regexp = false; + + if (typeof rule === 'string' && rule.substring(0, 1) === ':') { + rule = rule.substring(1); + utils.log.error('RegExp no longer supported: ' + rule); + regexp = true; + } else if (rule.length === 0) { + // blank line (or it was a comment) + return; + } + + if (regexp) { + // rules[which].push(rule); + } else { + // rule = rule.replace(reEscapeChars, '\\$&') + // .replace(reAsterisk, '.*'); + + rules[which].push(rule); + // compile a regexp of all the rules for this ignore or watch + var re = rules[which].map(function (rule) { + return rule.replace(reEscapeChars, '\\$&') + .replace(reAsterisk, '.*'); + }).join('|'); + + // used for the directory matching + rules[which].re = new RegExp(re); + } +} diff --git a/node_modules/nodemon/lib/rules/index.js b/node_modules/nodemon/lib/rules/index.js new file mode 100644 index 0000000000000000000000000000000000000000..04aa92f87ef0e915a4e7640ab418cb79a29df8d2 --- /dev/null +++ b/node_modules/nodemon/lib/rules/index.js @@ -0,0 +1,53 @@ +'use strict'; +var utils = require('../utils'); +var add = require('./add'); +var parse = require('./parse'); + +// exported +var rules = { ignore: [], watch: [] }; + +/** + * Loads a nodemon config file and populates the ignore + * and watch rules with it's contents, and calls callback + * with the new rules + * + * @param {String} filename + * @param {Function} callback + */ +function load(filename, callback) { + parse(filename, function (err, result) { + if (err) { + // we should have bombed already, but + utils.log.error(err); + callback(err); + } + + if (result.raw) { + result.raw.forEach(add.bind(null, rules, 'ignore')); + } else { + result.ignore.forEach(add.bind(null, rules, 'ignore')); + result.watch.forEach(add.bind(null, rules, 'watch')); + } + + callback(null, rules); + }); +} + +module.exports = { + reset: function () { // just used for testing + rules.ignore.length = rules.watch.length = 0; + delete rules.ignore.re; + delete rules.watch.re; + }, + load: load, + ignore: { + test: add.bind(null, rules, 'ignore'), + add: add.bind(null, rules, 'ignore'), + }, + watch: { + test: add.bind(null, rules, 'watch'), + add: add.bind(null, rules, 'watch'), + }, + add: add.bind(null, rules), + rules: rules, +}; \ No newline at end of file diff --git a/node_modules/nodemon/lib/rules/parse.js b/node_modules/nodemon/lib/rules/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..6e1caceaa1e574fac2323d5e78ccf1f226bd832e --- /dev/null +++ b/node_modules/nodemon/lib/rules/parse.js @@ -0,0 +1,43 @@ +'use strict'; +var fs = require('fs'); + +/** + * Parse the nodemon config file, supporting both old style + * plain text config file, and JSON version of the config + * + * @param {String} filename + * @param {Function} callback + */ +function parse(filename, callback) { + var rules = { + ignore: [], + watch: [], + }; + + fs.readFile(filename, 'utf8', function (err, content) { + + if (err) { + return callback(err); + } + + var json = null; + try { + json = JSON.parse(content); + } catch (e) {} + + if (json !== null) { + rules = { + ignore: json.ignore || [], + watch: json.watch || [], + }; + + return callback(null, rules); + } + + // otherwise return the raw file + return callback(null, { raw: content.split(/\n/) }); + }); +} + +module.exports = parse; + diff --git a/node_modules/nodemon/lib/spawn.js b/node_modules/nodemon/lib/spawn.js new file mode 100644 index 0000000000000000000000000000000000000000..256734a01f90029f50ffad8bfbb9a721ec68ac62 --- /dev/null +++ b/node_modules/nodemon/lib/spawn.js @@ -0,0 +1,74 @@ +const path = require('path'); +const utils = require('./utils'); +const merge = utils.merge; +const bus = utils.bus; +const spawn = require('child_process').spawn; + +module.exports = function spawnCommand(command, config, eventArgs) { + var stdio = ['pipe', 'pipe', 'pipe']; + + if (config.options.stdout) { + stdio = ['pipe', process.stdout, process.stderr]; + } + + const env = merge(process.env, { FILENAME: eventArgs[0] }); + + var sh = 'sh'; + var shFlag = '-c'; + var spawnOptions = { + env: merge(config.options.execOptions.env, env), + stdio: stdio, + }; + + if (!Array.isArray(command)) { + command = [command]; + } + + if (utils.isWindows) { + // if the exec includes a forward slash, reverse it for windows compat + // but *only* apply to the first command, and none of the arguments. + // ref #1251 and #1236 + command = command.map(executable => { + if (executable.indexOf('/') === -1) { + return executable; + } + + return executable.split(' ').map((e, i) => { + if (i === 0) { + return path.normalize(e); + } + return e; + }).join(' '); + }); + // taken from npm's cli: https://git.io/vNFD4 + sh = process.env.comspec || 'cmd'; + shFlag = '/d /s /c'; + spawnOptions.windowsVerbatimArguments = true; + spawnOptions.windowsHide = true; + } + + const args = command.join(' '); + const child = spawn(sh, [shFlag, args], spawnOptions); + + if (config.required) { + var emit = { + stdout: function (data) { + bus.emit('stdout', data); + }, + stderr: function (data) { + bus.emit('stderr', data); + }, + }; + + // now work out what to bind to... + if (config.options.stdout) { + child.on('stdout', emit.stdout).on('stderr', emit.stderr); + } else { + child.stdout.on('data', emit.stdout); + child.stderr.on('data', emit.stderr); + + bus.stdout = child.stdout; + bus.stderr = child.stderr; + } + } +}; diff --git a/node_modules/nodemon/lib/utils/bus.js b/node_modules/nodemon/lib/utils/bus.js new file mode 100644 index 0000000000000000000000000000000000000000..4e120c58d6d4f3a1f35156b48b06eef92e233a73 --- /dev/null +++ b/node_modules/nodemon/lib/utils/bus.js @@ -0,0 +1,44 @@ +var events = require('events'); +var debug = require('debug')('nodemon'); +var util = require('util'); + +var Bus = function () { + events.EventEmitter.call(this); +}; + +util.inherits(Bus, events.EventEmitter); + +var bus = new Bus(); + +// /* +var collected = {}; +bus.on('newListener', function (event) { + debug('bus new listener: %s (%s)', event, bus.listeners(event).length); + if (!collected[event]) { + collected[event] = true; + bus.on(event, function () { + debug('bus emit: %s', event); + }); + } +}); + +// */ + +// proxy process messages (if forked) to the bus +process.on('message', function (event) { + debug('process.message(%s)', event); + bus.emit(event); +}); + +var emit = bus.emit; + +// if nodemon was spawned via a fork, allow upstream communication +// via process.send +if (process.send) { + bus.emit = function (event, data) { + process.send({ type: event, data: data }); + emit.apply(bus, arguments); + }; +} + +module.exports = bus; diff --git a/node_modules/nodemon/lib/utils/clone.js b/node_modules/nodemon/lib/utils/clone.js new file mode 100644 index 0000000000000000000000000000000000000000..6ba6330f33551e3378bd53ab17d8a2c3a3e56b65 --- /dev/null +++ b/node_modules/nodemon/lib/utils/clone.js @@ -0,0 +1,40 @@ +module.exports = clone; + +// via http://stackoverflow.com/a/728694/22617 +function clone(obj) { + // Handle the 3 simple types, and null or undefined + if (null === obj || 'object' !== typeof obj) { + return obj; + } + + var copy; + + // Handle Date + if (obj instanceof Date) { + copy = new Date(); + copy.setTime(obj.getTime()); + return copy; + } + + // Handle Array + if (obj instanceof Array) { + copy = []; + for (var i = 0, len = obj.length; i < len; i++) { + copy[i] = clone(obj[i]); + } + return copy; + } + + // Handle Object + if (obj instanceof Object) { + copy = {}; + for (var attr in obj) { + if (obj.hasOwnProperty && obj.hasOwnProperty(attr)) { + copy[attr] = clone(obj[attr]); + } + } + return copy; + } + + throw new Error('Unable to copy obj! Its type isn\'t supported.'); +} \ No newline at end of file diff --git a/node_modules/nodemon/lib/utils/colour.js b/node_modules/nodemon/lib/utils/colour.js new file mode 100644 index 0000000000000000000000000000000000000000..8c1b59054413d7c17868e8935a186878ed6e2238 --- /dev/null +++ b/node_modules/nodemon/lib/utils/colour.js @@ -0,0 +1,26 @@ +/** + * Encodes a string in a colour: red, yellow or green + * @param {String} c colour to highlight in + * @param {String} str the string to encode + * @return {String} coloured string for terminal printing + */ +function colour(c, str) { + return (colour[c] || colour.black) + str + colour.black; +} + +function strip(str) { + re.lastIndex = 0; // reset position + return str.replace(re, ''); +} + +colour.red = '\x1B[31m'; +colour.yellow = '\x1B[33m'; +colour.green = '\x1B[32m'; +colour.black = '\x1B[39m'; + +var reStr = Object.keys(colour).map(key => colour[key]).join('|'); +var re = new RegExp(('(' + reStr + ')').replace(/\[/g, '\\['), 'g'); + +colour.strip = strip; + +module.exports = colour; diff --git a/node_modules/nodemon/lib/utils/index.js b/node_modules/nodemon/lib/utils/index.js new file mode 100644 index 0000000000000000000000000000000000000000..92651216d2f127321b2b1cf5a08a46a92325cc73 --- /dev/null +++ b/node_modules/nodemon/lib/utils/index.js @@ -0,0 +1,103 @@ +var noop = function () { }; +var path = require('path'); +const semver = require('semver'); +var version = process.versions.node.split('.') || [null, null, null]; + +var utils = (module.exports = { + semver: semver, + satisfies: test => semver.satisfies(process.versions.node, test), + version: { + major: parseInt(version[0] || 0, 10), + minor: parseInt(version[1] || 0, 10), + patch: parseInt(version[2] || 0, 10), + }, + clone: require('./clone'), + merge: require('./merge'), + bus: require('./bus'), + isWindows: process.platform === 'win32', + isMac: process.platform === 'darwin', + isLinux: process.platform === 'linux', + isIBMi: require('os').type() === 'OS400', + isRequired: (function () { + var p = module.parent; + while (p) { + // in electron.js engine it happens + if (!p.filename) { + return true; + } + if (p.filename.indexOf('bin' + path.sep + 'nodemon.js') !== -1) { + return false; + } + p = p.parent; + } + + return true; + })(), + home: process.env.HOME || process.env.HOMEPATH, + quiet: function () { + // nukes the logging + if (!this.debug) { + for (var method in utils.log) { + if (typeof utils.log[method] === 'function') { + utils.log[method] = noop; + } + } + } + }, + reset: function () { + if (!this.debug) { + for (var method in utils.log) { + if (typeof utils.log[method] === 'function') { + delete utils.log[method]; + } + } + } + this.debug = false; + }, + regexpToText: function (t) { + return t + .replace(/\.\*\\./g, '*.') + .replace(/\\{2}/g, '^^') + .replace(/\\/g, '') + .replace(/\^\^/g, '\\'); + }, + stringify: function (exec, args) { + // serializes an executable string and array of arguments into a string + args = args || []; + + return [exec] + .concat( + args.map(function (arg) { + // if an argument contains a space, we want to show it with quotes + // around it to indicate that it is a single argument + if (arg.length > 0 && arg.indexOf(' ') === -1) { + return arg; + } + // this should correctly escape nested quotes + return JSON.stringify(arg); + }) + ) + .join(' ') + .trim(); + }, +}); + +utils.log = require('./log')(utils.isRequired); + +Object.defineProperty(utils, 'debug', { + set: function (value) { + this.log.debug = value; + }, + get: function () { + return this.log.debug; + }, +}); + +Object.defineProperty(utils, 'colours', { + set: function (value) { + this.log.useColours = value; + }, + get: function () { + return this.log.useColours; + }, +}); diff --git a/node_modules/nodemon/lib/utils/log.js b/node_modules/nodemon/lib/utils/log.js new file mode 100644 index 0000000000000000000000000000000000000000..65800872d11b5fe861add16be08cf024fcbddc2d --- /dev/null +++ b/node_modules/nodemon/lib/utils/log.js @@ -0,0 +1,82 @@ +var colour = require('./colour'); +var bus = require('./bus'); +var required = false; +var useColours = true; + +var coding = { + log: 'black', + info: 'yellow', + status: 'green', + detail: 'yellow', + fail: 'red', + error: 'red', +}; + +function log(type, text) { + var msg = '[nodemon] ' + (text || ''); + + if (useColours) { + msg = colour(coding[type], msg); + } + + // always push the message through our bus, using nextTick + // to help testing and get _out of_ promises. + process.nextTick(() => { + bus.emit('log', { type: type, message: text, colour: msg }); + }); + + // but if we're running on the command line, also echo out + // question: should we actually just consume our own events? + if (!required) { + if (type === 'error') { + console.error(msg); + } else { + console.log(msg || ''); + } + } +} + +var Logger = function (r) { + if (!(this instanceof Logger)) { + return new Logger(r); + } + this.required(r); + return this; +}; + +Object.keys(coding).forEach(function (type) { + Logger.prototype[type] = log.bind(null, type); +}); + +// detail is for messages that are turned on during debug +Logger.prototype.detail = function (msg) { + if (this.debug) { + log('detail', msg); + } +}; + +Logger.prototype.required = function (val) { + required = val; +}; + +Logger.prototype.debug = false; +Logger.prototype._log = function (type, msg) { + if (required) { + bus.emit('log', { type: type, message: msg || '', colour: msg || '' }); + } else if (type === 'error') { + console.error(msg); + } else { + console.log(msg || ''); + } +}; + +Object.defineProperty(Logger.prototype, 'useColours', { + set: function (val) { + useColours = val; + }, + get: function () { + return useColours; + }, +}); + +module.exports = Logger; diff --git a/node_modules/nodemon/lib/utils/merge.js b/node_modules/nodemon/lib/utils/merge.js new file mode 100644 index 0000000000000000000000000000000000000000..1f3440bd6aa2b3815ae547818a41bfd8e86b3d75 --- /dev/null +++ b/node_modules/nodemon/lib/utils/merge.js @@ -0,0 +1,47 @@ +var clone = require('./clone'); + +module.exports = merge; + +function typesMatch(a, b) { + return (typeof a === typeof b) && (Array.isArray(a) === Array.isArray(b)); +} + +/** + * A deep merge of the source based on the target. + * @param {Object} source [description] + * @param {Object} target [description] + * @return {Object} [description] + */ +function merge(source, target, result) { + if (result === undefined) { + result = clone(source); + } + + // merge missing values from the target to the source + Object.getOwnPropertyNames(target).forEach(function (key) { + if (source[key] === undefined) { + result[key] = target[key]; + } + }); + + Object.getOwnPropertyNames(source).forEach(function (key) { + var value = source[key]; + + if (target[key] && typesMatch(value, target[key])) { + // merge empty values + if (value === '') { + result[key] = target[key]; + } + + if (Array.isArray(value)) { + if (value.length === 0 && target[key].length) { + result[key] = target[key].slice(0); + } + } else if (typeof value === 'object') { + result[key] = merge(value, target[key]); + } + } + }); + + return result; +} \ No newline at end of file diff --git a/node_modules/nodemon/lib/version.js b/node_modules/nodemon/lib/version.js new file mode 100644 index 0000000000000000000000000000000000000000..d0f510447f57b96aad5bf60c59f6cd3d741bfb8d --- /dev/null +++ b/node_modules/nodemon/lib/version.js @@ -0,0 +1,100 @@ +module.exports = version; +module.exports.pin = pin; + +var fs = require('fs'); +var path = require('path'); +var exec = require('child_process').exec; +var root = null; + +function pin() { + return version().then(function (v) { + version.pinned = v; + }); +} + +function version(callback) { + // first find the package.json as this will be our root + var promise = findPackage(path.dirname(module.parent.filename)) + .then(function (dir) { + // now try to load the package + var v = require(path.resolve(dir, 'package.json')).version; + + if (v && v !== '0.0.0-development') { + return v; + } + + root = dir; + + // else we're in development, give the commit out + // get the last commit and whether the working dir is dirty + var promises = [ + branch().catch(function () { return 'master'; }), + commit().catch(function () { return ''; }), + dirty().catch(function () { return 0; }), + ]; + + // use the cached result as the export + return Promise.all(promises).then(function (res) { + var branch = res[0]; + var commit = res[1]; + var dirtyCount = parseInt(res[2], 10); + var curr = branch + ': ' + commit; + if (dirtyCount !== 0) { + curr += ' (' + dirtyCount + ' dirty files)'; + } + + return curr; + }); + }).catch(function (error) { + console.log(error.stack); + throw error; + }); + + if (callback) { + promise.then(function (res) { + callback(null, res); + }, callback); + } + + return promise; +} + +function findPackage(dir) { + if (dir === '/') { + return Promise.reject(new Error('package not found')); + } + return new Promise(function (resolve) { + fs.stat(path.resolve(dir, 'package.json'), function (error, exists) { + if (error || !exists) { + return resolve(findPackage(path.resolve(dir, '..'))); + } + + resolve(dir); + }); + }); +} + +function command(cmd) { + return new Promise(function (resolve, reject) { + exec(cmd, { cwd: root }, function (err, stdout, stderr) { + var error = stderr.trim(); + if (error) { + return reject(new Error(error)); + } + resolve(stdout.split('\n').join('')); + }); + }); +} + +function commit() { + return command('git rev-parse HEAD'); +} + +function branch() { + return command('git rev-parse --abbrev-ref HEAD'); +} + +function dirty() { + return command('expr $(git status --porcelain 2>/dev/null| ' + + 'egrep "^(M| M)" | wc -l)'); +} diff --git a/node_modules/nodemon/package.json b/node_modules/nodemon/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f742a1ed3f9bb83c2958c3ed5e2ca3c93d05c6c3 --- /dev/null +++ b/node_modules/nodemon/package.json @@ -0,0 +1,78 @@ +{ + "name": "nodemon", + "homepage": "https://nodemon.io", + "author": { + "name": "Remy Sharp", + "url": "https://github.com/remy" + }, + "bin": { + "nodemon": "./bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "repository": { + "type": "git", + "url": "https://github.com/remy/nodemon.git" + }, + "description": "Simple monitor script for use during development of a Node.js app.", + "keywords": [ + "cli", + "monitor", + "monitor", + "development", + "restart", + "autoload", + "reload", + "terminal" + ], + "license": "MIT", + "types": "./index.d.ts", + "main": "./lib/nodemon", + "scripts": { + "commitmsg": "commitlint -e", + "coverage": "istanbul cover _mocha -- --timeout 30000 --ui bdd --reporter list test/**/*.test.js", + "lint": "eslint lib/**/*.js", + "test": "npm run lint && npm run spec", + "spec": "for FILE in test/**/*.test.js; do echo $FILE; TEST=1 mocha --exit --timeout 30000 $FILE; if [ $? -ne 0 ]; then exit 1; fi; sleep 1; done", + "postspec": "npm run clean", + "clean": "rm -rf test/fixtures/test*.js test/fixtures/test*.md", + "web": "node web", + "semantic-release": "semantic-release", + "prepush": "npm run lint", + "killall": "ps auxww | grep node | grep -v grep | awk '{ print $2 }' | xargs kill -9" + }, + "devDependencies": { + "@commitlint/cli": "^11.0.0", + "@commitlint/config-conventional": "^11.0.0", + "async": "1.4.2", + "coffee-script": "~1.7.1", + "eslint": "^7.32.0", + "husky": "^7.0.4", + "mocha": "^2.5.3", + "nyc": "^15.1.0", + "proxyquire": "^1.8.0", + "semantic-release": "^25.0.0", + "should": "~4.0.0" + }, + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^10.2.1", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "version": "3.1.14", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + }, + "publishConfig": { + "provenance": true + } +} diff --git a/node_modules/normalize-path/LICENSE b/node_modules/normalize-path/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d32ab4426a5f6bd7986ed80df4073bbf997903d1 --- /dev/null +++ b/node_modules/normalize-path/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2018, Jon Schlinkert. + +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. diff --git a/node_modules/normalize-path/README.md b/node_modules/normalize-path/README.md new file mode 100644 index 0000000000000000000000000000000000000000..726d4d6891a295fbd2706d7c98ba72f09b8a4a6b --- /dev/null +++ b/node_modules/normalize-path/README.md @@ -0,0 +1,127 @@ +# normalize-path [![NPM version](https://img.shields.io/npm/v/normalize-path.svg?style=flat)](https://www.npmjs.com/package/normalize-path) [![NPM monthly downloads](https://img.shields.io/npm/dm/normalize-path.svg?style=flat)](https://npmjs.org/package/normalize-path) [![NPM total downloads](https://img.shields.io/npm/dt/normalize-path.svg?style=flat)](https://npmjs.org/package/normalize-path) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/normalize-path.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/normalize-path) + +> Normalize slashes in a file path to be posix/unix-like forward slashes. Also condenses repeat slashes to a single slash and removes and trailing slashes, unless disabled. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save normalize-path +``` + +## Usage + +```js +const normalize = require('normalize-path'); + +console.log(normalize('\\foo\\bar\\baz\\')); +//=> '/foo/bar/baz' +``` + +**win32 namespaces** + +```js +console.log(normalize('\\\\?\\UNC\\Server01\\user\\docs\\Letter.txt')); +//=> '//?/UNC/Server01/user/docs/Letter.txt' + +console.log(normalize('\\\\.\\CdRomX')); +//=> '//./CdRomX' +``` + +**Consecutive slashes** + +Condenses multiple consecutive forward slashes (except for leading slashes in win32 namespaces) to a single slash. + +```js +console.log(normalize('.//foo//bar///////baz/')); +//=> './foo/bar/baz' +``` + +### Trailing slashes + +By default trailing slashes are removed. Pass `false` as the last argument to disable this behavior and _**keep** trailing slashes_: + +```js +console.log(normalize('foo\\bar\\baz\\', false)); //=> 'foo/bar/baz/' +console.log(normalize('./foo/bar/baz/', false)); //=> './foo/bar/baz/' +``` + +## Release history + +### v3.0 + +No breaking changes in this release. + +* a check was added to ensure that [win32 namespaces](https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces) are handled properly by win32 `path.parse()` after a path has been normalized by this library. +* a minor optimization was made to simplify how the trailing separator was handled + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +Other useful path-related libraries: + +* [contains-path](https://www.npmjs.com/package/contains-path): Return true if a file path contains the given path. | [homepage](https://github.com/jonschlinkert/contains-path "Return true if a file path contains the given path.") +* [is-absolute](https://www.npmjs.com/package/is-absolute): Returns true if a file path is absolute. Does not rely on the path module… [more](https://github.com/jonschlinkert/is-absolute) | [homepage](https://github.com/jonschlinkert/is-absolute "Returns true if a file path is absolute. Does not rely on the path module and can be used as a polyfill for node.js native `path.isAbolute`.") +* [is-relative](https://www.npmjs.com/package/is-relative): Returns `true` if the path appears to be relative. | [homepage](https://github.com/jonschlinkert/is-relative "Returns `true` if the path appears to be relative.") +* [parse-filepath](https://www.npmjs.com/package/parse-filepath): Pollyfill for node.js `path.parse`, parses a filepath into an object. | [homepage](https://github.com/jonschlinkert/parse-filepath "Pollyfill for node.js `path.parse`, parses a filepath into an object.") +* [path-ends-with](https://www.npmjs.com/package/path-ends-with): Return `true` if a file path ends with the given string/suffix. | [homepage](https://github.com/jonschlinkert/path-ends-with "Return `true` if a file path ends with the given string/suffix.") +* [unixify](https://www.npmjs.com/package/unixify): Convert Windows file paths to unix paths. | [homepage](https://github.com/jonschlinkert/unixify "Convert Windows file paths to unix paths.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 35 | [jonschlinkert](https://github.com/jonschlinkert) | +| 1 | [phated](https://github.com/phated) | + +### Author + +**Jon Schlinkert** + +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) + +### License + +Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on April 19, 2018._ \ No newline at end of file diff --git a/node_modules/normalize-path/index.js b/node_modules/normalize-path/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6fac553a30915ee38b6c1552b8df343da69f3926 --- /dev/null +++ b/node_modules/normalize-path/index.js @@ -0,0 +1,35 @@ +/*! + * normalize-path + * + * Copyright (c) 2014-2018, Jon Schlinkert. + * Released under the MIT License. + */ + +module.exports = function(path, stripTrailing) { + if (typeof path !== 'string') { + throw new TypeError('expected path to be a string'); + } + + if (path === '\\' || path === '/') return '/'; + + var len = path.length; + if (len <= 1) return path; + + // ensure that win32 namespaces has two leading slashes, so that the path is + // handled properly by the win32 version of path.parse() after being normalized + // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + var prefix = ''; + if (len > 4 && path[3] === '\\') { + var ch = path[2]; + if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { + path = path.slice(2); + prefix = '//'; + } + } + + var segs = path.split(/[/\\]+/); + if (stripTrailing !== false && segs[segs.length - 1] === '') { + segs.pop(); + } + return prefix + segs.join('/'); +}; diff --git a/node_modules/normalize-path/package.json b/node_modules/normalize-path/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ad61098a8a8fc51a4be93b25769a47959abd5ade --- /dev/null +++ b/node_modules/normalize-path/package.json @@ -0,0 +1,77 @@ +{ + "name": "normalize-path", + "description": "Normalize slashes in a file path to be posix/unix-like forward slashes. Also condenses repeat slashes to a single slash and removes and trailing slashes, unless disabled.", + "version": "3.0.0", + "homepage": "https://github.com/jonschlinkert/normalize-path", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Blaine Bublitz (https://twitter.com/BlaineBublitz)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)" + ], + "repository": "jonschlinkert/normalize-path", + "bugs": { + "url": "https://github.com/jonschlinkert/normalize-path/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "gulp-format-md": "^1.0.0", + "minimist": "^1.2.0", + "mocha": "^3.5.3" + }, + "keywords": [ + "absolute", + "backslash", + "delimiter", + "file", + "file-path", + "filepath", + "fix", + "forward", + "fp", + "fs", + "normalize", + "path", + "relative", + "separator", + "slash", + "slashes", + "trailing", + "unix", + "urix" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "related": { + "description": "Other useful path-related libraries:", + "list": [ + "contains-path", + "is-absolute", + "is-relative", + "parse-filepath", + "path-ends-with", + "path-ends-with", + "unixify" + ] + }, + "lint": { + "reflinks": true + } + } +} diff --git a/node_modules/normalize-svg-path/.eslintrc.json b/node_modules/normalize-svg-path/.eslintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..ab87b064922bb21099f463bcafc37585340c3b2b --- /dev/null +++ b/node_modules/normalize-svg-path/.eslintrc.json @@ -0,0 +1,43 @@ +{ + "env": { + "browser": true, + "node": true, + "commonjs": true, + "es6": true + }, + "extends": "eslint:recommended", + "rules": { + "strict": 2, + "indent": 0, + "linebreak-style": 0, + "quotes": 0, + "semi": 0, + "no-cond-assign": 1, + "no-constant-condition": 1, + "no-duplicate-case": 1, + "no-empty": 1, + "no-ex-assign": 1, + "no-extra-boolean-cast": 1, + "no-extra-semi": 1, + "no-fallthrough": 1, + "no-func-assign": 1, + "no-global-assign": 1, + "no-implicit-globals": 2, + "no-inner-declarations": ["error", "functions"], + "no-irregular-whitespace": 2, + "no-loop-func": 1, + "no-multi-str": 1, + "no-mixed-spaces-and-tabs": 1, + "no-proto": 1, + "no-sequences": 1, + "no-throw-literal": 1, + "no-unmodified-loop-condition": 1, + "no-useless-call": 1, + "no-void": 1, + "no-with": 2, + "wrap-iife": 1, + "no-redeclare": 1, + "no-unused-vars": ["error", { "vars": "all", "args": "none" }], + "no-sparse-arrays": 1 + } +} diff --git a/node_modules/normalize-svg-path/.travis.yml b/node_modules/normalize-svg-path/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..a756a652361a41d0d5adbcfabca45066a78065e5 --- /dev/null +++ b/node_modules/normalize-svg-path/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "stable" diff --git a/node_modules/normalize-svg-path/Readme.md b/node_modules/normalize-svg-path/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..b67cd77188dbe37aa8ff62d211e239b32d768ee4 --- /dev/null +++ b/node_modules/normalize-svg-path/Readme.md @@ -0,0 +1,26 @@ +# normalize-svg-path [![build](https://travis-ci.org/jkroso/normalize-svg-path.svg?branch=master)](https://travis-ci.org/jkroso/normalize-svg-path) + + + Convert all segments in a path to curves. Usefull if you intend to animate one shape to another. By defining all segments with curves instead of a mix of lines, arcs, and curves tweening becomes much simpler. It could also help you rewrite your SVG code according to the principles of [narcissistic design](//vimeo.com/77199361). + +## Usage + +[![npm install normalize-svg-path](https://nodei.co/npm/normalize-svg-path.png?mini=true)](https://npmjs.org/package/normalize-svg-path/) + +```js +var parse = require('parse-svg-path') +var abs = require('abs-svg-path') +var normalize = require('normalize-svg-path') + +var segments = normalize(abs(parse('M0 0L10 10A10 10 0 0 0 20 20Z'))) +``` + +## API + +### normalize(path) + + Translate each segment in `path` to an equivalent cubic bézier curve. The input `path` must be [absolute](//github.com/jkroso/abs-svg-path). + +```js +normalize([['L',1,2]]) // => [['C',0,0,1,2,1,2]] +``` diff --git a/node_modules/normalize-svg-path/index.js b/node_modules/normalize-svg-path/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ed286c9d9fe9ca95837333e2040a1287a15466f1 --- /dev/null +++ b/node_modules/normalize-svg-path/index.js @@ -0,0 +1,122 @@ +'use strict' + +module.exports = normalize + +var arcToCurve = require('svg-arc-to-cubic-bezier') + +function normalize(path){ + // init state + var prev + var result = [] + var bezierX = 0 + var bezierY = 0 + var startX = 0 + var startY = 0 + var quadX = null + var quadY = null + var x = 0 + var y = 0 + + for (var i = 0, len = path.length; i < len; i++) { + var seg = path[i] + var command = seg[0] + + switch (command) { + case 'M': + startX = seg[1] + startY = seg[2] + break + case 'A': + var curves = arcToCurve({ + px: x, + py: y, + cx: seg[6], + cy: seg[7], + rx: seg[1], + ry: seg[2], + xAxisRotation: seg[3], + largeArcFlag: seg[4], + sweepFlag: seg[5] + }) + + // null-curves + if (!curves.length) continue + + for (var j = 0, c; j < curves.length; j++) { + c = curves[j] + seg = ['C', c.x1, c.y1, c.x2, c.y2, c.x, c.y] + if (j < curves.length - 1) result.push(seg) + } + + break + case 'S': + // default control point + var cx = x + var cy = y + if (prev == 'C' || prev == 'S') { + cx += cx - bezierX // reflect the previous command's control + cy += cy - bezierY // point relative to the current point + } + seg = ['C', cx, cy, seg[1], seg[2], seg[3], seg[4]] + break + case 'T': + if (prev == 'Q' || prev == 'T') { + quadX = x * 2 - quadX // as with 'S' reflect previous control point + quadY = y * 2 - quadY + } else { + quadX = x + quadY = y + } + seg = quadratic(x, y, quadX, quadY, seg[1], seg[2]) + break + case 'Q': + quadX = seg[1] + quadY = seg[2] + seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4]) + break + case 'L': + seg = line(x, y, seg[1], seg[2]) + break + case 'H': + seg = line(x, y, seg[1], y) + break + case 'V': + seg = line(x, y, x, seg[1]) + break + case 'Z': + seg = line(x, y, startX, startY) + break + } + + // update state + prev = command + x = seg[seg.length - 2] + y = seg[seg.length - 1] + if (seg.length > 4) { + bezierX = seg[seg.length - 4] + bezierY = seg[seg.length - 3] + } else { + bezierX = x + bezierY = y + } + result.push(seg) + } + + return result +} + +function line(x1, y1, x2, y2){ + return ['C', x1, y1, x2, y2, x2, y2] +} + +function quadratic(x1, y1, cx, cy, x2, y2){ + return [ + 'C', + x1/3 + (2/3) * cx, + y1/3 + (2/3) * cy, + x2/3 + (2/3) * cx, + y2/3 + (2/3) * cy, + x2, + y2 + ] +} diff --git a/node_modules/normalize-svg-path/index.mjs b/node_modules/normalize-svg-path/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1cc05572ec9262be8688941126f064b319fc9afc --- /dev/null +++ b/node_modules/normalize-svg-path/index.mjs @@ -0,0 +1,118 @@ +import arcToCurve from 'svg-arc-to-cubic-bezier' + +export default function normalize(path){ + // init state + var prev + var result = [] + var bezierX = 0 + var bezierY = 0 + var startX = 0 + var startY = 0 + var quadX = null + var quadY = null + var x = 0 + var y = 0 + + for (var i = 0, len = path.length; i < len; i++) { + var seg = path[i] + var command = seg[0] + + switch (command) { + case 'M': + startX = seg[1] + startY = seg[2] + break + case 'A': + var curves = arcToCurve({ + px: x, + py: y, + cx: seg[6], + cy: seg[7], + rx: seg[1], + ry: seg[2], + xAxisRotation: seg[3], + largeArcFlag: seg[4], + sweepFlag: seg[5] + }) + + // null-curves + if (!curves.length) continue + + for (var j = 0, c; j < curves.length; j++) { + c = curves[j] + seg = ['C', c.x1, c.y1, c.x2, c.y2, c.x, c.y] + if (j < curves.length - 1) result.push(seg) + } + + break + case 'S': + // default control point + var cx = x + var cy = y + if (prev == 'C' || prev == 'S') { + cx += cx - bezierX // reflect the previous command's control + cy += cy - bezierY // point relative to the current point + } + seg = ['C', cx, cy, seg[1], seg[2], seg[3], seg[4]] + break + case 'T': + if (prev == 'Q' || prev == 'T') { + quadX = x * 2 - quadX // as with 'S' reflect previous control point + quadY = y * 2 - quadY + } else { + quadX = x + quadY = y + } + seg = quadratic(x, y, quadX, quadY, seg[1], seg[2]) + break + case 'Q': + quadX = seg[1] + quadY = seg[2] + seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4]) + break + case 'L': + seg = line(x, y, seg[1], seg[2]) + break + case 'H': + seg = line(x, y, seg[1], y) + break + case 'V': + seg = line(x, y, x, seg[1]) + break + case 'Z': + seg = line(x, y, startX, startY) + break + } + + // update state + prev = command + x = seg[seg.length - 2] + y = seg[seg.length - 1] + if (seg.length > 4) { + bezierX = seg[seg.length - 4] + bezierY = seg[seg.length - 3] + } else { + bezierX = x + bezierY = y + } + result.push(seg) + } + + return result +} + +function line(x1, y1, x2, y2){ + return ['C', x1, y1, x2, y2, x2, y2] +} + +function quadratic(x1, y1, cx, cy, x2, y2){ + return [ + 'C', + x1/3 + (2/3) * cx, + y1/3 + (2/3) * cy, + x2/3 + (2/3) * cx, + y2/3 + (2/3) * cy, + x2, + y2 + ] +} diff --git a/node_modules/normalize-svg-path/license.md b/node_modules/normalize-svg-path/license.md new file mode 100644 index 0000000000000000000000000000000000000000..ea89a3fe185be3e7ee258390197cec1651971fc6 --- /dev/null +++ b/node_modules/normalize-svg-path/license.md @@ -0,0 +1,25 @@ + +The MIT License + +Copyright © 2008-2013 Dmitry Baranovskiy (http://raphaeljs.com) +Copyright © 2008-2013 Sencha Labs (http://sencha.com) +Copyright © 2013 Jake Rosoman + +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. diff --git a/node_modules/normalize-svg-path/package.json b/node_modules/normalize-svg-path/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a4ee350f94987ade5352c69533ba53bf662f51b5 --- /dev/null +++ b/node_modules/normalize-svg-path/package.json @@ -0,0 +1,30 @@ +{ + "name": "normalize-svg-path", + "version": "1.1.0", + "description": "Convert all segments in a path to curves", + "keywords": [ + "svg", + "path", + "normalize" + ], + "module": "./index.mjs", + "main": "./index.js", + "exports": { + "require": "./index.js", + "import": "./index.mjs" + }, + "dependencies": { + "svg-arc-to-cubic-bezier": "^3.0.0" + }, + "devDependencies": { + "parse-svg-path": "^0.1.2", + "tape": "^4.7.0" + }, + "scripts": { + "test": "node test.mjs" + }, + "repository": "git://github.com/jkroso/normalize-svg-path.git", + "bugs": "https://github.com/jkroso/normalize-svg-path/issues", + "author": "Jake Rosoman", + "license": "MIT" +} diff --git a/node_modules/normalize-svg-path/test.mjs b/node_modules/normalize-svg-path/test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e9f862414d35743394be349e52ce1c7e6a2012b6 --- /dev/null +++ b/node_modules/normalize-svg-path/test.mjs @@ -0,0 +1,131 @@ +import t from 'tape' +import normalize from './index.mjs' +import parse from 'parse-svg-path' + + +t('line-to', t => { + t.deepEqual( + normalize(parse('L100 100')), + parse('C0,0 100,100 100,100') + ) + + t.deepEqual( + normalize(parse('L50 50 100 0')), + parse('C0,0 50,50 50,50 C50,50 100,0 100,0') + ) + + t.deepEqual( + normalize(parse('H50 100')), + parse('C0,0 50,0 50,0 C50,0 100,0 100,0') + ) + + t.deepEqual( + normalize(parse('V50 100')), + parse('C0,0 0,50 0,50 C0,50 0,100 0,100') + ) + + t.end() +}) + +t('curve-to', t => { + t.deepEqual( + normalize(parse('M10 150 C10 10 150 10 150 150')), + parse('M10,150C10,10,150,10,150,150') + ) + + t.deepEqual( + normalize(parse('M0 120 Q60 0 120 120')), + parse('M0,120C40,40,80,40,120,120') + ) + + t.deepEqual( + normalize(parse('M10 80 C10 10 75 10 75 80 S150 150 150 80')), + parse('M10,80C10,10,75,10,75,80C75,150,150,150,150,80') + ) + + t.deepEqual( + normalize(parse('M0 60 Q30 0 60 60 T120 60')), + parse('M0,60C20,20,40,20,60,60C80,100,100,100,120,60') + ) + + t.deepEqual( + normalize(parse('M30 30 Q50 50 84 50 S124 73 107 92 T127 122')), + parse('M30,30C43.33333333333333,43.33333333333333,61.33333333333333,50,84,50C84,50,124,73,107,92C107,92,113.66666666666666,102,127,122') + ) + + t.end() +}) + +t('close-path', t => { + t.deepEqual( + normalize(parse('L100 0 100 100Z')), + parse('C0,0,100,0,100,0C100,0,100,100,100,100C100,100,0,0,0,0') + ) + + t.end() +}) + + + + +t('arc-to', t => { + t.deepEqual( + r(normalize(parse('M10 80 A150 150 0 0 0 150 80'))), + r(parse('M 10 80C 53.80473794537901 103.1133445143787 106.19526205462094 103.1133445143787 149.99999999999997 80.00000000000003')) + ) + + // half circle clockwise + t.deepEqual( + r(normalize(parse('M10 80 A50 50 0 0 1 150 80'))), + r(parse('M 10 80C 10 41.340067511844474 41.34006751184445 10.000000000000014 79.99999999999999 10C 118.65993248815552 10 150 41.34006751184445 150 79.99999999999999')) + ) + + // half circle anticlockwise + t.deepEqual( + r(normalize(parse('M10 80 A50 50 0 1 0 150 80'))), + r(parse('M 10 80C 10.000000000000014 118.65993248815553 41.340067511844474 150 80 150C 118.65993248815553 150 150 118.65993248815553 150 80')) + ) + + // circle + t.deepEqual( + r(normalize(parse('M10 80 A50 50 0 0 1 150 80 A50 50 0 0 1 10 80'))), + r(parse('M 10 80C 10 41.340067511844474 41.34006751184445 10.000000000000014 79.99999999999999 10C 118.65993248815552 10 150 41.34006751184445 150 79.99999999999999C 150 118.65993248815553 118.65993248815553 150 80 150C 41.340067511844474 150 10.000000000000014 118.65993248815553 10 80.00000000000001')) + ) + + t.deepEqual( + normalize(parse('M10 80 A150 75 30 0 0 150 80')), + parse('M 10 80C 72.04149682761658 108.21761044823509 129.85079028483736 108.21761044823509 150 79.99999999999999') + ) + + // the null curve + t.deepEqual( + normalize(parse('M10 80 A50 50 0 0 1 10 80')), + parse('M10,80') + ) + + t.end() +}) + +function r(arr) { return arr.map(function (arr) { return [arr[0]].concat(arr.slice(1).map(round)) }) } +function round(v) { return Math.round(v) } + +//show parsed curve in the doc +function show(src) { + let path = src.map(seg => seg.join(' ')).join('') + + let el = document.body.appendChild(document.createElement('div')) + let svgNS = 'http://www.w3.org/2000/svg' + + el.innerHTML = `` + + let svg = el.firstChild + + let pathEl = svg.appendChild(document.createElementNS(svgNS, 'path')) + pathEl.setAttribute('d', path) + + pathEl.style.strokeWidth = '2px'; + pathEl.style.stroke = 'black'; + pathEl.style.fill = 'transparent'; + + return src +} diff --git a/node_modules/object-assign/index.js b/node_modules/object-assign/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0930cf8890b9af66125c222c29d7bd75614ac6b4 --- /dev/null +++ b/node_modules/object-assign/index.js @@ -0,0 +1,90 @@ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; diff --git a/node_modules/object-assign/license b/node_modules/object-assign/license new file mode 100644 index 0000000000000000000000000000000000000000..654d0bfe943437d43242325b1fbcff5f400d84ee --- /dev/null +++ b/node_modules/object-assign/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/object-assign/package.json b/node_modules/object-assign/package.json new file mode 100644 index 0000000000000000000000000000000000000000..503eb1e6d0f5a1404c8e7f6c09fbda7e40fd29b4 --- /dev/null +++ b/node_modules/object-assign/package.json @@ -0,0 +1,42 @@ +{ + "name": "object-assign", + "version": "4.1.1", + "description": "ES2015 `Object.assign()` ponyfill", + "license": "MIT", + "repository": "sindresorhus/object-assign", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava", + "bench": "matcha bench.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "object", + "assign", + "extend", + "properties", + "es2015", + "ecmascript", + "harmony", + "ponyfill", + "prollyfill", + "polyfill", + "shim", + "browser" + ], + "devDependencies": { + "ava": "^0.16.0", + "lodash": "^4.16.4", + "matcha": "^0.7.0", + "xo": "^0.16.0" + } +} diff --git a/node_modules/object-assign/readme.md b/node_modules/object-assign/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..1be09d35c776cc0e9cc59519c2de6b9eecf8aa68 --- /dev/null +++ b/node_modules/object-assign/readme.md @@ -0,0 +1,61 @@ +# object-assign [![Build Status](https://travis-ci.org/sindresorhus/object-assign.svg?branch=master)](https://travis-ci.org/sindresorhus/object-assign) + +> ES2015 [`Object.assign()`](http://www.2ality.com/2014/01/object-assign.html) [ponyfill](https://ponyfill.com) + + +## Use the built-in + +Node.js 4 and up, as well as every evergreen browser (Chrome, Edge, Firefox, Opera, Safari), +support `Object.assign()` :tada:. If you target only those environments, then by all +means, use `Object.assign()` instead of this package. + + +## Install + +``` +$ npm install --save object-assign +``` + + +## Usage + +```js +const objectAssign = require('object-assign'); + +objectAssign({foo: 0}, {bar: 1}); +//=> {foo: 0, bar: 1} + +// multiple sources +objectAssign({foo: 0}, {bar: 1}, {baz: 2}); +//=> {foo: 0, bar: 1, baz: 2} + +// overwrites equal keys +objectAssign({foo: 0}, {foo: 1}, {foo: 2}); +//=> {foo: 2} + +// ignores null and undefined sources +objectAssign({foo: 0}, null, {bar: 1}, undefined); +//=> {foo: 0, bar: 1} +``` + + +## API + +### objectAssign(target, [source, ...]) + +Assigns enumerable own properties of `source` objects to the `target` object and returns the `target` object. Additional `source` objects will overwrite previous ones. + + +## Resources + +- [ES2015 spec - Object.assign](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign) + + +## Related + +- [deep-assign](https://github.com/sindresorhus/deep-assign) - Recursive `Object.assign()` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/object-hash/LICENSE b/node_modules/object-hash/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6ea185fae6b93a21dd4faf5659c313f4bcd4904c --- /dev/null +++ b/node_modules/object-hash/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2014 object-hash contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/object-hash/index.js b/node_modules/object-hash/index.js new file mode 100644 index 0000000000000000000000000000000000000000..962bf62887fd3b08c1665a40fc073ac997385f46 --- /dev/null +++ b/node_modules/object-hash/index.js @@ -0,0 +1,453 @@ +'use strict'; + +var crypto = require('crypto'); + +/** + * Exported function + * + * Options: + * + * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' + * - `excludeValues` {true|*false} hash object keys, values ignored + * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' + * - `ignoreUnknown` {true|*false} ignore unknown object types + * - `replacer` optional function that replaces values before hashing + * - `respectFunctionProperties` {*true|false} consider function properties when hashing + * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing + * - `respectType` {*true|false} Respect special properties (prototype, constructor) + * when hashing to distinguish between types + * - `unorderedArrays` {true|*false} Sort all arrays before hashing + * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing + * * = default + * + * @param {object} object value to hash + * @param {object} options hashing options + * @return {string} hash value + * @api public + */ +exports = module.exports = objectHash; + +function objectHash(object, options){ + options = applyDefaults(object, options); + + return hash(object, options); +} + +/** + * Exported sugar methods + * + * @param {object} object value to hash + * @return {string} hash value + * @api public + */ +exports.sha1 = function(object){ + return objectHash(object); +}; +exports.keys = function(object){ + return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); +}; +exports.MD5 = function(object){ + return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); +}; +exports.keysMD5 = function(object){ + return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); +}; + +// Internals +var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; +hashes.push('passthrough'); +var encodings = ['buffer', 'hex', 'binary', 'base64']; + +function applyDefaults(object, sourceOptions){ + sourceOptions = sourceOptions || {}; + + // create a copy rather than mutating + var options = {}; + options.algorithm = sourceOptions.algorithm || 'sha1'; + options.encoding = sourceOptions.encoding || 'hex'; + options.excludeValues = sourceOptions.excludeValues ? true : false; + options.algorithm = options.algorithm.toLowerCase(); + options.encoding = options.encoding.toLowerCase(); + options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false + options.respectType = sourceOptions.respectType === false ? false : true; // default to true + options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; + options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; + options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false + options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false + options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true + options.replacer = sourceOptions.replacer || undefined; + options.excludeKeys = sourceOptions.excludeKeys || undefined; + + if(typeof object === 'undefined') { + throw new Error('Object argument required.'); + } + + // if there is a case-insensitive match in the hashes list, accept it + // (i.e. SHA256 for sha256) + for (var i = 0; i < hashes.length; ++i) { + if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { + options.algorithm = hashes[i]; + } + } + + if(hashes.indexOf(options.algorithm) === -1){ + throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + + 'supported values: ' + hashes.join(', ')); + } + + if(encodings.indexOf(options.encoding) === -1 && + options.algorithm !== 'passthrough'){ + throw new Error('Encoding "' + options.encoding + '" not supported. ' + + 'supported values: ' + encodings.join(', ')); + } + + return options; +} + +/** Check if the given function is a native function */ +function isNativeFunction(f) { + if ((typeof f) !== 'function') { + return false; + } + var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; + return exp.exec(Function.prototype.toString.call(f)) != null; +} + +function hash(object, options) { + var hashingStream; + + if (options.algorithm !== 'passthrough') { + hashingStream = crypto.createHash(options.algorithm); + } else { + hashingStream = new PassThrough(); + } + + if (typeof hashingStream.write === 'undefined') { + hashingStream.write = hashingStream.update; + hashingStream.end = hashingStream.update; + } + + var hasher = typeHasher(options, hashingStream); + hasher.dispatch(object); + if (!hashingStream.update) { + hashingStream.end(''); + } + + if (hashingStream.digest) { + return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); + } + + var buf = hashingStream.read(); + if (options.encoding === 'buffer') { + return buf; + } + + return buf.toString(options.encoding); +} + +/** + * Expose streaming API + * + * @param {object} object Value to serialize + * @param {object} options Options, as for hash() + * @param {object} stream A stream to write the serializiation to + * @api public + */ +exports.writeToStream = function(object, options, stream) { + if (typeof stream === 'undefined') { + stream = options; + options = {}; + } + + options = applyDefaults(object, options); + + return typeHasher(options, stream).dispatch(object); +}; + +function typeHasher(options, writeTo, context){ + context = context || []; + var write = function(str) { + if (writeTo.update) { + return writeTo.update(str, 'utf8'); + } else { + return writeTo.write(str, 'utf8'); + } + }; + + return { + dispatch: function(value){ + if (options.replacer) { + value = options.replacer(value); + } + + var type = typeof value; + if (value === null) { + type = 'null'; + } + + //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); + + return this['_' + type](value); + }, + _object: function(object) { + var pattern = (/\[object (.*)\]/i); + var objString = Object.prototype.toString.call(object); + var objType = pattern.exec(objString); + if (!objType) { // object type did not match [object ...] + objType = 'unknown:[' + objString + ']'; + } else { + objType = objType[1]; // take only the class name + } + + objType = objType.toLowerCase(); + + var objectNumber = null; + + if ((objectNumber = context.indexOf(object)) >= 0) { + return this.dispatch('[CIRCULAR:' + objectNumber + ']'); + } else { + context.push(object); + } + + if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { + write('buffer:'); + return write(object); + } + + if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { + if(this['_' + objType]) { + this['_' + objType](object); + } else if (options.ignoreUnknown) { + return write('[' + objType + ']'); + } else { + throw new Error('Unknown object type "' + objType + '"'); + } + }else{ + var keys = Object.keys(object); + if (options.unorderedObjects) { + keys = keys.sort(); + } + // Make sure to incorporate special properties, so + // Types with different prototypes will produce + // a different hash and objects derived from + // different functions (`new Foo`, `new Bar`) will + // produce different hashes. + // We never do this for native functions since some + // seem to break because of that. + if (options.respectType !== false && !isNativeFunction(object)) { + keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); + } + + if (options.excludeKeys) { + keys = keys.filter(function(key) { return !options.excludeKeys(key); }); + } + + write('object:' + keys.length + ':'); + var self = this; + return keys.forEach(function(key){ + self.dispatch(key); + write(':'); + if(!options.excludeValues) { + self.dispatch(object[key]); + } + write(','); + }); + } + }, + _array: function(arr, unordered){ + unordered = typeof unordered !== 'undefined' ? unordered : + options.unorderedArrays !== false; // default to options.unorderedArrays + + var self = this; + write('array:' + arr.length + ':'); + if (!unordered || arr.length <= 1) { + return arr.forEach(function(entry) { + return self.dispatch(entry); + }); + } + + // the unordered case is a little more complicated: + // since there is no canonical ordering on objects, + // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, + // we first serialize each entry using a PassThrough stream + // before sorting. + // also: we can’t use the same context array for all entries + // since the order of hashing should *not* matter. instead, + // we keep track of the additions to a copy of the context array + // and add all of them to the global context array when we’re done + var contextAdditions = []; + var entries = arr.map(function(entry) { + var strm = new PassThrough(); + var localContext = context.slice(); // make copy + var hasher = typeHasher(options, strm, localContext); + hasher.dispatch(entry); + // take only what was added to localContext and append it to contextAdditions + contextAdditions = contextAdditions.concat(localContext.slice(context.length)); + return strm.read().toString(); + }); + context = context.concat(contextAdditions); + entries.sort(); + return this._array(entries, false); + }, + _date: function(date){ + return write('date:' + date.toJSON()); + }, + _symbol: function(sym){ + return write('symbol:' + sym.toString()); + }, + _error: function(err){ + return write('error:' + err.toString()); + }, + _boolean: function(bool){ + return write('bool:' + bool.toString()); + }, + _string: function(string){ + write('string:' + string.length + ':'); + write(string.toString()); + }, + _function: function(fn){ + write('fn:'); + if (isNativeFunction(fn)) { + this.dispatch('[native]'); + } else { + this.dispatch(fn.toString()); + } + + if (options.respectFunctionNames !== false) { + // Make sure we can still distinguish native functions + // by their name, otherwise String and Function will + // have the same hash + this.dispatch("function-name:" + String(fn.name)); + } + + if (options.respectFunctionProperties) { + this._object(fn); + } + }, + _number: function(number){ + return write('number:' + number.toString()); + }, + _xml: function(xml){ + return write('xml:' + xml.toString()); + }, + _null: function() { + return write('Null'); + }, + _undefined: function() { + return write('Undefined'); + }, + _regexp: function(regex){ + return write('regex:' + regex.toString()); + }, + _uint8array: function(arr){ + write('uint8array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint8clampedarray: function(arr){ + write('uint8clampedarray:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int8array: function(arr){ + write('int8array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint16array: function(arr){ + write('uint16array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int16array: function(arr){ + write('int16array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint32array: function(arr){ + write('uint32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int32array: function(arr){ + write('int32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float32array: function(arr){ + write('float32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float64array: function(arr){ + write('float64array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _arraybuffer: function(arr){ + write('arraybuffer:'); + return this.dispatch(new Uint8Array(arr)); + }, + _url: function(url) { + return write('url:' + url.toString(), 'utf8'); + }, + _map: function(map) { + write('map:'); + var arr = Array.from(map); + return this._array(arr, options.unorderedSets !== false); + }, + _set: function(set) { + write('set:'); + var arr = Array.from(set); + return this._array(arr, options.unorderedSets !== false); + }, + _file: function(file) { + write('file:'); + return this.dispatch([file.name, file.size, file.type, file.lastModfied]); + }, + _blob: function() { + if (options.ignoreUnknown) { + return write('[blob]'); + } + + throw Error('Hashing Blob objects is currently not supported\n' + + '(see https://github.com/puleos/object-hash/issues/26)\n' + + 'Use "options.replacer" or "options.ignoreUnknown"\n'); + }, + _domwindow: function() { return write('domwindow'); }, + _bigint: function(number){ + return write('bigint:' + number.toString()); + }, + /* Node.js standard native objects */ + _process: function() { return write('process'); }, + _timer: function() { return write('timer'); }, + _pipe: function() { return write('pipe'); }, + _tcp: function() { return write('tcp'); }, + _udp: function() { return write('udp'); }, + _tty: function() { return write('tty'); }, + _statwatcher: function() { return write('statwatcher'); }, + _securecontext: function() { return write('securecontext'); }, + _connection: function() { return write('connection'); }, + _zlib: function() { return write('zlib'); }, + _context: function() { return write('context'); }, + _nodescript: function() { return write('nodescript'); }, + _httpparser: function() { return write('httpparser'); }, + _dataview: function() { return write('dataview'); }, + _signal: function() { return write('signal'); }, + _fsevent: function() { return write('fsevent'); }, + _tlswrap: function() { return write('tlswrap'); }, + }; +} + +// Mini-implementation of stream.PassThrough +// We are far from having need for the full implementation, and we can +// make assumptions like "many writes, then only one final read" +// and we can ignore encoding specifics +function PassThrough() { + return { + buf: '', + + write: function(b) { + this.buf += b; + }, + + end: function(b) { + this.buf += b; + }, + + read: function() { + return this.buf; + } + }; +} diff --git a/node_modules/object-hash/package.json b/node_modules/object-hash/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a72557f638b41c66bb77a7903c11ede3685db54b --- /dev/null +++ b/node_modules/object-hash/package.json @@ -0,0 +1,53 @@ +{ + "name": "object-hash", + "version": "3.0.0", + "description": "Generate hashes from javascript objects in node and the browser.", + "homepage": "https://github.com/puleos/object-hash", + "repository": { + "type": "git", + "url": "https://github.com/puleos/object-hash" + }, + "keywords": [ + "object", + "hash", + "sha1", + "md5" + ], + "bugs": { + "url": "https://github.com/puleos/object-hash/issues" + }, + "scripts": { + "test": "node ./node_modules/.bin/mocha test", + "prepublish": "gulp dist" + }, + "author": "Scott Puleo ", + "files": [ + "index.js", + "dist/object_hash.js" + ], + "license": "MIT", + "devDependencies": { + "browserify": "^16.2.3", + "gulp": "^4.0.0", + "gulp-browserify": "^0.5.1", + "gulp-coveralls": "^0.1.4", + "gulp-exec": "^3.0.1", + "gulp-istanbul": "^1.1.3", + "gulp-jshint": "^2.0.0", + "gulp-mocha": "^5.0.0", + "gulp-rename": "^1.2.0", + "gulp-replace": "^1.0.0", + "gulp-uglify": "^3.0.0", + "jshint": "^2.8.0", + "jshint-stylish": "^2.1.0", + "karma": "^4.2.0", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "mocha": "^6.2.0" + }, + "engines": { + "node": ">= 6" + }, + "main": "./index.js", + "browser": "./dist/object_hash.js" +} diff --git a/node_modules/object-hash/readme.markdown b/node_modules/object-hash/readme.markdown new file mode 100644 index 0000000000000000000000000000000000000000..c507cf8cec1968ccefa9181a94444795dda43e2d --- /dev/null +++ b/node_modules/object-hash/readme.markdown @@ -0,0 +1,198 @@ +# object-hash + +Generate hashes from objects and values in node and the browser. Uses node.js +crypto module for hashing. Supports SHA1 and many others (depending on the platform) +as well as custom streams (e.g. CRC32). + +[![NPM](https://nodei.co/npm/object-hash.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/object-hash) + +[![Travis CI](https://secure.travis-ci.org/puleos/object-hash.png?branch=master)](https://secure.travis-ci.org/puleos/object-hash?branch=master) +[![Coverage Status](https://coveralls.io/repos/puleos/object-hash/badge.svg?branch=master&service=github)](https://coveralls.io/github/puleos/object-hash?branch=master) + +* Hash values of any type. +* Supports a keys only option for grouping similar objects with different values. + +```js +var hash = require('object-hash'); + +hash({foo: 'bar'}) // => '67b69634f9880a282c14a0f0cb7ba20cf5d677e9' +hash([1, 2, 2.718, 3.14159]) // => '136b9b88375971dff9f1af09d7356e3e04281951' +``` + +## Versioning Disclaimer + +Starting with version `1.1.8` (released April 2017), new versions will consider +the exact returned hash part of the API contract, i.e. changes that will affect +hash values will be considered `semver-major`. Previous versions may violate +that expectation. + +For more information, see [this discussion](https://github.com/puleos/object-hash/issues/30). + +## hash(value, options) + +Generate a hash from any object or type. Defaults to sha1 with hex encoding. + +* `algorithm` hash algo to be used: 'sha1', 'md5', 'passthrough'. default: sha1 + * This supports the algorithms returned by `crypto.getHashes()`. Note that the default of SHA-1 is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. + * This also supports the `passthrough` algorith, which will return the information that would otherwise have been hashed. +* `excludeValues` {true|false} hash object keys, values ignored. default: false +* `encoding` hash encoding, supports 'buffer', 'hex', 'binary', 'base64'. default: hex +* `ignoreUnknown` {true|*false} ignore unknown object types. default: false +* `replacer` optional function that replaces values before hashing. default: accept all values +* `respectFunctionProperties` {true|false} Whether properties on functions are considered when hashing. default: true +* `respectFunctionNames` {true|false} consider `name` property of functions for hashing. default: true +* `respectType` {true|false} Whether special type attributes (`.prototype`, `.__proto__`, `.constructor`) + are hashed. default: true +* `unorderedArrays` {true|false} Sort all arrays before hashing. Note that this affects *all* collections, + i.e. including typed arrays, Sets, Maps, etc. default: false +* `unorderedSets` {true|false} Sort `Set` and `Map` instances before hashing, i.e. make + `hash(new Set([1, 2])) == hash(new Set([2, 1]))` return `true`. default: true +* `unorderedObjects` {true|false} Sort objects before hashing, i.e. make `hash({ x: 1, y: 2 }) === hash({ y: 2, x: 1 })`. default: true +* `excludeKeys` optional function for excluding specific key(s) from hashing, if true is returned then exclude from hash. default: include all keys + +## hash.sha1(value) + +Hash using the sha1 algorithm. + +Note that SHA-1 is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. + +*Sugar method, equivalent to* `hash(value, {algorithm: 'sha1'})` + +## hash.keys(value) + +Hash object keys using the sha1 algorithm, values ignored. + +*Sugar method, equivalent to* `hash(value, {excludeValues: true})` + +## hash.MD5(value) + +Hash using the md5 algorithm. + +Note that the MD5 algorithm is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. + +*Sugar method, equivalent to* `hash(value, {algorithm: 'md5'})` + +## hash.keysMD5(value) + +Hash object keys using the md5 algorithm, values ignored. + +Note that the MD5 algorithm is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. + +*Sugar method, equivalent to* `hash(value, {algorithm: 'md5', excludeValues: true})` + +## hash.writeToStream(value, [options,] stream) + +Write the information that would otherwise have been hashed to a stream, e.g.: + +```js +hash.writeToStream({foo: 'bar', a: 42}, {respectType: false}, process.stdout) +// => e.g. 'object:a:number:42foo:string:bar' +``` + +## Installation + +node: + +```js +npm install object-hash +``` + +browser: */dist/object_hash.js* + +```html + + + +``` + +## Example usage + +```js +var hash = require('object-hash'); + +var peter = { name: 'Peter', stapler: false, friends: ['Joanna', 'Michael', 'Samir'] }; +var michael = { name: 'Michael', stapler: false, friends: ['Peter', 'Samir'] }; +var bob = { name: 'Bob', stapler: true, friends: [] }; + +/*** + * sha1 hex encoding (default) + */ +hash(peter); +// 14fa461bf4b98155e82adc86532938553b4d33a9 +hash(michael); +// 4b2b30e27699979ce46714253bc2213010db039c +hash(bob); +// 38d96106bc8ef3d8bd369b99bb6972702c9826d5 + +/*** + * hash object keys, values ignored + */ +hash(peter, { excludeValues: true }); +// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c +hash(michael, { excludeValues: true }); +// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c +hash.keys(bob); +// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c + +/*** + * hash object, ignore specific key(s) + */ +hash(peter, { excludeKeys: function(key) { + if ( key === 'friends') { + return true; + } + return false; + } +}); +// 66b7d7e64871aa9fda1bdc8e88a28df797648d80 + +/*** + * md5 base64 encoding + */ +hash(peter, { algorithm: 'md5', encoding: 'base64' }); +// 6rkWaaDiG3NynWw4svGH7g== +hash(michael, { algorithm: 'md5', encoding: 'base64' }); +// djXaWpuWVJeOF8Sb6SFFNg== +hash(bob, { algorithm: 'md5', encoding: 'base64' }); +// lFzkw/IJ8/12jZI0rQeS3w== +``` + +## Legacy Browser Support + +IE <= 8 and Opera <= 11 support dropped in version 0.3.0. If you require +legacy browser support you must either use an ES5 shim or use version 0.2.5 +of this module. + +## Development + +```sh-session +git clone https://github.com/puleos/object-hash +``` + +## Node Docker Wrapper + +If you want to stand this up in a docker container, you should take at look +at the [![node-object-hash](https://github.com/bean5/node-object-hash)](https://github.com/bean5/node-object-hash) project. + +### gulp tasks + +* `gulp watch` (default) watch files, test and lint on change/add +* `gulp test` unit tests +* `gulp karma` browser unit tests +* `gulp lint` jshint +* `gulp dist` create browser version in /dist + +## License + +MIT + +## Changelog + +### v2.0.0 + +Only Node.js versions `>= 6.0.0` are being tested in CI now. +No other breaking changes were introduced. diff --git a/node_modules/object-inspect/.eslintrc b/node_modules/object-inspect/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..21f903923ef11aef5d6ca8ade40028520b82a37a --- /dev/null +++ b/node_modules/object-inspect/.eslintrc @@ -0,0 +1,53 @@ +{ + "root": true, + "extends": "@ljharb", + "rules": { + "complexity": 0, + "func-style": [2, "declaration"], + "indent": [2, 4], + "max-lines": 1, + "max-lines-per-function": 1, + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "no-param-reassign": 1, + "strict": 0, // TODO + }, + "overrides": [ + { + "files": ["test/**", "test-*", "example/**"], + "extends": "@ljharb/eslint-config/tests", + "rules": { + "id-length": 0, + }, + }, + { + "files": ["example/**"], + "rules": { + "no-console": 0, + }, + }, + { + "files": ["test/browser/**"], + "env": { + "browser": true, + }, + }, + { + "files": ["test/bigint*"], + "rules": { + "new-cap": [2, { "capIsNewExceptions": ["BigInt"] }], + }, + }, + { + "files": "index.js", + "globals": { + "HTMLElement": false, + }, + "rules": { + "no-use-before-define": 1, + }, + }, + ], +} diff --git a/node_modules/object-inspect/.github/FUNDING.yml b/node_modules/object-inspect/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..730276bd121df856ede4c51d6e7b63d071242487 --- /dev/null +++ b/node_modules/object-inspect/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/object-inspect +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/object-inspect/.nycrc b/node_modules/object-inspect/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..58a5db7834ad50f2f9a5814f49d98db106381316 --- /dev/null +++ b/node_modules/object-inspect/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "instrumentation": false, + "sourceMap": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "example", + "test", + "test-core-js.js" + ] +} diff --git a/node_modules/object-inspect/CHANGELOG.md b/node_modules/object-inspect/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..bdf9002747e971f342607364e8557fc8bd3e80ec --- /dev/null +++ b/node_modules/object-inspect/CHANGELOG.md @@ -0,0 +1,424 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.13.4](https://github.com/inspect-js/object-inspect/compare/v1.13.3...v1.13.4) - 2025-02-04 + +### Commits + +- [Fix] avoid being fooled by a `Symbol.toStringTag` [`fa5870d`](https://github.com/inspect-js/object-inspect/commit/fa5870da468a525d2f20193700f70752f506cbf7) +- [Tests] fix tests in node v6.0 - v6.4 [`2abfe1b`](https://github.com/inspect-js/object-inspect/commit/2abfe1bc3c69f9293c07c5cd65a9d7d87a628b84) +- [Dev Deps] update `es-value-fixtures`, `for-each`, `has-symbols` [`3edfb01`](https://github.com/inspect-js/object-inspect/commit/3edfb01cc8cce220fba0dfdfe2dc8bc955758cdd) + +## [v1.13.3](https://github.com/inspect-js/object-inspect/compare/v1.13.2...v1.13.3) - 2024-11-09 + +### Commits + +- [actions] split out node 10-20, and 20+ [`44395a8`](https://github.com/inspect-js/object-inspect/commit/44395a8fc1deda6718a5e125e86b9ffcaa1c7580) +- [Fix] `quoteStyle`: properly escape only the containing quotes [`5137f8f`](https://github.com/inspect-js/object-inspect/commit/5137f8f7bea69a7fc671bb683fd35f244f38fc52) +- [Refactor] clean up `quoteStyle` code [`450680c`](https://github.com/inspect-js/object-inspect/commit/450680cd50de4e689ee3b8e1d6db3a1bcf3fc18c) +- [Tests] add `quoteStyle` escaping tests [`e997c59`](https://github.com/inspect-js/object-inspect/commit/e997c595aeaea84fd98ca35d7e1c3b5ab3ae26e0) +- [Dev Deps] update `auto-changelog`, `es-value-fixtures`, `tape` [`d5a469c`](https://github.com/inspect-js/object-inspect/commit/d5a469c99ec07ccaeafc36ac4b36a93285086d48) +- [Tests] replace `aud` with `npm audit` [`fb7815f`](https://github.com/inspect-js/object-inspect/commit/fb7815f9b72cae277a04f65bbb0543f85b88be62) +- [Dev Deps] update `mock-property` [`11c817b`](https://github.com/inspect-js/object-inspect/commit/11c817bf10392aa017755962ba6bc89d731359ee) + +## [v1.13.2](https://github.com/inspect-js/object-inspect/compare/v1.13.1...v1.13.2) - 2024-06-21 + +### Commits + +- [readme] update badges [`8a51e6b`](https://github.com/inspect-js/object-inspect/commit/8a51e6bedaf389ec40cc4659e9df53e8543d176e) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`ef05f58`](https://github.com/inspect-js/object-inspect/commit/ef05f58c9761a41416ab907299bf0fa79517014b) +- [Dev Deps] update `error-cause`, `has-tostringtag`, `tape` [`c0c6c26`](https://github.com/inspect-js/object-inspect/commit/c0c6c26c44cee6671f7c5d43d2b91d27c5c00d90) +- [Fix] Don't throw when `global` is not defined [`d4d0965`](https://github.com/inspect-js/object-inspect/commit/d4d096570f7dbd0e03266a96de11d05eb7b63e0f) +- [meta] add missing `engines.node` [`17a352a`](https://github.com/inspect-js/object-inspect/commit/17a352af6fe1ba6b70a19081674231eb1a50c940) +- [Dev Deps] update `globalthis` [`9c08884`](https://github.com/inspect-js/object-inspect/commit/9c08884aa662a149e2f11403f413927736b97da7) +- [Dev Deps] update `error-cause` [`6af352d`](https://github.com/inspect-js/object-inspect/commit/6af352d7c3929a4cc4c55768c27bf547a5e900f4) +- [Dev Deps] update `npmignore` [`94e617d`](https://github.com/inspect-js/object-inspect/commit/94e617d38831722562fa73dff4c895746861d267) +- [Dev Deps] update `mock-property` [`2ac24d7`](https://github.com/inspect-js/object-inspect/commit/2ac24d7e58cd388ad093c33249e413e05bbfd6c3) +- [Dev Deps] update `tape` [`46125e5`](https://github.com/inspect-js/object-inspect/commit/46125e58f1d1dcfb170ed3d1ea69da550ea8d77b) + +## [v1.13.1](https://github.com/inspect-js/object-inspect/compare/v1.13.0...v1.13.1) - 2023-10-19 + +### Commits + +- [Fix] in IE 8, global can !== window despite them being prototypes of each other [`30d0859`](https://github.com/inspect-js/object-inspect/commit/30d0859dc4606cf75c2410edcd5d5c6355f8d372) + +## [v1.13.0](https://github.com/inspect-js/object-inspect/compare/v1.12.3...v1.13.0) - 2023-10-14 + +### Commits + +- [New] add special handling for the global object [`431bab2`](https://github.com/inspect-js/object-inspect/commit/431bab21a490ee51d35395966a504501e8c685da) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`fd4f619`](https://github.com/inspect-js/object-inspect/commit/fd4f6193562b4b0e95dcf5c0201b4e8cbbc4f58d) +- [Dev Deps] update `mock-property`, `tape` [`b453f6c`](https://github.com/inspect-js/object-inspect/commit/b453f6ceeebf8a1b738a1029754092e0367a4134) +- [Dev Deps] update `error-cause` [`e8ffc57`](https://github.com/inspect-js/object-inspect/commit/e8ffc577d73b92bb6a4b00c44f14e3319e374888) +- [Dev Deps] update `tape` [`054b8b9`](https://github.com/inspect-js/object-inspect/commit/054b8b9b98633284cf989e582450ebfbbe53503c) +- [Dev Deps] temporarily remove `aud` due to breaking change in transitive deps [`2476845`](https://github.com/inspect-js/object-inspect/commit/2476845e0678dd290c541c81cd3dec8420782c52) +- [Dev Deps] pin `glob`, since v10.3.8+ requires a broken `jackspeak` [`383fa5e`](https://github.com/inspect-js/object-inspect/commit/383fa5eebc0afd705cc778a4b49d8e26452e49a8) +- [Dev Deps] pin `jackspeak` since 2.1.2+ depends on npm aliases, which kill the install process in npm < 6 [`68c244c`](https://github.com/inspect-js/object-inspect/commit/68c244c5174cdd877e5dcb8ee90aa3f44b2f25be) + +## [v1.12.3](https://github.com/inspect-js/object-inspect/compare/v1.12.2...v1.12.3) - 2023-01-12 + +### Commits + +- [Fix] in eg FF 24, collections lack forEach [`75fc226`](https://github.com/inspect-js/object-inspect/commit/75fc22673c82d45f28322b1946bb0eb41b672b7f) +- [actions] update rebase action to use reusable workflow [`250a277`](https://github.com/inspect-js/object-inspect/commit/250a277a095e9dacc029ab8454dcfc15de549dcd) +- [Dev Deps] update `aud`, `es-value-fixtures`, `tape` [`66a19b3`](https://github.com/inspect-js/object-inspect/commit/66a19b3209ccc3c5ef4b34c3cb0160e65d1ce9d5) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `error-cause` [`c43d332`](https://github.com/inspect-js/object-inspect/commit/c43d3324b48384a16fd3dc444e5fc589d785bef3) +- [Tests] add `@pkgjs/support` to `postlint` [`e2618d2`](https://github.com/inspect-js/object-inspect/commit/e2618d22a7a3fa361b6629b53c1752fddc9c4d80) + +## [v1.12.2](https://github.com/inspect-js/object-inspect/compare/v1.12.1...v1.12.2) - 2022-05-26 + +### Commits + +- [Fix] use `util.inspect` for a custom inspection symbol method [`e243bf2`](https://github.com/inspect-js/object-inspect/commit/e243bf2eda6c4403ac6f1146fddb14d12e9646c1) +- [meta] add support info [`ca20ba3`](https://github.com/inspect-js/object-inspect/commit/ca20ba35713c17068ca912a86c542f5e8acb656c) +- [Fix] ignore `cause` in node v16.9 and v16.10 where it has a bug [`86aa553`](https://github.com/inspect-js/object-inspect/commit/86aa553a4a455562c2c56f1540f0bf857b9d314b) + +## [v1.12.1](https://github.com/inspect-js/object-inspect/compare/v1.12.0...v1.12.1) - 2022-05-21 + +### Commits + +- [Tests] use `mock-property` [`4ec8893`](https://github.com/inspect-js/object-inspect/commit/4ec8893ea9bfd28065ca3638cf6762424bf44352) +- [meta] use `npmignore` to autogenerate an npmignore file [`07f868c`](https://github.com/inspect-js/object-inspect/commit/07f868c10bd25a9d18686528339bb749c211fc9a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`b05244b`](https://github.com/inspect-js/object-inspect/commit/b05244b4f331e00c43b3151bc498041be77ccc91) +- [Dev Deps] update `@ljharb/eslint-config`, `error-cause`, `es-value-fixtures`, `functions-have-names`, `tape` [`d037398`](https://github.com/inspect-js/object-inspect/commit/d037398dcc5d531532e4c19c4a711ed677f579c1) +- [Fix] properly handle callable regexes in older engines [`848fe48`](https://github.com/inspect-js/object-inspect/commit/848fe48bd6dd0064ba781ee6f3c5e54a94144c37) + +## [v1.12.0](https://github.com/inspect-js/object-inspect/compare/v1.11.1...v1.12.0) - 2021-12-18 + +### Commits + +- [New] add `numericSeparator` boolean option [`2d2d537`](https://github.com/inspect-js/object-inspect/commit/2d2d537f5359a4300ce1c10241369f8024f89e11) +- [Robustness] cache more prototype methods [`191533d`](https://github.com/inspect-js/object-inspect/commit/191533da8aec98a05eadd73a5a6e979c9c8653e8) +- [New] ensure an Error’s `cause` is displayed [`53bc2ce`](https://github.com/inspect-js/object-inspect/commit/53bc2cee4e5a9cc4986f3cafa22c0685f340715e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`bc164b6`](https://github.com/inspect-js/object-inspect/commit/bc164b6e2e7d36b263970f16f54de63048b84a36) +- [Robustness] cache `RegExp.prototype.test` [`a314ab8`](https://github.com/inspect-js/object-inspect/commit/a314ab8271b905cbabc594c82914d2485a8daf12) +- [meta] fix auto-changelog settings [`5ed0983`](https://github.com/inspect-js/object-inspect/commit/5ed0983be72f73e32e2559997517a95525c7e20d) + +## [v1.11.1](https://github.com/inspect-js/object-inspect/compare/v1.11.0...v1.11.1) - 2021-12-05 + +### Commits + +- [meta] add `auto-changelog` [`7dbdd22`](https://github.com/inspect-js/object-inspect/commit/7dbdd228401d6025d8b7391476d88aee9ea9bbdf) +- [actions] reuse common workflows [`c8823bc`](https://github.com/inspect-js/object-inspect/commit/c8823bc0a8790729680709d45fb6e652432e91aa) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`7532b12`](https://github.com/inspect-js/object-inspect/commit/7532b120598307497b712890f75af8056f6d37a6) +- [Refactor] use `has-tostringtag` to behave correctly in the presence of symbol shams [`94abb5d`](https://github.com/inspect-js/object-inspect/commit/94abb5d4e745bf33253942dea86b3e538d2ff6c6) +- [actions] update codecov uploader [`5ed5102`](https://github.com/inspect-js/object-inspect/commit/5ed51025267a00e53b1341357315490ac4eb0874) +- [Dev Deps] update `eslint`, `tape` [`37b2ad2`](https://github.com/inspect-js/object-inspect/commit/37b2ad26c08d94bfd01d5d07069a0b28ef4e2ad7) +- [meta] add `sideEffects` flag [`d341f90`](https://github.com/inspect-js/object-inspect/commit/d341f905ef8bffa6a694cda6ddc5ba343532cd4f) + +## [v1.11.0](https://github.com/inspect-js/object-inspect/compare/v1.10.3...v1.11.0) - 2021-07-12 + +### Commits + +- [New] `customInspect`: add `symbol` option, to mimic modern util.inspect behavior [`e973a6e`](https://github.com/inspect-js/object-inspect/commit/e973a6e21f8140c5837cf25e9d89bdde88dc3120) +- [Dev Deps] update `eslint` [`05f1cb3`](https://github.com/inspect-js/object-inspect/commit/05f1cb3cbcfe1f238e8b51cf9bc294305b7ed793) + +## [v1.10.3](https://github.com/inspect-js/object-inspect/compare/v1.10.2...v1.10.3) - 2021-05-07 + +### Commits + +- [Fix] handle core-js Symbol shams [`4acfc2c`](https://github.com/inspect-js/object-inspect/commit/4acfc2c4b503498759120eb517abad6d51c9c5d6) +- [readme] update badges [`95c323a`](https://github.com/inspect-js/object-inspect/commit/95c323ad909d6cbabb95dd6015c190ba6db9c1f2) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud` [`cb38f48`](https://github.com/inspect-js/object-inspect/commit/cb38f485de6ec7a95109b5a9bbd0a1deba2f6611) + +## [v1.10.2](https://github.com/inspect-js/object-inspect/compare/v1.10.1...v1.10.2) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed Symbol [`87f12d6`](https://github.com/inspect-js/object-inspect/commit/87f12d6e69ce530be04659c81a4cd502943acac5) + +## [v1.10.1](https://github.com/inspect-js/object-inspect/compare/v1.10.0...v1.10.1) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed bigint [`d5ca829`](https://github.com/inspect-js/object-inspect/commit/d5ca8298b6d2e5c7b9334a5b21b96ed95d225c91) + +## [v1.10.0](https://github.com/inspect-js/object-inspect/compare/v1.9.0...v1.10.0) - 2021-04-17 + +### Commits + +- [Tests] increase coverage [`d8abb8a`](https://github.com/inspect-js/object-inspect/commit/d8abb8a62c2f084919df994a433b346e0d87a227) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`4bfec2e`](https://github.com/inspect-js/object-inspect/commit/4bfec2e30aaef6ddef6cbb1448306f9f8b9520b7) +- [New] respect `Symbol.toStringTag` on objects [`799b58f`](https://github.com/inspect-js/object-inspect/commit/799b58f536a45e4484633a8e9daeb0330835f175) +- [Fix] do not allow Symbol.toStringTag to masquerade as builtins [`d6c5b37`](https://github.com/inspect-js/object-inspect/commit/d6c5b37d7e94427796b82432fb0c8964f033a6ab) +- [New] add `WeakRef` support [`b6d898e`](https://github.com/inspect-js/object-inspect/commit/b6d898ee21868c780a7ee66b28532b5b34ed7f09) +- [meta] do not publish github action workflow files [`918cdfc`](https://github.com/inspect-js/object-inspect/commit/918cdfc4b6fe83f559ff6ef04fe66201e3ff5cbd) +- [meta] create `FUNDING.yml` [`0bb5fc5`](https://github.com/inspect-js/object-inspect/commit/0bb5fc516dbcd2cd728bd89cee0b580acc5ce301) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`22c8dc0`](https://github.com/inspect-js/object-inspect/commit/22c8dc0cac113d70f4781e49a950070923a671be) +- [meta] use `prepublishOnly` script for npm 7+ [`e52ee09`](https://github.com/inspect-js/object-inspect/commit/e52ee09e8050b8dbac94ef57f786675567728223) +- [Dev Deps] update `eslint` [`7c4e6fd`](https://github.com/inspect-js/object-inspect/commit/7c4e6fdedcd27cc980e13c9ad834d05a96f3d40c) + +## [v1.9.0](https://github.com/inspect-js/object-inspect/compare/v1.8.0...v1.9.0) - 2020-11-30 + +### Commits + +- [Tests] migrate tests to Github Actions [`d262251`](https://github.com/inspect-js/object-inspect/commit/d262251e13e16d3490b5473672f6b6d6ff86675d) +- [New] add enumerable own Symbols to plain object output [`ee60c03`](https://github.com/inspect-js/object-inspect/commit/ee60c033088cff9d33baa71e59a362a541b48284) +- [Tests] add passing tests [`01ac3e4`](https://github.com/inspect-js/object-inspect/commit/01ac3e4b5a30f97875a63dc9b1416b3bd626afc9) +- [actions] add "Require Allow Edits" action [`c2d7746`](https://github.com/inspect-js/object-inspect/commit/c2d774680cde4ca4af332d84d4121b26f798ba9e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `core-js` [`70058de`](https://github.com/inspect-js/object-inspect/commit/70058de1579fc54d1d15ed6c2dbe246637ce70ff) +- [Fix] hex characters in strings should be uppercased, to match node `assert` [`6ab8faa`](https://github.com/inspect-js/object-inspect/commit/6ab8faaa0abc08fe7a8e2afd8b39c6f1f0e00113) +- [Tests] run `nyc` on all tests [`4c47372`](https://github.com/inspect-js/object-inspect/commit/4c473727879ddc8e28b599202551ddaaf07b6210) +- [Tests] node 0.8 has an unpredictable property order; fix `groups` test by removing property [`f192069`](https://github.com/inspect-js/object-inspect/commit/f192069a978a3b60e6f0e0d45ac7df260ab9a778) +- [New] add enumerable properties to Function inspect result, per node’s `assert` [`fd38e1b`](https://github.com/inspect-js/object-inspect/commit/fd38e1bc3e2a1dc82091ce3e021917462eee64fc) +- [Tests] fix tests for node < 10, due to regex match `groups` [`2ac6462`](https://github.com/inspect-js/object-inspect/commit/2ac6462cc4f72eaa0b63a8cfee9aabe3008b2330) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`44b59e2`](https://github.com/inspect-js/object-inspect/commit/44b59e2676a7f825ef530dfd19dafb599e3b9456) +- [Robustness] cache `Symbol.prototype.toString` [`f3c2074`](https://github.com/inspect-js/object-inspect/commit/f3c2074d8f32faf8292587c07c9678ea931703dd) +- [Dev Deps] update `eslint` [`9411294`](https://github.com/inspect-js/object-inspect/commit/94112944b9245e3302e25453277876402d207e7f) +- [meta] `require-allow-edits` no longer requires an explicit github token [`36c0220`](https://github.com/inspect-js/object-inspect/commit/36c02205de3c2b0e84d53777c5c9fd54a36c48ab) +- [actions] update rebase checkout action to v2 [`55a39a6`](https://github.com/inspect-js/object-inspect/commit/55a39a64e944f19c6a7d8efddf3df27700f20d14) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`f59fd3c`](https://github.com/inspect-js/object-inspect/commit/f59fd3cf406c3a7c7ece140904a80bbc6bacfcca) +- [Dev Deps] update `eslint` [`a492bec`](https://github.com/inspect-js/object-inspect/commit/a492becec644b0155c9c4bc1caf6f9fac11fb2c7) + +## [v1.8.0](https://github.com/inspect-js/object-inspect/compare/v1.7.0...v1.8.0) - 2020-06-18 + +### Fixed + +- [New] add `indent` option [`#27`](https://github.com/inspect-js/object-inspect/issues/27) + +### Commits + +- [Tests] add codecov [`4324cbb`](https://github.com/inspect-js/object-inspect/commit/4324cbb1a2bd7710822a4151ff373570db22453e) +- [New] add `maxStringLength` option [`b3995cb`](https://github.com/inspect-js/object-inspect/commit/b3995cb71e15b5ee127a3094c43994df9d973502) +- [New] add `customInspect` option, to disable custom inspect methods [`28b9179`](https://github.com/inspect-js/object-inspect/commit/28b9179ee802bb3b90810100c11637db90c2fb6d) +- [Tests] add Date and RegExp tests [`3b28eca`](https://github.com/inspect-js/object-inspect/commit/3b28eca57b0367aeadffac604ea09e8bdae7d97b) +- [actions] add automatic rebasing / merge commit blocking [`0d9c6c0`](https://github.com/inspect-js/object-inspect/commit/0d9c6c044e83475ff0bfffb9d35b149834c83a2e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape`; add `aud` [`7c204f2`](https://github.com/inspect-js/object-inspect/commit/7c204f22b9e41bc97147f4d32d4cb045b17769a6) +- [readme] fix repo URLs, remove testling [`34ca9a0`](https://github.com/inspect-js/object-inspect/commit/34ca9a0dabfe75bd311f806a326fadad029909a3) +- [Fix] when truncating a deep array, note it as `[Array]` instead of just `[Object]` [`f74c82d`](https://github.com/inspect-js/object-inspect/commit/f74c82dd0b35386445510deb250f34c41be3ec0e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`1a8a5ea`](https://github.com/inspect-js/object-inspect/commit/1a8a5ea069ea2bee89d77caedad83ffa23d35711) +- [Fix] do not be fooled by a function’s own `toString` method [`7cb5c65`](https://github.com/inspect-js/object-inspect/commit/7cb5c657a976f94715c19c10556a30f15bb7d5d7) +- [patch] indicate explicitly that anon functions are anonymous, to match node [`81ebdd4`](https://github.com/inspect-js/object-inspect/commit/81ebdd4215005144074bbdff3f6bafa01407910a) +- [Dev Deps] loosen the `core-js` dep [`e7472e8`](https://github.com/inspect-js/object-inspect/commit/e7472e8e242117670560bd995830c2a4d12080f5) +- [Dev Deps] update `tape` [`699827e`](https://github.com/inspect-js/object-inspect/commit/699827e6b37258b5203c33c78c009bf4b0e6a66d) +- [meta] add `safe-publish-latest` [`c5d2868`](https://github.com/inspect-js/object-inspect/commit/c5d2868d6eb33c472f37a20f89ceef2787046088) +- [Dev Deps] update `@ljharb/eslint-config` [`9199501`](https://github.com/inspect-js/object-inspect/commit/919950195d486114ccebacbdf9d74d7f382693b0) + +## [v1.7.0](https://github.com/inspect-js/object-inspect/compare/v1.6.0...v1.7.0) - 2019-11-10 + +### Commits + +- [Tests] use shared travis-ci configs [`19899ed`](https://github.com/inspect-js/object-inspect/commit/19899edbf31f4f8809acf745ce34ad1ce1bfa63b) +- [Tests] add linting [`a00f057`](https://github.com/inspect-js/object-inspect/commit/a00f057d917f66ea26dd37769c6b810ec4af97e8) +- [Tests] lint last file [`2698047`](https://github.com/inspect-js/object-inspect/commit/2698047b58af1e2e88061598ef37a75f228dddf6) +- [Tests] up to `node` `v12.7`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`589e87a`](https://github.com/inspect-js/object-inspect/commit/589e87a99cadcff4b600e6a303418e9d922836e8) +- [New] add support for `WeakMap` and `WeakSet` [`3ddb3e4`](https://github.com/inspect-js/object-inspect/commit/3ddb3e4e0c8287130c61a12e0ed9c104b1549306) +- [meta] clean up license so github can detect it properly [`27527bb`](https://github.com/inspect-js/object-inspect/commit/27527bb801520c9610c68cc3b55d6f20a2bee56d) +- [Tests] cover `util.inspect.custom` [`36d47b9`](https://github.com/inspect-js/object-inspect/commit/36d47b9c59056a57ef2f1491602c726359561800) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape` [`b614eaa`](https://github.com/inspect-js/object-inspect/commit/b614eaac901da0e5c69151f534671f990a94cace) +- [Tests] fix coverage thresholds [`7b7b176`](https://github.com/inspect-js/object-inspect/commit/7b7b176e15f8bd6e8b2f261ff5a493c2fe78d9c2) +- [Tests] bigint tests now can run on unflagged node [`063af31`](https://github.com/inspect-js/object-inspect/commit/063af31ce9cd13c202e3b67c07ba06dc9b7c0f81) +- [Refactor] add early bailout to `isMap` and `isSet` checks [`fc51047`](https://github.com/inspect-js/object-inspect/commit/fc5104714a3671d37e225813db79470d6335683b) +- [meta] add `funding` field [`7f9953a`](https://github.com/inspect-js/object-inspect/commit/7f9953a113eec7b064a6393cf9f90ba15f1d131b) +- [Tests] Fix invalid strict-mode syntax with hexadecimal [`a8b5425`](https://github.com/inspect-js/object-inspect/commit/a8b542503b4af1599a275209a1a99f5fdedb1ead) +- [Dev Deps] update `@ljharb/eslint-config` [`98df157`](https://github.com/inspect-js/object-inspect/commit/98df1577314d9188a3fc3f17fdcf2fba697ae1bd) +- add copyright to LICENSE [`bb69fd0`](https://github.com/inspect-js/object-inspect/commit/bb69fd017a062d299e44da1f9b2c7dcd67f621e6) +- [Tests] use `npx aud` in `posttest` [`4838353`](https://github.com/inspect-js/object-inspect/commit/4838353593974cf7f905b9ef04c03c094f0cdbe2) +- [Tests] move `0.6` to allowed failures, because it won‘t build on travis [`1bff32a`](https://github.com/inspect-js/object-inspect/commit/1bff32aa52e8aea687f0856b28ba754b3e43ebf7) + +## [v1.6.0](https://github.com/inspect-js/object-inspect/compare/v1.5.0...v1.6.0) - 2018-05-02 + +### Commits + +- [New] add support for boxed BigInt primitives [`356c66a`](https://github.com/inspect-js/object-inspect/commit/356c66a410e7aece7162c8319880a5ef647beaa9) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`c77b65b`](https://github.com/inspect-js/object-inspect/commit/c77b65bba593811b906b9ec57561c5cba92e2db3) +- [New] Add support for upcoming `BigInt` [`1ac548e`](https://github.com/inspect-js/object-inspect/commit/1ac548e4b27e26466c28c9a5e63e5d4e0591c31f) +- [Tests] run bigint tests in CI with --harmony-bigint flag [`d31b738`](https://github.com/inspect-js/object-inspect/commit/d31b73831880254b5c6cf5691cda9a149fbc5f04) +- [Dev Deps] update `core-js`, `tape` [`ff9eff6`](https://github.com/inspect-js/object-inspect/commit/ff9eff67113341ee1aaf80c1c22d683f43bfbccf) +- [Docs] fix example to use `safer-buffer` [`48cae12`](https://github.com/inspect-js/object-inspect/commit/48cae12a73ec6cacc955175bc56bbe6aee6a211f) + +## [v1.5.0](https://github.com/inspect-js/object-inspect/compare/v1.4.1...v1.5.0) - 2017-12-25 + +### Commits + +- [New] add `quoteStyle` option [`f5a72d2`](https://github.com/inspect-js/object-inspect/commit/f5a72d26edb3959b048f74c056ca7100a6b091e4) +- [Tests] add more test coverage [`30ebe4e`](https://github.com/inspect-js/object-inspect/commit/30ebe4e1fa943b99ecbb85be7614256d536e2759) +- [Tests] require 0.6 to pass [`99a008c`](https://github.com/inspect-js/object-inspect/commit/99a008ccace189a60fd7da18bf00e32c9572b980) + +## [v1.4.1](https://github.com/inspect-js/object-inspect/compare/v1.4.0...v1.4.1) - 2017-12-19 + +### Commits + +- [Tests] up to `node` `v9.3`, `v8.9`, `v6.12` [`6674476`](https://github.com/inspect-js/object-inspect/commit/6674476cc56acaac1bde96c84fed5ef631911906) +- [Fix] `inspect(Object(-0))` should be “Object(-0)”, not “Object(0)” [`d0a031f`](https://github.com/inspect-js/object-inspect/commit/d0a031f1cbb3024ee9982bfe364dd18a7e4d1bd3) + +## [v1.4.0](https://github.com/inspect-js/object-inspect/compare/v1.3.0...v1.4.0) - 2017-10-24 + +### Commits + +- [Tests] add `npm run coverage` [`3b48fb2`](https://github.com/inspect-js/object-inspect/commit/3b48fb25db037235eeb808f0b2830aad7aa36f70) +- [Tests] remove commented-out osx builds [`71e24db`](https://github.com/inspect-js/object-inspect/commit/71e24db8ad6ee3b9b381c5300b0475f2ba595a73) +- [New] add support for `util.inspect.custom`, in node only. [`20cca77`](https://github.com/inspect-js/object-inspect/commit/20cca7762d7e17f15b21a90793dff84acce155df) +- [Tests] up to `node` `v8.6`; use `nvm install-latest-npm` to ensure new npm doesn’t break old node [`252952d`](https://github.com/inspect-js/object-inspect/commit/252952d230d8065851dd3d4d5fe8398aae068529) +- [Tests] up to `node` `v8.8` [`4aa868d`](https://github.com/inspect-js/object-inspect/commit/4aa868d3a62914091d489dd6ec6eed194ee67cd3) +- [Dev Deps] update `core-js`, `tape` [`59483d1`](https://github.com/inspect-js/object-inspect/commit/59483d1df418f852f51fa0db7b24aa6b0209a27a) + +## [v1.3.0](https://github.com/inspect-js/object-inspect/compare/v1.2.2...v1.3.0) - 2017-07-31 + +### Fixed + +- [Fix] Map/Set: work around core-js bug < v2.5.0 [`#9`](https://github.com/inspect-js/object-inspect/issues/9) + +### Commits + +- [New] add support for arrays with additional object keys [`0d19937`](https://github.com/inspect-js/object-inspect/commit/0d199374ee37959e51539616666f420ccb29acb9) +- [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`; fix new npm breaking on older nodes [`e24784a`](https://github.com/inspect-js/object-inspect/commit/e24784a90c49117787157a12a63897c49cf89bbb) +- Only apps should have lockfiles [`c6faebc`](https://github.com/inspect-js/object-inspect/commit/c6faebcb2ee486a889a4a1c4d78c0776c7576185) +- [Dev Deps] update `tape` [`7345a0a`](https://github.com/inspect-js/object-inspect/commit/7345a0aeba7e91b888a079c10004d17696a7f586) + +## [v1.2.2](https://github.com/inspect-js/object-inspect/compare/v1.2.1...v1.2.2) - 2017-03-24 + +### Commits + +- [Tests] up to `node` `v7.7`, `v6.10`, `v4.8`; improve test matrix [`a2ddc15`](https://github.com/inspect-js/object-inspect/commit/a2ddc15a1f2c65af18076eea1c0eb9cbceb478a0) +- [Tests] up to `node` `v7.0`, `v6.9`, `v5.12`, `v4.6`, `io.js` `v3.3`; improve test matrix [`a48949f`](https://github.com/inspect-js/object-inspect/commit/a48949f6b574b2d4d2298109d8e8d0eb3e7a83e7) +- [Performance] check for primitive types as early as possible. [`3b8092a`](https://github.com/inspect-js/object-inspect/commit/3b8092a2a4deffd0575f94334f00194e2d48dad3) +- [Refactor] remove unneeded `else`s. [`7255034`](https://github.com/inspect-js/object-inspect/commit/725503402e08de4f96f6bf2d8edef44ac36f26b6) +- [Refactor] avoid recreating `lowbyte` function every time. [`81edd34`](https://github.com/inspect-js/object-inspect/commit/81edd3475bd15bdd18e84de7472033dcf5004aaa) +- [Fix] differentiate -0 from 0 [`521d345`](https://github.com/inspect-js/object-inspect/commit/521d3456b009da7bf1c5785c8a9df5a9f8718264) +- [Refactor] move object key gathering into separate function [`aca6265`](https://github.com/inspect-js/object-inspect/commit/aca626536eaeef697196c6e9db3e90e7e0355b6a) +- [Refactor] consolidate wrapping logic for boxed primitives into a function. [`4e440cd`](https://github.com/inspect-js/object-inspect/commit/4e440cd9065df04802a2a1dead03f48c353ca301) +- [Robustness] use `typeof` instead of comparing to literal `undefined` [`5ca6f60`](https://github.com/inspect-js/object-inspect/commit/5ca6f601937506daff8ed2fcf686363b55807b69) +- [Refactor] consolidate Map/Set notations. [`4e576e5`](https://github.com/inspect-js/object-inspect/commit/4e576e5d7ed2f9ec3fb7f37a0d16732eb10758a9) +- [Tests] ensure that this function remains anonymous, despite ES6 name inference. [`7540ae5`](https://github.com/inspect-js/object-inspect/commit/7540ae591278756db614fa4def55ca413150e1a3) +- [Refactor] explicitly coerce Error objects to strings. [`7f4ca84`](https://github.com/inspect-js/object-inspect/commit/7f4ca8424ee8dc2c0ca5a422d94f7fac40327261) +- [Refactor] split up `var` declarations for debuggability [`6f2c11e`](https://github.com/inspect-js/object-inspect/commit/6f2c11e6a85418586a00292dcec5e97683f89bc3) +- [Robustness] cache `Object.prototype.toString` [`df44a20`](https://github.com/inspect-js/object-inspect/commit/df44a20adfccf31529d60d1df2079bfc3c836e27) +- [Dev Deps] update `tape` [`3ec714e`](https://github.com/inspect-js/object-inspect/commit/3ec714eba57bc3f58a6eb4fca1376f49e70d300a) +- [Dev Deps] update `tape` [`beb72d9`](https://github.com/inspect-js/object-inspect/commit/beb72d969653747d7cde300393c28755375329b0) + +## [v1.2.1](https://github.com/inspect-js/object-inspect/compare/v1.2.0...v1.2.1) - 2016-04-09 + +### Fixed + +- [Fix] fix Boolean `false` object inspection. [`#7`](https://github.com/substack/object-inspect/pull/7) + +## [v1.2.0](https://github.com/inspect-js/object-inspect/compare/v1.1.0...v1.2.0) - 2016-04-09 + +### Fixed + +- [New] add support for inspecting String/Number/Boolean objects. [`#6`](https://github.com/inspect-js/object-inspect/issues/6) + +### Commits + +- [Dev Deps] update `tape` [`742caa2`](https://github.com/inspect-js/object-inspect/commit/742caa262cf7af4c815d4821c8bd0129c1446432) + +## [v1.1.0](https://github.com/inspect-js/object-inspect/compare/1.0.2...v1.1.0) - 2015-12-14 + +### Merged + +- [New] add ES6 Map/Set support. [`#4`](https://github.com/inspect-js/object-inspect/pull/4) + +### Fixed + +- [New] add ES6 Map/Set support. [`#3`](https://github.com/inspect-js/object-inspect/issues/3) + +### Commits + +- Update `travis.yml` to test on bunches of `iojs` and `node` versions. [`4c1fd65`](https://github.com/inspect-js/object-inspect/commit/4c1fd65cc3bd95307e854d114b90478324287fd2) +- [Dev Deps] update `tape` [`88a907e`](https://github.com/inspect-js/object-inspect/commit/88a907e33afbe408e4b5d6e4e42a33143f88848c) + +## [1.0.2](https://github.com/inspect-js/object-inspect/compare/1.0.1...1.0.2) - 2015-08-07 + +### Commits + +- [Fix] Cache `Object.prototype.hasOwnProperty` in case it's deleted later. [`1d0075d`](https://github.com/inspect-js/object-inspect/commit/1d0075d3091dc82246feeb1f9871cb2b8ed227b3) +- [Dev Deps] Update `tape` [`ca8d5d7`](https://github.com/inspect-js/object-inspect/commit/ca8d5d75635ddbf76f944e628267581e04958457) +- gitignore node_modules since this is a reusable modules. [`ed41407`](https://github.com/inspect-js/object-inspect/commit/ed41407811743ca530cdeb28f982beb96026af82) + +## [1.0.1](https://github.com/inspect-js/object-inspect/compare/1.0.0...1.0.1) - 2015-07-19 + +### Commits + +- Make `inspect` work with symbol primitives and objects, including in node 0.11 and 0.12. [`ddf1b94`](https://github.com/inspect-js/object-inspect/commit/ddf1b94475ab951f1e3bccdc0a48e9073cfbfef4) +- bump tape [`103d674`](https://github.com/inspect-js/object-inspect/commit/103d67496b504bdcfdd765d303a773f87ec106e2) +- use newer travis config [`d497276`](https://github.com/inspect-js/object-inspect/commit/d497276c1da14234bb5098a59cf20de75fbc316a) + +## [1.0.0](https://github.com/inspect-js/object-inspect/compare/0.4.0...1.0.0) - 2014-08-05 + +### Commits + +- error inspect works properly [`260a22d`](https://github.com/inspect-js/object-inspect/commit/260a22d134d3a8a482c67d52091c6040c34f4299) +- seen coverage [`57269e8`](https://github.com/inspect-js/object-inspect/commit/57269e8baa992a7439047f47325111fdcbcb8417) +- htmlelement instance coverage [`397ffe1`](https://github.com/inspect-js/object-inspect/commit/397ffe10a1980350868043ef9de65686d438979f) +- more element coverage [`6905cc2`](https://github.com/inspect-js/object-inspect/commit/6905cc2f7df35600177e613b0642b4df5efd3eca) +- failing test for type errors [`385b615`](https://github.com/inspect-js/object-inspect/commit/385b6152e49b51b68449a662f410b084ed7c601a) +- fn name coverage [`edc906d`](https://github.com/inspect-js/object-inspect/commit/edc906d40fca6b9194d304062c037ee8e398c4c2) +- server-side element test [`362d1d3`](https://github.com/inspect-js/object-inspect/commit/362d1d3e86f187651c29feeb8478110afada385b) +- custom inspect fn [`e89b0f6`](https://github.com/inspect-js/object-inspect/commit/e89b0f6fe6d5e03681282af83732a509160435a6) +- fixed browser test [`b530882`](https://github.com/inspect-js/object-inspect/commit/b5308824a1c8471c5617e394766a03a6977102a9) +- depth test, matches node [`1cfd9e0`](https://github.com/inspect-js/object-inspect/commit/1cfd9e0285a4ae1dff44101ad482915d9bf47e48) +- exercise hasOwnProperty path [`8d753fb`](https://github.com/inspect-js/object-inspect/commit/8d753fb362a534fa1106e4d80f2ee9bea06a66d9) +- more cases covered for errors [`c5c46a5`](https://github.com/inspect-js/object-inspect/commit/c5c46a569ec4606583497e8550f0d8c7ad39a4a4) +- \W obj key test case [`b0eceee`](https://github.com/inspect-js/object-inspect/commit/b0eceeea6e0eb94d686c1046e99b9e25e5005f75) +- coverage for explicit depth param [`e12b91c`](https://github.com/inspect-js/object-inspect/commit/e12b91cd59683362f3a0e80f46481a0211e26c15) + +## [0.4.0](https://github.com/inspect-js/object-inspect/compare/0.3.1...0.4.0) - 2014-03-21 + +### Commits + +- passing lowbyte interpolation test [`b847511`](https://github.com/inspect-js/object-inspect/commit/b8475114f5def7e7961c5353d48d3d8d9a520985) +- lowbyte test [`4a2b0e1`](https://github.com/inspect-js/object-inspect/commit/4a2b0e142667fc933f195472759385ac08f3946c) + +## [0.3.1](https://github.com/inspect-js/object-inspect/compare/0.3.0...0.3.1) - 2014-03-04 + +### Commits + +- sort keys [`a07b19c`](https://github.com/inspect-js/object-inspect/commit/a07b19cc3b1521a82d4fafb6368b7a9775428a05) + +## [0.3.0](https://github.com/inspect-js/object-inspect/compare/0.2.0...0.3.0) - 2014-03-04 + +### Commits + +- [] and {} instead of [ ] and { } [`654c44b`](https://github.com/inspect-js/object-inspect/commit/654c44b2865811f3519e57bb8526e0821caf5c6b) + +## [0.2.0](https://github.com/inspect-js/object-inspect/compare/0.1.3...0.2.0) - 2014-03-04 + +### Commits + +- failing holes test [`99cdfad`](https://github.com/inspect-js/object-inspect/commit/99cdfad03c6474740275a75636fe6ca86c77737a) +- regex already work [`e324033`](https://github.com/inspect-js/object-inspect/commit/e324033267025995ec97d32ed0a65737c99477a6) +- failing undef/null test [`1f88a00`](https://github.com/inspect-js/object-inspect/commit/1f88a00265d3209719dda8117b7e6360b4c20943) +- holes in the all example [`7d345f3`](https://github.com/inspect-js/object-inspect/commit/7d345f3676dcbe980cff89a4f6c243269ebbb709) +- check for .inspect(), fixes Buffer use-case [`c3f7546`](https://github.com/inspect-js/object-inspect/commit/c3f75466dbca125347d49847c05262c292f12b79) +- fixes for holes [`ce25f73`](https://github.com/inspect-js/object-inspect/commit/ce25f736683de4b92ff27dc5471218415e2d78d8) +- weird null behavior [`405c1ea`](https://github.com/inspect-js/object-inspect/commit/405c1ea72cd5a8cf3b498c3eaa903d01b9fbcab5) +- tape is actually a devDependency, upgrade [`703b0ce`](https://github.com/inspect-js/object-inspect/commit/703b0ce6c5817b4245a082564bccd877e0bb6990) +- put date in the example [`a342219`](https://github.com/inspect-js/object-inspect/commit/a3422190eeaa013215f46df2d0d37b48595ac058) +- passing the null test [`4ab737e`](https://github.com/inspect-js/object-inspect/commit/4ab737ebf862a75d247ebe51e79307a34d6380d4) + +## [0.1.3](https://github.com/inspect-js/object-inspect/compare/0.1.1...0.1.3) - 2013-07-26 + +### Commits + +- special isElement() check [`882768a`](https://github.com/inspect-js/object-inspect/commit/882768a54035d30747be9de1baf14e5aa0daa128) +- oh right old IEs don't have indexOf either [`36d1275`](https://github.com/inspect-js/object-inspect/commit/36d12756c38b08a74370b0bb696c809e529913a5) + +## [0.1.1](https://github.com/inspect-js/object-inspect/compare/0.1.0...0.1.1) - 2013-07-26 + +### Commits + +- tests! [`4422fd9`](https://github.com/inspect-js/object-inspect/commit/4422fd95532c2745aa6c4f786f35f1090be29998) +- fix for ie<9, doesn't have hasOwnProperty [`6b7d611`](https://github.com/inspect-js/object-inspect/commit/6b7d61183050f6da801ea04473211da226482613) +- fix for all IEs: no f.name [`4e0c2f6`](https://github.com/inspect-js/object-inspect/commit/4e0c2f6dfd01c306d067d7163319acc97c94ee50) +- badges [`5ed0d88`](https://github.com/inspect-js/object-inspect/commit/5ed0d88e4e407f9cb327fa4a146c17921f9680f3) + +## [0.1.0](https://github.com/inspect-js/object-inspect/compare/0.0.0...0.1.0) - 2013-07-26 + +### Commits + +- [Function] for functions [`ad5c485`](https://github.com/inspect-js/object-inspect/commit/ad5c485098fc83352cb540a60b2548ca56820e0b) + +## 0.0.0 - 2013-07-26 + +### Commits + +- working browser example [`34be6b6`](https://github.com/inspect-js/object-inspect/commit/34be6b6548f9ce92bdc3c27572857ba0c4a1218d) +- package.json etc [`cad51f2`](https://github.com/inspect-js/object-inspect/commit/cad51f23fc6bcf1a456ed6abe16088256c2f632f) +- docs complete [`b80cce2`](https://github.com/inspect-js/object-inspect/commit/b80cce2490c4e7183a9ee11ea89071f0abec4446) +- circular example [`4b4a7b9`](https://github.com/inspect-js/object-inspect/commit/4b4a7b92209e4e6b4630976cb6bcd17d14165a59) +- string rep [`7afb479`](https://github.com/inspect-js/object-inspect/commit/7afb479baa798d27f09e0a178b72ea327f60f5c8) diff --git a/node_modules/object-inspect/LICENSE b/node_modules/object-inspect/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ca64cc1e605205438cc1b04b215f6fc12ab3f039 --- /dev/null +++ b/node_modules/object-inspect/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 James Halliday + +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. diff --git a/node_modules/object-inspect/example/all.js b/node_modules/object-inspect/example/all.js new file mode 100644 index 0000000000000000000000000000000000000000..2f3355c509acd1a0e9d409f9e655939d6d18c2ec --- /dev/null +++ b/node_modules/object-inspect/example/all.js @@ -0,0 +1,23 @@ +'use strict'; + +var inspect = require('../'); +var Buffer = require('safer-buffer').Buffer; + +var holes = ['a', 'b']; +holes[4] = 'e'; +holes[6] = 'g'; + +var obj = { + a: 1, + b: [3, 4, undefined, null], + c: undefined, + d: null, + e: { + regex: /^x/i, + buf: Buffer.from('abc'), + holes: holes + }, + now: new Date() +}; +obj.self = obj; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/circular.js b/node_modules/object-inspect/example/circular.js new file mode 100644 index 0000000000000000000000000000000000000000..487a7c169d0df8c4acb6ad02b26ce76175ecfc0f --- /dev/null +++ b/node_modules/object-inspect/example/circular.js @@ -0,0 +1,6 @@ +'use strict'; + +var inspect = require('../'); +var obj = { a: 1, b: [3, 4] }; +obj.c = obj; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/fn.js b/node_modules/object-inspect/example/fn.js new file mode 100644 index 0000000000000000000000000000000000000000..9b5db8de036ffc6718969bee9193de36409235aa --- /dev/null +++ b/node_modules/object-inspect/example/fn.js @@ -0,0 +1,5 @@ +'use strict'; + +var inspect = require('../'); +var obj = [1, 2, function f(n) { return n + 5; }, 4]; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/inspect.js b/node_modules/object-inspect/example/inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..e2df7c9f471356c48f14e7af2813119ffb6854bb --- /dev/null +++ b/node_modules/object-inspect/example/inspect.js @@ -0,0 +1,10 @@ +'use strict'; + +/* eslint-env browser */ +var inspect = require('../'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }])); diff --git a/node_modules/object-inspect/index.js b/node_modules/object-inspect/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a4b2d4cd850adb5cda64eb9e5692457a73c0947e --- /dev/null +++ b/node_modules/object-inspect/index.js @@ -0,0 +1,544 @@ +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); + +function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} + +var utilInspect = require('./util.inspect'); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + +var quotes = { + __proto__: null, + 'double': '"', + single: "'" +}; +var quoteREs = { + __proto__: null, + 'double': /(["\\])/g, + single: /(['\\])/g +}; + +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has(opts, 'quoteStyle') && !has(quotes, opts.quoteStyle)) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + // note: in IE 8, sometimes `global !== window` but both are the prototypes of each other + /* eslint-env browser */ + if (typeof window !== 'undefined' && obj === window) { + return '{ [object Window] }'; + } + if ( + (typeof globalThis !== 'undefined' && obj === globalThis) + || (typeof global !== 'undefined' && obj === global) + ) { + return '{ [object globalThis] }'; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; + +function wrapQuotes(s, defaultStyle, opts) { + var style = opts.quoteStyle || defaultStyle; + var quoteChar = quotes[style]; + return quoteChar + s + quoteChar; +} + +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} + +function canTrustToString(obj) { + return !toStringTag || !(typeof obj === 'object' && (toStringTag in obj || typeof obj[toStringTag] !== 'undefined')); +} +function isArray(obj) { return toStr(obj) === '[object Array]' && canTrustToString(obj); } +function isDate(obj) { return toStr(obj) === '[object Date]' && canTrustToString(obj); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && canTrustToString(obj); } +function isError(obj) { return toStr(obj) === '[object Error]' && canTrustToString(obj); } +function isString(obj) { return toStr(obj) === '[object String]' && canTrustToString(obj); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && canTrustToString(obj); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && canTrustToString(obj); } + +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} + +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} + +function toStr(obj) { + return objectToString.call(obj); +} + +function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; +} + +function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; +} + +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} + +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} + +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var quoteRE = quoteREs[opts.quoteStyle || 'single']; + quoteRE.lastIndex = 0; + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, quoteRE, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} + +function markBoxed(str) { + return 'Object(' + str + ')'; +} + +function weakCollectionOf(type) { + return type + ' { ? }'; +} + +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} + +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} + +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} + +function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} + +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} diff --git a/node_modules/object-inspect/package-support.json b/node_modules/object-inspect/package-support.json new file mode 100644 index 0000000000000000000000000000000000000000..5cc12d0585a386018d3c486be5a841d8377d15db --- /dev/null +++ b/node_modules/object-inspect/package-support.json @@ -0,0 +1,20 @@ +{ + "versions": [ + { + "version": "*", + "target": { + "node": "all" + }, + "response": { + "type": "time-permitting" + }, + "backing": { + "npm-funding": true, + "donations": [ + "https://github.com/ljharb", + "https://tidelift.com/funding/github/npm/object-inspect" + ] + } + } + ] +} diff --git a/node_modules/object-inspect/package.json b/node_modules/object-inspect/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9fd97ff7523f106de04c47adf74aa3a36db8dbbd --- /dev/null +++ b/node_modules/object-inspect/package.json @@ -0,0 +1,105 @@ +{ + "name": "object-inspect", + "version": "1.13.4", + "description": "string representations of objects in node and the browser", + "main": "index.js", + "sideEffects": false, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.1", + "@pkgjs/support": "^0.0.6", + "auto-changelog": "^2.5.0", + "core-js": "^2.6.12", + "error-cause": "^1.0.8", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "for-each": "^0.3.4", + "functions-have-names": "^1.2.3", + "glob": "=10.3.7", + "globalthis": "^1.0.4", + "has-symbols": "^1.1.0", + "has-tostringtag": "^1.0.2", + "in-publish": "^2.0.1", + "jackspeak": "=2.1.1", + "make-arrow-function": "^1.2.0", + "mock-property": "^1.1.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "safer-buffer": "^2.1.2", + "semver": "^6.3.1", + "string.prototype.repeat": "^1.0.0", + "tape": "^5.9.0" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "lint": "eslint --ext=js,mjs .", + "postlint": "npx @pkgjs/support validate", + "test": "npm run tests-only && npm run test:corejs", + "tests-only": "nyc tape 'test/*.js'", + "test:corejs": "nyc tape test-core-js.js 'test/*.js'", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": [ + "test/*.js", + "test/browser/*.js" + ], + "browsers": [ + "ie/6..latest", + "chrome/latest", + "firefox/latest", + "safari/latest", + "opera/latest", + "iphone/latest", + "ipad/latest", + "android/latest" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/object-inspect.git" + }, + "homepage": "https://github.com/inspect-js/object-inspect", + "keywords": [ + "inspect", + "util.inspect", + "object", + "stringify", + "pretty" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "browser": { + "./util.inspect.js": false + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "./test-core-js.js" + ] + }, + "support": true, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/object-inspect/readme.markdown b/node_modules/object-inspect/readme.markdown new file mode 100644 index 0000000000000000000000000000000000000000..f91617df32a3c8b9ffa23300ad26ca918bca13aa --- /dev/null +++ b/node_modules/object-inspect/readme.markdown @@ -0,0 +1,84 @@ +# object-inspect [![Version Badge][npm-version-svg]][package-url] + +string representations of objects in node and the browser + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +# example + +## circular + +``` js +var inspect = require('object-inspect'); +var obj = { a: 1, b: [3,4] }; +obj.c = obj; +console.log(inspect(obj)); +``` + +## dom element + +``` js +var inspect = require('object-inspect'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ])); +``` + +output: + +``` +[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [ ... ] ] ] ] } ] +``` + +# methods + +``` js +var inspect = require('object-inspect') +``` + +## var s = inspect(obj, opts={}) + +Return a string `s` with the string representation of `obj` up to a depth of `opts.depth`. + +Additional options: + - `quoteStyle`: must be "single" or "double", if present. Default `'single'` for strings, `'double'` for HTML elements. + - `maxStringLength`: must be `0`, a positive integer, `Infinity`, or `null`, if present. Default `Infinity`. + - `customInspect`: When `true`, a custom inspect method function will be invoked (either undere the `util.inspect.custom` symbol, or the `inspect` property). When the string `'symbol'`, only the symbol method will be invoked. Default `true`. + - `indent`: must be "\t", `null`, or a positive integer. Default `null`. + - `numericSeparator`: must be a boolean, if present. Default `false`. If `true`, all numbers will be printed with numeric separators (eg, `1234.5678` will be printed as `'1_234.567_8'`) + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install object-inspect +``` + +# license + +MIT + +[package-url]: https://npmjs.org/package/object-inspect +[npm-version-svg]: https://versionbadg.es/inspect-js/object-inspect.svg +[deps-svg]: https://david-dm.org/inspect-js/object-inspect.svg +[deps-url]: https://david-dm.org/inspect-js/object-inspect +[dev-deps-svg]: https://david-dm.org/inspect-js/object-inspect/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/object-inspect#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/object-inspect.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/object-inspect.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/object-inspect.svg +[downloads-url]: https://npm-stat.com/charts.html?package=object-inspect +[codecov-image]: https://codecov.io/gh/inspect-js/object-inspect/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/object-inspect/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/object-inspect +[actions-url]: https://github.com/inspect-js/object-inspect/actions diff --git a/node_modules/object-inspect/test-core-js.js b/node_modules/object-inspect/test-core-js.js new file mode 100644 index 0000000000000000000000000000000000000000..e53c40022533f691fd17d623cd24a8ecb5a82669 --- /dev/null +++ b/node_modules/object-inspect/test-core-js.js @@ -0,0 +1,26 @@ +'use strict'; + +require('core-js'); + +var inspect = require('./'); +var test = require('tape'); + +test('Maps', function (t) { + t.equal(inspect(new Map([[1, 2]])), 'Map (1) {1 => 2}'); + t.end(); +}); + +test('WeakMaps', function (t) { + t.equal(inspect(new WeakMap([[{}, 2]])), 'WeakMap { ? }'); + t.end(); +}); + +test('Sets', function (t) { + t.equal(inspect(new Set([[1, 2]])), 'Set (1) {[ 1, 2 ]}'); + t.end(); +}); + +test('WeakSets', function (t) { + t.equal(inspect(new WeakSet([[1, 2]])), 'WeakSet { ? }'); + t.end(); +}); diff --git a/node_modules/object-inspect/test/bigint.js b/node_modules/object-inspect/test/bigint.js new file mode 100644 index 0000000000000000000000000000000000000000..4ecc31df8ab3fd311570d866b418514d159abfde --- /dev/null +++ b/node_modules/object-inspect/test/bigint.js @@ -0,0 +1,58 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('bigint', { skip: typeof BigInt === 'undefined' }, function (t) { + t.test('primitives', function (st) { + st.plan(3); + + st.equal(inspect(BigInt(-256)), '-256n'); + st.equal(inspect(BigInt(0)), '0n'); + st.equal(inspect(BigInt(256)), '256n'); + }); + + t.test('objects', function (st) { + st.plan(3); + + st.equal(inspect(Object(BigInt(-256))), 'Object(-256n)'); + st.equal(inspect(Object(BigInt(0))), 'Object(0n)'); + st.equal(inspect(Object(BigInt(256))), 'Object(256n)'); + }); + + t.test('syntactic primitives', function (st) { + st.plan(3); + + /* eslint-disable no-new-func */ + st.equal(inspect(Function('return -256n')()), '-256n'); + st.equal(inspect(Function('return 0n')()), '0n'); + st.equal(inspect(Function('return 256n')()), '256n'); + }); + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'BigInt'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'BigInt\' }', + 'object lying about being a BigInt inspects as an object' + ); + }); + + t.test('numericSeparator', function (st) { + st.equal(inspect(BigInt(0), { numericSeparator: false }), '0n', '0n, numericSeparator false'); + st.equal(inspect(BigInt(0), { numericSeparator: true }), '0n', '0n, numericSeparator true'); + + st.equal(inspect(BigInt(1234), { numericSeparator: false }), '1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(1234), { numericSeparator: true }), '1_234n', '1234n, numericSeparator true'); + st.equal(inspect(BigInt(-1234), { numericSeparator: false }), '-1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(-1234), { numericSeparator: true }), '-1_234n', '1234n, numericSeparator true'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/browser/dom.js b/node_modules/object-inspect/test/browser/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..210c0b233e9f72c5733ef80fa38a3e8a315e5c29 --- /dev/null +++ b/node_modules/object-inspect/test/browser/dom.js @@ -0,0 +1,15 @@ +var inspect = require('../../'); +var test = require('tape'); + +test('dom element', function (t) { + t.plan(1); + + var d = document.createElement('div'); + d.setAttribute('id', 'beep'); + d.innerHTML = 'woooiiiii'; + + t.equal( + inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }]), + '[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [Object] ] ] ] } ]' + ); +}); diff --git a/node_modules/object-inspect/test/circular.js b/node_modules/object-inspect/test/circular.js new file mode 100644 index 0000000000000000000000000000000000000000..5df4233cb202efc92a8e874ef74f0c69d6ac29d1 --- /dev/null +++ b/node_modules/object-inspect/test/circular.js @@ -0,0 +1,16 @@ +var inspect = require('../'); +var test = require('tape'); + +test('circular', function (t) { + t.plan(2); + var obj = { a: 1, b: [3, 4] }; + obj.c = obj; + t.equal(inspect(obj), '{ a: 1, b: [ 3, 4 ], c: [Circular] }'); + + var double = {}; + double.a = [double]; + double.b = {}; + double.b.inner = double.b; + double.b.obj = double; + t.equal(inspect(double), '{ a: [ [Circular] ], b: { inner: [Circular], obj: [Circular] } }'); +}); diff --git a/node_modules/object-inspect/test/deep.js b/node_modules/object-inspect/test/deep.js new file mode 100644 index 0000000000000000000000000000000000000000..99ce32a088f90f217c1e4b001f4e41d3ddd4f3ec --- /dev/null +++ b/node_modules/object-inspect/test/deep.js @@ -0,0 +1,12 @@ +var inspect = require('../'); +var test = require('tape'); + +test('deep', function (t) { + t.plan(4); + var obj = [[[[[[500]]]]]]; + t.equal(inspect(obj), '[ [ [ [ [ [Array] ] ] ] ] ]'); + t.equal(inspect(obj, { depth: 4 }), '[ [ [ [ [Array] ] ] ] ]'); + t.equal(inspect(obj, { depth: 2 }), '[ [ [Array] ] ]'); + + t.equal(inspect([[[{ a: 1 }]]], { depth: 3 }), '[ [ [ [Object] ] ] ]'); +}); diff --git a/node_modules/object-inspect/test/element.js b/node_modules/object-inspect/test/element.js new file mode 100644 index 0000000000000000000000000000000000000000..47fa9e240029eb6fa2906727e20ec843fc3b6308 --- /dev/null +++ b/node_modules/object-inspect/test/element.js @@ -0,0 +1,53 @@ +var inspect = require('../'); +var test = require('tape'); + +test('element', function (t) { + t.plan(3); + var elem = { + nodeName: 'div', + attributes: [{ name: 'class', value: 'row' }], + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + t.deepEqual(inspect(obj, { quoteStyle: 'single' }), "[ 1,
, 3 ]"); + t.deepEqual(inspect(obj, { quoteStyle: 'double' }), '[ 1,
, 3 ]'); +}); + +test('element no attr', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); +}); + +test('element with contents', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [{ nodeName: 'b' }] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
...
, 3 ]'); +}); + +test('element instance', function (t) { + t.plan(1); + var h = global.HTMLElement; + global.HTMLElement = function (name, attr) { + this.nodeName = name; + this.attributes = attr; + }; + global.HTMLElement.prototype.getAttribute = function () {}; + + var elem = new global.HTMLElement('div', []); + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + global.HTMLElement = h; +}); diff --git a/node_modules/object-inspect/test/err.js b/node_modules/object-inspect/test/err.js new file mode 100644 index 0000000000000000000000000000000000000000..cc1d884abdc52c8b5443b6212ab1d0d886ce9c33 --- /dev/null +++ b/node_modules/object-inspect/test/err.js @@ -0,0 +1,48 @@ +var test = require('tape'); +var ErrorWithCause = require('error-cause/Error'); + +var inspect = require('../'); + +test('type error', function (t) { + t.plan(1); + var aerr = new TypeError(); + aerr.foo = 555; + aerr.bar = [1, 2, 3]; + + var berr = new TypeError('tuv'); + berr.baz = 555; + + var cerr = new SyntaxError(); + cerr.message = 'whoa'; + cerr['a-b'] = 5; + + var withCause = new ErrorWithCause('foo', { cause: 'bar' }); + var withCausePlus = new ErrorWithCause('foo', { cause: 'bar' }); + withCausePlus.foo = 'bar'; + var withUndefinedCause = new ErrorWithCause('foo', { cause: undefined }); + var withEnumerableCause = new Error('foo'); + withEnumerableCause.cause = 'bar'; + + var obj = [ + new TypeError(), + new TypeError('xxx'), + aerr, + berr, + cerr, + withCause, + withCausePlus, + withUndefinedCause, + withEnumerableCause + ]; + t.equal(inspect(obj), '[ ' + [ + '[TypeError]', + '[TypeError: xxx]', + '{ [TypeError] foo: 555, bar: [ 1, 2, 3 ] }', + '{ [TypeError: tuv] baz: 555 }', + '{ [SyntaxError: whoa] message: \'whoa\', \'a-b\': 5 }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: \'bar\' }', + '{ [Error: foo] ' + ('cause' in Error.prototype ? '' : '[cause]: \'bar\', ') + 'foo: \'bar\' }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: undefined }', + '{ [Error: foo] cause: \'bar\' }' + ].join(', ') + ' ]'); +}); diff --git a/node_modules/object-inspect/test/fakes.js b/node_modules/object-inspect/test/fakes.js new file mode 100644 index 0000000000000000000000000000000000000000..a65c08c15a6e4c9c5500cbbb7a2b01327a5a8c4b --- /dev/null +++ b/node_modules/object-inspect/test/fakes.js @@ -0,0 +1,29 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('for-each'); + +test('fakes', { skip: !hasToStringTag }, function (t) { + forEach([ + 'Array', + 'Boolean', + 'Date', + 'Error', + 'Number', + 'RegExp', + 'String' + ], function (expected) { + var faker = {}; + faker[Symbol.toStringTag] = expected; + + t.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'' + expected + '\' }', + 'faker masquerading as ' + expected + ' is not shown as one' + ); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/fn.js b/node_modules/object-inspect/test/fn.js new file mode 100644 index 0000000000000000000000000000000000000000..de3ca625e73adcabc8570a11318504d8d6aa6806 --- /dev/null +++ b/node_modules/object-inspect/test/fn.js @@ -0,0 +1,76 @@ +var inspect = require('../'); +var test = require('tape'); +var arrow = require('make-arrow-function')(); +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); + +test('function', function (t) { + t.plan(1); + var obj = [1, 2, function f(n) { return n; }, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function: f], 4 ]'); +}); + +test('function name', function (t) { + t.plan(1); + var f = (function () { + return function () {}; + }()); + f.toString = function toStr() { return 'function xxx () {}'; }; + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)] { toString: [Function: toStr] }, 4 ]'); +}); + +test('anon function', function (t) { + var f = (function () { + return function () {}; + }()); + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)], 4 ]'); + + t.end(); +}); + +test('arrow function', { skip: !arrow }, function (t) { + t.equal(inspect(arrow), '[Function (anonymous)]'); + + t.end(); +}); + +test('truly nameless function', { skip: !arrow || !functionsHaveConfigurableNames }, function (t) { + function f() {} + Object.defineProperty(f, 'name', { value: false }); + t.equal(f.name, false); + t.equal( + inspect(f), + '[Function: f]', + 'named function with falsy `.name` does not hide its original name' + ); + + function g() {} + Object.defineProperty(g, 'name', { value: true }); + t.equal(g.name, true); + t.equal( + inspect(g), + '[Function: true]', + 'named function with truthy `.name` hides its original name' + ); + + var anon = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon, 'name', { value: null }); + t.equal(anon.name, null); + t.equal( + inspect(anon), + '[Function (anonymous)]', + 'anon function with falsy `.name` does not hide its anonymity' + ); + + var anon2 = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon2, 'name', { value: 1 }); + t.equal(anon2.name, 1); + t.equal( + inspect(anon2), + '[Function: 1]', + 'anon function with truthy `.name` hides its anonymity' + ); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/global.js b/node_modules/object-inspect/test/global.js new file mode 100644 index 0000000000000000000000000000000000000000..c57216aebd518555d0ba6e6677238b6cf4aee59d --- /dev/null +++ b/node_modules/object-inspect/test/global.js @@ -0,0 +1,17 @@ +'use strict'; + +var inspect = require('../'); + +var test = require('tape'); +var globalThis = require('globalthis')(); + +test('global object', function (t) { + /* eslint-env browser */ + var expected = typeof window === 'undefined' ? 'globalThis' : 'Window'; + t.equal( + inspect([globalThis]), + '[ { [object ' + expected + '] } ]' + ); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/has.js b/node_modules/object-inspect/test/has.js new file mode 100644 index 0000000000000000000000000000000000000000..01800dee6b07894536485e9a23ca6cda472984a2 --- /dev/null +++ b/node_modules/object-inspect/test/has.js @@ -0,0 +1,15 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); + +test('when Object#hasOwnProperty is deleted', function (t) { + t.plan(1); + var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays + + t.teardown(mockProperty(Array.prototype, 1, { value: 2 })); // this is needed to account for "in" vs "hasOwnProperty" + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect(arr), '[ 1, , 3 ]'); +}); diff --git a/node_modules/object-inspect/test/holes.js b/node_modules/object-inspect/test/holes.js new file mode 100644 index 0000000000000000000000000000000000000000..87fc8c84aedf765a2c908f451564e54ac27dcb85 --- /dev/null +++ b/node_modules/object-inspect/test/holes.js @@ -0,0 +1,15 @@ +var test = require('tape'); +var inspect = require('../'); + +var xs = ['a', 'b']; +xs[5] = 'f'; +xs[7] = 'j'; +xs[8] = 'k'; + +test('holes', function (t) { + t.plan(1); + t.equal( + inspect(xs), + "[ 'a', 'b', , , , 'f', , 'j', 'k' ]" + ); +}); diff --git a/node_modules/object-inspect/test/indent-option.js b/node_modules/object-inspect/test/indent-option.js new file mode 100644 index 0000000000000000000000000000000000000000..89d8fcedfa318ca67c9ba8fe694ba06fd2b47044 --- /dev/null +++ b/node_modules/object-inspect/test/indent-option.js @@ -0,0 +1,271 @@ +var test = require('tape'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('bad indent options', function (t) { + forEach([ + undefined, + true, + false, + -1, + 1.2, + Infinity, + -Infinity, + NaN + ], function (indent) { + t['throws']( + function () { inspect('', { indent: indent }); }, + TypeError, + inspect(indent) + ' is invalid' + ); + }); + + t.end(); +}); + +test('simple object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: 2 }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('two deep object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: { c: 3, d: 4 } }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('simple array with all single line elements', function (t) { + t.plan(2); + + var obj = [1, 2, 3, 'asdf\nsdf']; + + var expected = '[ 1, 2, 3, \'asdf\\nsdf\' ]'; + + t.equal(inspect(obj, { indent: 2 }), expected, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expected, 'tabs'); +}); + +test('array with complex elements', function (t) { + t.plan(2); + + var obj = [1, { a: 1, b: { c: 1 } }, 'asdf\nsdf']; + + var expectedSpaces = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('values', function (t) { + t.plan(2); + var obj = [{}, [], { 'a-b': 5 }]; + + var expectedSpaces = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + + var expectedStringSpaces = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabsDoubleQuotes = [ + 'Map (2) {', + ' { a: 1 } => [ "b" ],', + ' 3 => NaN', + '}' + ].join('\n'); + + t.equal( + inspect(map, { indent: 2 }), + expectedStringSpaces, + 'Map keys are not indented (two)' + ); + t.equal( + inspect(map, { indent: '\t' }), + expectedStringTabs, + 'Map keys are not indented (tabs)' + ); + t.equal( + inspect(map, { indent: '\t', quoteStyle: 'double' }), + expectedStringTabsDoubleQuotes, + 'Map keys are not indented (tabs + double quotes)' + ); + + t.equal(inspect(new Map(), { indent: 2 }), 'Map (0) {}', 'empty Map should show as empty (two)'); + t.equal(inspect(new Map(), { indent: '\t' }), 'Map (0) {}', 'empty Map should show as empty (tabs)'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + var expectedNestedSpaces = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + t.equal(inspect(nestedMap, { indent: 2 }), expectedNestedSpaces, 'Map containing a Map should work (two)'); + t.equal(inspect(nestedMap, { indent: '\t' }), expectedNestedTabs, 'Map containing a Map should work (tabs)'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedStringSpaces = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + t.equal(inspect(set, { indent: 2 }), expectedStringSpaces, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (two)'); + t.equal(inspect(set, { indent: '\t' }), expectedStringTabs, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (tabs)'); + + t.equal(inspect(new Set(), { indent: 2 }), 'Set (0) {}', 'empty Set should show as empty (two)'); + t.equal(inspect(new Set(), { indent: '\t' }), 'Set (0) {}', 'empty Set should show as empty (tabs)'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + var expectedNestedSpaces = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + t.equal(inspect(nestedSet, { indent: 2 }), expectedNestedSpaces, 'Set containing a Set should work (two)'); + t.equal(inspect(nestedSet, { indent: '\t' }), expectedNestedTabs, 'Set containing a Set should work (tabs)'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/inspect.js b/node_modules/object-inspect/test/inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..1abf81b1f00b305519e52fe74477b2c5b71803c7 --- /dev/null +++ b/node_modules/object-inspect/test/inspect.js @@ -0,0 +1,139 @@ +var test = require('tape'); +var hasSymbols = require('has-symbols/shams')(); +var utilInspect = require('../util.inspect'); +var repeat = require('string.prototype.repeat'); + +var inspect = require('..'); + +test('inspect', function (t) { + t.plan(5); + + var obj = [{ inspect: function xyzInspect() { return '!XYZ¡'; } }, []]; + var stringResult = '[ !XYZ¡, [] ]'; + var falseResult = '[ { inspect: [Function: xyzInspect] }, [] ]'; + + t.equal(inspect(obj), stringResult); + t.equal(inspect(obj, { customInspect: true }), stringResult); + t.equal(inspect(obj, { customInspect: 'symbol' }), falseResult); + t.equal(inspect(obj, { customInspect: false }), falseResult); + t['throws']( + function () { inspect(obj, { customInspect: 'not a boolean or "symbol"' }); }, + TypeError, + '`customInspect` must be a boolean or the string "symbol"' + ); +}); + +test('inspect custom symbol', { skip: !hasSymbols || !utilInspect || !utilInspect.custom }, function (t) { + t.plan(4); + + var obj = { inspect: function stringInspect() { return 'string'; } }; + obj[utilInspect.custom] = function custom() { return 'symbol'; }; + + var symbolResult = '[ symbol, [] ]'; + var stringResult = '[ string, [] ]'; + var falseResult = '[ { inspect: [Function: stringInspect]' + (utilInspect.custom ? ', [' + inspect(utilInspect.custom) + ']: [Function: custom]' : '') + ' }, [] ]'; + + var symbolStringFallback = utilInspect.custom ? symbolResult : stringResult; + var symbolFalseFallback = utilInspect.custom ? symbolResult : falseResult; + + t.equal(inspect([obj, []]), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: true }), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: 'symbol' }), symbolFalseFallback); + t.equal(inspect([obj, []], { customInspect: false }), falseResult); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + t.plan(2); + + var obj = { a: 1 }; + obj[Symbol('test')] = 2; + obj[Symbol.iterator] = 3; + Object.defineProperty(obj, Symbol('non-enum'), { + enumerable: false, + value: 4 + }); + + if (typeof Symbol.iterator === 'symbol') { + t.equal(inspect(obj), '{ a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }', 'object with symbols'); + t.equal(inspect([obj, []]), '[ { a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }, [] ]', 'object with symbols in array'); + } else { + // symbol sham key ordering is unreliable + t.match( + inspect(obj), + /^(?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 })$/, + 'object with symbols (nondeterministic symbol sham key ordering)' + ); + t.match( + inspect([obj, []]), + /^\[ (?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 }), \[\] \]$/, + 'object with symbols in array (nondeterministic symbol sham key ordering)' + ); + } +}); + +test('maxStringLength', function (t) { + t['throws']( + function () { inspect('', { maxStringLength: -1 }); }, + TypeError, + 'maxStringLength must be >= 0, or Infinity, not negative' + ); + + var str = repeat('a', 1e8); + + t.equal( + inspect([str], { maxStringLength: 10 }), + '[ \'aaaaaaaaaa\'... 99999990 more characters ]', + 'maxStringLength option limits output' + ); + + t.equal( + inspect(['f'], { maxStringLength: null }), + '[ \'\'... 1 more character ]', + 'maxStringLength option accepts `null`' + ); + + t.equal( + inspect([str], { maxStringLength: Infinity }), + '[ \'' + str + '\' ]', + 'maxStringLength option accepts ∞' + ); + + t.end(); +}); + +test('inspect options', { skip: !utilInspect.custom }, function (t) { + var obj = {}; + obj[utilInspect.custom] = function () { + return JSON.stringify(arguments); + }; + t.equal( + inspect(obj), + utilInspect(obj, { depth: 5 }), + 'custom symbols will use node\'s inspect' + ); + t.equal( + inspect(obj, { depth: 2 }), + utilInspect(obj, { depth: 2 }), + 'a reduced depth will be passed to node\'s inspect' + ); + t.equal( + inspect({ d1: obj }, { depth: 3 }), + '{ d1: ' + utilInspect(obj, { depth: 2 }) + ' }', + 'deep objects will receive a reduced depth' + ); + t.equal( + inspect({ d1: obj }, { depth: 1 }), + '{ d1: [Object] }', + 'unlike nodejs inspect, customInspect will not be used once the depth is exceeded.' + ); + t.end(); +}); + +test('inspect URL', { skip: typeof URL === 'undefined' }, function (t) { + t.match( + inspect(new URL('https://nodejs.org')), + /nodejs\.org/, // Different environments stringify it differently + 'url can be inspected' + ); + t.end(); +}); diff --git a/node_modules/object-inspect/test/lowbyte.js b/node_modules/object-inspect/test/lowbyte.js new file mode 100644 index 0000000000000000000000000000000000000000..68a345d8578004506a45296d6de9e091b7811272 --- /dev/null +++ b/node_modules/object-inspect/test/lowbyte.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { x: 'a\r\nb', y: '\x05! \x1f \x12' }; + +test('interpolate low bytes', function (t) { + t.plan(1); + t.equal( + inspect(obj), + "{ x: 'a\\r\\nb', y: '\\x05! \\x1F \\x12' }" + ); +}); diff --git a/node_modules/object-inspect/test/number.js b/node_modules/object-inspect/test/number.js new file mode 100644 index 0000000000000000000000000000000000000000..8f287e8e2ab93785108de2e82e5b359ffb524f02 --- /dev/null +++ b/node_modules/object-inspect/test/number.js @@ -0,0 +1,58 @@ +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('negative zero', function (t) { + t.equal(inspect(0), '0', 'inspect(0) === "0"'); + t.equal(inspect(Object(0)), 'Object(0)', 'inspect(Object(0)) === "Object(0)"'); + + t.equal(inspect(-0), '-0', 'inspect(-0) === "-0"'); + t.equal(inspect(Object(-0)), 'Object(-0)', 'inspect(Object(-0)) === "Object(-0)"'); + + t.end(); +}); + +test('numericSeparator', function (t) { + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { inspect(true, { numericSeparator: nonBoolean }); }, + TypeError, + inspect(nonBoolean) + ' is not a boolean' + ); + }); + + t.test('3 digit numbers', function (st) { + var failed = false; + for (var i = -999; i < 1000; i += 1) { + var actual = inspect(i); + var actualSepNo = inspect(i, { numericSeparator: false }); + var actualSepYes = inspect(i, { numericSeparator: true }); + var expected = String(i); + if (actual !== expected || actualSepNo !== expected || actualSepYes !== expected) { + failed = true; + t.equal(actual, expected); + t.equal(actualSepNo, expected); + t.equal(actualSepYes, expected); + } + } + + st.notOk(failed, 'all 3 digit numbers passed'); + + st.end(); + }); + + t.equal(inspect(1e3), '1000', '1000'); + t.equal(inspect(1e3, { numericSeparator: false }), '1000', '1000, numericSeparator false'); + t.equal(inspect(1e3, { numericSeparator: true }), '1_000', '1000, numericSeparator true'); + t.equal(inspect(-1e3), '-1000', '-1000'); + t.equal(inspect(-1e3, { numericSeparator: false }), '-1000', '-1000, numericSeparator false'); + t.equal(inspect(-1e3, { numericSeparator: true }), '-1_000', '-1000, numericSeparator true'); + + t.equal(inspect(1234.5678, { numericSeparator: true }), '1_234.567_8', 'fractional numbers get separators'); + t.equal(inspect(1234.56789, { numericSeparator: true }), '1_234.567_89', 'fractional numbers get separators'); + t.equal(inspect(1234.567891, { numericSeparator: true }), '1_234.567_891', 'fractional numbers get separators'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/quoteStyle.js b/node_modules/object-inspect/test/quoteStyle.js new file mode 100644 index 0000000000000000000000000000000000000000..da23e630cfcf0b2bcd6d5e90becc09d714f46d7b --- /dev/null +++ b/node_modules/object-inspect/test/quoteStyle.js @@ -0,0 +1,26 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); + +test('quoteStyle option', function (t) { + t['throws'](function () { inspect(null, { quoteStyle: false }); }, 'false is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: true }); }, 'true is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: '' }); }, '"" is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: {} }); }, '{} is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: [] }); }, '[] is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: 42 }); }, '42 is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: NaN }); }, 'NaN is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: function () {} }); }, 'a function is not a valid value'); + + t.equal(inspect('"', { quoteStyle: 'single' }), '\'"\'', 'double quote, quoteStyle: "single"'); + t.equal(inspect('"', { quoteStyle: 'double' }), '"\\""', 'double quote, quoteStyle: "double"'); + + t.equal(inspect('\'', { quoteStyle: 'single' }), '\'\\\'\'', 'single quote, quoteStyle: "single"'); + t.equal(inspect('\'', { quoteStyle: 'double' }), '"\'"', 'single quote, quoteStyle: "double"'); + + t.equal(inspect('`', { quoteStyle: 'single' }), '\'`\'', 'backtick, quoteStyle: "single"'); + t.equal(inspect('`', { quoteStyle: 'double' }), '"`"', 'backtick, quoteStyle: "double"'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/toStringTag.js b/node_modules/object-inspect/test/toStringTag.js new file mode 100644 index 0000000000000000000000000000000000000000..95f82703d08f358b00f180c7b479b9f33dff3dac --- /dev/null +++ b/node_modules/object-inspect/test/toStringTag.js @@ -0,0 +1,40 @@ +'use strict'; + +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +var inspect = require('../'); + +test('Symbol.toStringTag', { skip: !hasToStringTag }, function (t) { + t.plan(4); + + var obj = { a: 1 }; + t.equal(inspect(obj), '{ a: 1 }', 'object, no Symbol.toStringTag'); + + obj[Symbol.toStringTag] = 'foo'; + t.equal(inspect(obj), '{ a: 1, [Symbol(Symbol.toStringTag)]: \'foo\' }', 'object with Symbol.toStringTag'); + + t.test('null objects', { skip: 'toString' in { __proto__: null } }, function (st) { + st.plan(2); + + var dict = { __proto__: null, a: 1 }; + st.equal(inspect(dict), '[Object: null prototype] { a: 1 }', 'null object with Symbol.toStringTag'); + + dict[Symbol.toStringTag] = 'Dict'; + st.equal(inspect(dict), '[Dict: null prototype] { a: 1, [Symbol(Symbol.toStringTag)]: \'Dict\' }', 'null object with Symbol.toStringTag'); + }); + + t.test('instances', function (st) { + st.plan(4); + + function C() { + this.a = 1; + } + st.equal(Object.prototype.toString.call(new C()), '[object Object]', 'instance, no toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C { a: 1 }', 'instance, no toStringTag'); + + C.prototype[Symbol.toStringTag] = 'Class!'; + st.equal(Object.prototype.toString.call(new C()), '[object Class!]', 'instance, with toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C [Class!] { a: 1 }', 'instance, with toStringTag'); + }); +}); diff --git a/node_modules/object-inspect/test/undef.js b/node_modules/object-inspect/test/undef.js new file mode 100644 index 0000000000000000000000000000000000000000..e3f4961229c249a1d4f242d415b5193fc0ad5056 --- /dev/null +++ b/node_modules/object-inspect/test/undef.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { a: 1, b: [3, 4, undefined, null], c: undefined, d: null }; + +test('undef and null', function (t) { + t.plan(1); + t.equal( + inspect(obj), + '{ a: 1, b: [ 3, 4, undefined, null ], c: undefined, d: null }' + ); +}); diff --git a/node_modules/object-inspect/test/values.js b/node_modules/object-inspect/test/values.js new file mode 100644 index 0000000000000000000000000000000000000000..15986cd0edbb8218fdd4fe8f414b4e27b5767b1e --- /dev/null +++ b/node_modules/object-inspect/test/values.js @@ -0,0 +1,261 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); +var hasSymbols = require('has-symbols/shams')(); +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('for-each'); +var semver = require('semver'); + +test('values', function (t) { + t.plan(1); + var obj = [{}, [], { 'a-b': 5 }]; + t.equal(inspect(obj), '[ {}, [], { \'a-b\': 5 } ]'); +}); + +test('arrays with properties', function (t) { + t.plan(1); + var arr = [3]; + arr.foo = 'bar'; + var obj = [1, 2, arr]; + obj.baz = 'quux'; + obj.index = -1; + t.equal(inspect(obj), '[ 1, 2, [ 3, foo: \'bar\' ], baz: \'quux\', index: -1 ]'); +}); + +test('has', function (t) { + t.plan(1); + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect({ a: 1, b: 2 }), '{ a: 1, b: 2 }'); +}); + +test('indexOf seen', function (t) { + t.plan(1); + var xs = [1, 2, 3, {}]; + xs.push(xs); + + var seen = []; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[ 1, 2, 3, {}, [Circular] ]' + ); +}); + +test('seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('seen seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [5, xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + var sym = Symbol('foo'); + t.equal(inspect(sym), 'Symbol(foo)', 'Symbol("foo") should be "Symbol(foo)"'); + if (typeof sym === 'symbol') { + // Symbol shams are incapable of differentiating boxed from unboxed symbols + t.equal(inspect(Object(sym)), 'Object(Symbol(foo))', 'Object(Symbol("foo")) should be "Object(Symbol(foo))"'); + } + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'Symbol'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'Symbol\' }', + 'object lying about being a Symbol inspects as an object' + ); + }); + + t.end(); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + var expectedString = 'Map (2) {' + inspect({ a: 1 }) + ' => ' + inspect(['b']) + ', 3 => NaN}'; + t.equal(inspect(map), expectedString, 'new Map([[{ a: 1 }, ["b"]], [3, NaN]]) should show size and contents'); + t.equal(inspect(new Map()), 'Map (0) {}', 'empty Map should show as empty'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + t.equal(inspect(nestedMap), 'Map (1) {[Circular] => ' + expectedString + '}', 'Map containing a Map should work'); + + t.end(); +}); + +test('WeakMap', { skip: typeof WeakMap !== 'function' }, function (t) { + var map = new WeakMap(); + map.set({ a: 1 }, ['b']); + var expectedString = 'WeakMap { ? }'; + t.equal(inspect(map), expectedString, 'new WeakMap([[{ a: 1 }, ["b"]]]) should not show size or contents'); + t.equal(inspect(new WeakMap()), 'WeakMap { ? }', 'empty WeakMap should not show as empty'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedString = 'Set (2) {' + inspect({ a: 1 }) + ', ' + inspect(['b']) + '}'; + t.equal(inspect(set), expectedString, 'new Set([{ a: 1 }, ["b"]]) should show size and contents'); + t.equal(inspect(new Set()), 'Set (0) {}', 'empty Set should show as empty'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + t.equal(inspect(nestedSet), 'Set (2) {' + expectedString + ', [Circular]}', 'Set containing a Set should work'); + + t.end(); +}); + +test('WeakSet', { skip: typeof WeakSet !== 'function' }, function (t) { + var map = new WeakSet(); + map.add({ a: 1 }); + var expectedString = 'WeakSet { ? }'; + t.equal(inspect(map), expectedString, 'new WeakSet([{ a: 1 }]) should not show size or contents'); + t.equal(inspect(new WeakSet()), 'WeakSet { ? }', 'empty WeakSet should not show as empty'); + + t.end(); +}); + +test('WeakRef', { skip: typeof WeakRef !== 'function' }, function (t) { + var ref = new WeakRef({ a: 1 }); + var expectedString = 'WeakRef { ? }'; + t.equal(inspect(ref), expectedString, 'new WeakRef({ a: 1 }) should not show contents'); + + t.end(); +}); + +test('FinalizationRegistry', { skip: typeof FinalizationRegistry !== 'function' }, function (t) { + var registry = new FinalizationRegistry(function () {}); + var expectedString = 'FinalizationRegistry [FinalizationRegistry] {}'; + t.equal(inspect(registry), expectedString, 'new FinalizationRegistry(function () {}) should work normallys'); + + t.end(); +}); + +test('Strings', function (t) { + var str = 'abc'; + + t.equal(inspect(str), "'" + str + "'", 'primitive string shows as such'); + t.equal(inspect(str, { quoteStyle: 'single' }), "'" + str + "'", 'primitive string shows as such, single quoted'); + t.equal(inspect(str, { quoteStyle: 'double' }), '"' + str + '"', 'primitive string shows as such, double quoted'); + t.equal(inspect(Object(str)), 'Object(' + inspect(str) + ')', 'String object shows as such'); + t.equal(inspect(Object(str), { quoteStyle: 'single' }), 'Object(' + inspect(str, { quoteStyle: 'single' }) + ')', 'String object shows as such, single quoted'); + t.equal(inspect(Object(str), { quoteStyle: 'double' }), 'Object(' + inspect(str, { quoteStyle: 'double' }) + ')', 'String object shows as such, double quoted'); + + t.end(); +}); + +test('Numbers', function (t) { + var num = 42; + + t.equal(inspect(num), String(num), 'primitive number shows as such'); + t.equal(inspect(Object(num)), 'Object(' + inspect(num) + ')', 'Number object shows as such'); + + t.end(); +}); + +test('Booleans', function (t) { + t.equal(inspect(true), String(true), 'primitive true shows as such'); + t.equal(inspect(Object(true)), 'Object(' + inspect(true) + ')', 'Boolean object true shows as such'); + + t.equal(inspect(false), String(false), 'primitive false shows as such'); + t.equal(inspect(Object(false)), 'Object(' + inspect(false) + ')', 'Boolean false object shows as such'); + + t.end(); +}); + +test('Date', function (t) { + var now = new Date(); + t.equal(inspect(now), String(now), 'Date shows properly'); + t.equal(inspect(new Date(NaN)), 'Invalid Date', 'Invalid Date shows properly'); + + t.end(); +}); + +test('RegExps', function (t) { + t.equal(inspect(/a/g), '/a/g', 'regex shows properly'); + t.equal(inspect(new RegExp('abc', 'i')), '/abc/i', 'new RegExp shows properly'); + + var match = 'abc abc'.match(/[ab]+/); + delete match.groups; // for node < 10 + t.equal(inspect(match), '[ \'ab\', index: 0, input: \'abc abc\' ]', 'RegExp match object shows properly'); + + t.end(); +}); + +test('Proxies', { skip: typeof Proxy !== 'function' || !hasToStringTag }, function (t) { + var target = { proxy: true }; + var fake = new Proxy(target, { has: function () { return false; } }); + + // needed to work around a weird difference in node v6.0 - v6.4 where non-present properties are not logged + var isNode60 = semver.satisfies(process.version, '6.0 - 6.4'); + + forEach([ + 'Boolean', + 'Number', + 'String', + 'Symbol', + 'Date' + ], function (tag) { + target[Symbol.toStringTag] = tag; + + t.equal( + inspect(fake), + '{ ' + (isNode60 ? '' : 'proxy: true, ') + '[Symbol(Symbol.toStringTag)]: \'' + tag + '\' }', + 'Proxy for + ' + tag + ' shows as the target, which has no slots' + ); + }); + + t.end(); +}); + +test('fakers', { skip: !hasToStringTag }, function (t) { + var target = { proxy: false }; + + forEach([ + 'Boolean', + 'Number', + 'String', + 'Symbol', + 'Date' + ], function (tag) { + target[Symbol.toStringTag] = tag; + + t.equal( + inspect(target), + '{ proxy: false, [Symbol(Symbol.toStringTag)]: \'' + tag + '\' }', + 'Object pretending to be ' + tag + ' does not trick us' + ); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/util.inspect.js b/node_modules/object-inspect/util.inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..7784fab55d08875a01b24636f3a541c3d0bd39b2 --- /dev/null +++ b/node_modules/object-inspect/util.inspect.js @@ -0,0 +1 @@ +module.exports = require('util').inspect; diff --git a/node_modules/object-keys/.editorconfig b/node_modules/object-keys/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..eaa214161f5cdb409c32465fd822624c633a6bd8 --- /dev/null +++ b/node_modules/object-keys/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = tab; +insert_final_newline = true; +quote_type = auto; +space_after_anonymous_functions = true; +space_after_control_statements = true; +spaces_around_operators = true; +trim_trailing_whitespace = true; +spaces_in_brackets = false; +end_of_line = lf; + diff --git a/node_modules/object-keys/.eslintrc b/node_modules/object-keys/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..9a8d5b0e95e3615753a24220256ddc671ac2cedc --- /dev/null +++ b/node_modules/object-keys/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": [2, 23], + "id-length": [2, { "min": 1, "max": 40 }], + "max-params": [2, 3], + "max-statements": [2, 23], + "max-statements-per-line": [2, { "max": 2 }], + "no-extra-parens": [1], + "no-invalid-this": [1], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "LabeledStatement", "WithStatement"], + "operator-linebreak": [2, "after"] + } +} diff --git a/node_modules/object-keys/.travis.yml b/node_modules/object-keys/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..94a6ce42df6f7716665798fab033108ab07f97b1 --- /dev/null +++ b/node_modules/object-keys/.travis.yml @@ -0,0 +1,277 @@ +language: node_js +os: + - linux +node_js: + - "11.8" + - "10.15" + - "9.11" + - "8.15" + - "7.10" + - "6.16" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "11.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true + - env: POSTTEST=true diff --git a/node_modules/object-keys/CHANGELOG.md b/node_modules/object-keys/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..b7d92df248e7c9c53413397b4e4dd50780f7cde8 --- /dev/null +++ b/node_modules/object-keys/CHANGELOG.md @@ -0,0 +1,232 @@ +1.1.1 / 2019-04-06 +================= + * [Fix] exclude deprecated Firefox keys (#53) + +1.1.0 / 2019-02-10 +================= + * [New] [Refactor] move full implementation to `implementation` entry point + * [Refactor] only evaluate the implementation if `Object.keys` is not present + * [Tests] up to `node` `v11.8`, `v10.15`, `v8.15`, `v6.16` + * [Tests] remove jscs + * [Tests] switch to `npm audit` from `nsp` + +1.0.12 / 2018-06-18 +================= + * [Fix] avoid accessing `window.applicationCache`, to avoid issues with latest Chrome on HTTP (#46) + +1.0.11 / 2016-07-05 +================= + * [Fix] exclude keys regarding the style (eg. `pageYOffset`) on `window` to avoid reflow (#32) + +1.0.10 / 2016-07-04 +================= + * [Fix] exclude `height` and `width` keys on `window` to avoid reflow (#31) + * [Fix] In IE 6, `window.external` makes `Object.keys` throw + * [Tests] up to `node` `v6.2`, `v5.10`, `v4.4` + * [Tests] use pretest/posttest for linting/security + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` + * [Dev Deps] remove unused eccheck script + dep + +1.0.9 / 2015-10-19 +================= + * [Fix] Blacklist 'frame' property on window (#16, #17) + * [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` + +1.0.8 / 2015-10-14 +================= + * [Fix] wrap automation equality bug checking in try/catch, per [es5-shim#327](https://github.com/es-shims/es5-shim/issues/327) + * [Fix] Blacklist 'window.frameElement' per [es5-shim#322](https://github.com/es-shims/es5-shim/issues/322) + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + * [Tests] up to `io.js` `v3.3`, `node` `v4.2` + * [Dev Deps] update `eslint`, `tape`, `@ljharb/eslint-config`, `jscs` + +1.0.7 / 2015-07-18 +================= + * [Fix] A proper fix for 176f03335e90d5c8d0d8125a99f27819c9b9cdad / https://github.com/es-shims/es5-shim/issues/275 that doesn't break dontEnum/constructor fixes in IE 8. + * [Fix] Remove deprecation message in Chrome by touching deprecated window properties (#15) + * [Tests] Improve test output for automation equality bugfix + * [Tests] Test on `io.js` `v2.4` + +1.0.6 / 2015-07-09 +================= + * [Fix] Use an object lookup rather than ES5's `indexOf` (#14) + * [Tests] ES3 browsers don't have `Array.isArray` + * [Tests] Fix `no-shadow` rule, as well as an IE 8 bug caused by engine NFE shadowing bugs. + +1.0.5 / 2015-07-03 +================= + * [Fix] Fix a flabbergasting IE 8 bug where `localStorage.constructor.prototype === localStorage` throws + * [Tests] Test up to `io.js` `v2.3` + * [Dev Deps] Update `nsp`, `eslint` + +1.0.4 / 2015-05-23 +================= + * Fix a Safari 5.0 bug with `Object.keys` not working with `arguments` + * Test on latest `node` and `io.js` + * Update `jscs`, `tape`, `eslint`, `nsp`, `is`, `editorconfig-tools`, `covert` + +1.0.3 / 2015-01-06 +================= + * Revert "Make `object-keys` more robust against later environment tampering" to maintain ES3 compliance + +1.0.2 / 2014-12-28 +================= + * Update lots of dev dependencies + * Tweaks to README + * Make `object-keys` more robust against later environment tampering + +1.0.1 / 2014-09-03 +================= + * Update URLs and badges in README + +1.0.0 / 2014-08-26 +================= + * v1.0.0 + +0.6.1 / 2014-08-25 +================= + * v0.6.1 + * Updating dependencies (tape, covert, is) + * Update badges in readme + * Use separate var statements + +0.6.0 / 2014-04-23 +================= + * v0.6.0 + * Updating dependencies (tape, covert) + * Make sure boxed primitives, and arguments objects, work properly in ES3 browsers + * Improve test matrix: test all node versions, but only latest two stables are a failure + * Remove internal foreach shim. + +0.5.1 / 2014-03-09 +================= + * 0.5.1 + * Updating dependencies (tape, covert, is) + * Removing forEach from the module (but keeping it in tests) + +0.5.0 / 2014-01-30 +================= + * 0.5.0 + * Explicitly returning the shim, instead of returning native Object.keys when present + * Adding a changelog. + * Cleaning up IIFE wrapping + * Testing on node 0.4 through 0.11 + +0.4.0 / 2013-08-14 +================== + + * v0.4.0 + * In Chrome 4-10 and Safari 4, typeof (new RegExp) === 'function' + * If it's a string, make sure to use charAt instead of brackets. + * Only use Function#call if necessary. + * Making sure the context tests actually run. + * Better function detection + * Adding the android browser + * Fixing testling files + * Updating tape + * Removing the "is" dependency. + * Making an isArguments shim. + * Adding a local forEach shim and tests. + * Updating paths. + * Moving the shim test. + * v0.3.0 + +0.3.0 / 2013-05-18 +================== + + * README tweak. + * Fixing constructor enum issue. Fixes [#5](https://github.com/ljharb/object-keys/issues/5). + * Adding a test for [#5](https://github.com/ljharb/object-keys/issues/5) + * Updating readme. + * Updating dependencies. + * Giving credit to lodash. + * Make sure that a prototype's constructor property is not enumerable. Fixes [#3](https://github.com/ljharb/object-keys/issues/3). + * Adding additional tests to handle arguments objects, and to skip "prototype" in functions. Fixes [#2](https://github.com/ljharb/object-keys/issues/2). + * Fixing a typo on this test for [#3](https://github.com/ljharb/object-keys/issues/3). + * Adding node 0.10 to travis. + * Adding an IE < 9 test per [#3](https://github.com/ljharb/object-keys/issues/3) + * Adding an iOS 5 mobile Safari test per [#2](https://github.com/ljharb/object-keys/issues/2) + * Moving "indexof" and "is" to be dev dependencies. + * Making sure the shim works with functions. + * Flattening the tests. + +0.2.0 / 2013-05-10 +================== + + * v0.2.0 + * Object.keys should work with arrays. + +0.1.8 / 2013-05-10 +================== + + * v0.1.8 + * Upgrading dependencies. + * Using a simpler check. + * Fixing a bug in hasDontEnumBug browsers. + * Using the newest tape! + * Fixing this error test. + * "undefined" is probably a reserved word in ES3. + * Better test message. + +0.1.7 / 2013-04-17 +================== + + * Upgrading "is" once more. + * The key "null" is breaking some browsers. + +0.1.6 / 2013-04-17 +================== + + * v0.1.6 + * Upgrading "is" + +0.1.5 / 2013-04-14 +================== + + * Bumping version. + * Adding more testling browsers. + * Updating "is" + +0.1.4 / 2013-04-08 +================== + + * Using "is" instead of "is-extended". + +0.1.3 / 2013-04-07 +================== + + * Using "foreach" instead of my own shim. + * Removing "tap"; I'll just wait for "tape" to fix its node 0.10 bug. + +0.1.2 / 2013-04-03 +================== + + * Adding dependency status; moving links to an index at the bottom. + * Upgrading is-extended; version 0.1.2 + * Adding an npm version badge. + +0.1.1 / 2013-04-01 +================== + + * Adding Travis CI. + * Bumping the version. + * Adding indexOf since IE sucks. + * Adding a forEach shim since older browsers don't have Array#forEach. + * Upgrading tape - 0.3.2 uses Array#map + * Using explicit end instead of plan. + * Can't test with Array.isArray in older browsers. + * Using is-extended. + * Fixing testling files. + * JSHint/JSLint-ing. + * Removing an unused object. + * Using strict mode. + +0.1.0 / 2013-03-30 +================== + + * Changing the exports should have meant a higher version bump. + * Oops, fixing the repo URL. + * Adding more tests. + * 0.0.2 + * Merge branch 'export_one_thing'; closes [#1](https://github.com/ljharb/object-keys/issues/1) + * Move shim export to a separate file. diff --git a/node_modules/object-keys/LICENSE b/node_modules/object-keys/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..28553fdd06841b14fea43a5093bea3a5773fe1e0 --- /dev/null +++ b/node_modules/object-keys/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (C) 2013 Jordan Harband + +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. \ No newline at end of file diff --git a/node_modules/object-keys/README.md b/node_modules/object-keys/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ed4c277023a8a48522ec922f35ed27dda62a0ea8 --- /dev/null +++ b/node_modules/object-keys/README.md @@ -0,0 +1,76 @@ +#object-keys [![Version Badge][npm-version-svg]][package-url] + +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +[![browser support][testling-svg]][testling-url] + +An Object.keys shim. Invoke its "shim" method to shim Object.keys if it is unavailable. + +Most common usage: +```js +var keys = Object.keys || require('object-keys'); +``` + +## Example + +```js +var keys = require('object-keys'); +var assert = require('assert'); +var obj = { + a: true, + b: true, + c: true +}; + +assert.deepEqual(keys(obj), ['a', 'b', 'c']); +``` + +```js +var keys = require('object-keys'); +var assert = require('assert'); +/* when Object.keys is not present */ +delete Object.keys; +var shimmedKeys = keys.shim(); +assert.equal(shimmedKeys, keys); +assert.deepEqual(Object.keys(obj), keys(obj)); +``` + +```js +var keys = require('object-keys'); +var assert = require('assert'); +/* when Object.keys is present */ +var shimmedKeys = keys.shim(); +assert.equal(shimmedKeys, Object.keys); +assert.deepEqual(Object.keys(obj), keys(obj)); +``` + +## Source +Implementation taken directly from [es5-shim][es5-shim-url], with modifications, including from [lodash][lodash-url]. + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/object-keys +[npm-version-svg]: http://versionbadg.es/ljharb/object-keys.svg +[travis-svg]: https://travis-ci.org/ljharb/object-keys.svg +[travis-url]: https://travis-ci.org/ljharb/object-keys +[deps-svg]: https://david-dm.org/ljharb/object-keys.svg +[deps-url]: https://david-dm.org/ljharb/object-keys +[dev-deps-svg]: https://david-dm.org/ljharb/object-keys/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/object-keys#info=devDependencies +[testling-svg]: https://ci.testling.com/ljharb/object-keys.png +[testling-url]: https://ci.testling.com/ljharb/object-keys +[es5-shim-url]: https://github.com/es-shims/es5-shim/blob/master/es5-shim.js#L542-589 +[lodash-url]: https://github.com/lodash/lodash +[npm-badge-png]: https://nodei.co/npm/object-keys.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/object-keys.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/object-keys.svg +[downloads-url]: http://npm-stat.com/charts.html?package=object-keys + diff --git a/node_modules/object-keys/implementation.js b/node_modules/object-keys/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..5b329861954977f86c06e1efaf4d30a3f9629a0d --- /dev/null +++ b/node_modules/object-keys/implementation.js @@ -0,0 +1,122 @@ +'use strict'; + +var keysShim; +if (!Object.keys) { + // modified from https://github.com/es-shims/es5-shim + var has = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var isArgs = require('./isArguments'); // eslint-disable-line global-require + var isEnumerable = Object.prototype.propertyIsEnumerable; + var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); + var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); + var dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + var equalsConstructorPrototype = function (o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + var excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + var hasAutomationEqualityBug = (function () { + /* global window */ + if (typeof window === 'undefined') { return false; } + for (var k in window) { + try { + if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }()); + var equalsConstructorPrototypeIfNotBuggy = function (o) { + /* global window */ + if (typeof window === 'undefined' || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; + + keysShim = function keys(object) { + var isObject = object !== null && typeof object === 'object'; + var isFunction = toStr.call(object) === '[object Function]'; + var isArguments = isArgs(object); + var isString = isObject && toStr.call(object) === '[object String]'; + var theKeys = []; + + if (!isObject && !isFunction && !isArguments) { + throw new TypeError('Object.keys called on a non-object'); + } + + var skipProto = hasProtoEnumBug && isFunction; + if (isString && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + + if (isArguments && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === 'prototype') && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; +} +module.exports = keysShim; diff --git a/node_modules/object-keys/index.js b/node_modules/object-keys/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a43807d2f695c7b101bf95a24620227ab00947de --- /dev/null +++ b/node_modules/object-keys/index.js @@ -0,0 +1,32 @@ +'use strict'; + +var slice = Array.prototype.slice; +var isArgs = require('./isArguments'); + +var origKeys = Object.keys; +var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation'); + +var originalKeys = Object.keys; + +keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = (function () { + // Safari 5.0 bug + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2)); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { // eslint-disable-line func-name-matching + if (isArgs(object)) { + return originalKeys(slice.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; +}; + +module.exports = keysShim; diff --git a/node_modules/object-keys/isArguments.js b/node_modules/object-keys/isArguments.js new file mode 100644 index 0000000000000000000000000000000000000000..f2a2a9014d925e99b46c9f776525b02442fb6005 --- /dev/null +++ b/node_modules/object-keys/isArguments.js @@ -0,0 +1,17 @@ +'use strict'; + +var toStr = Object.prototype.toString; + +module.exports = function isArguments(value) { + var str = toStr.call(value); + var isArgs = str === '[object Arguments]'; + if (!isArgs) { + isArgs = str !== '[object Array]' && + value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr.call(value.callee) === '[object Function]'; + } + return isArgs; +}; diff --git a/node_modules/object-keys/package.json b/node_modules/object-keys/package.json new file mode 100644 index 0000000000000000000000000000000000000000..99ea923870ceb9e896828018d22a083dc4e70545 --- /dev/null +++ b/node_modules/object-keys/package.json @@ -0,0 +1,88 @@ +{ + "name": "object-keys", + "version": "1.1.1", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + { + "name": "Raynos", + "email": "raynos2@gmail.com" + }, + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net" + }, + { + "name": "Ivan Starkov", + "email": "istarkov@gmail.com" + }, + { + "name": "Gary Katsevman", + "email": "git@gkatsev.com" + } + ], + "description": "An Object.keys replacement, in case Object.keys is not available. From https://github.com/es-shims/es5-shim", + "license": "MIT", + "main": "index.js", + "scripts": { + "pretest": "npm run --silent lint", + "test": "npm run --silent tests-only", + "posttest": "npm run --silent audit", + "tests-only": "node test/index.js", + "coverage": "covert test/*.js", + "coverage-quiet": "covert test/*.js --quiet", + "lint": "eslint .", + "preaudit": "npm install --package-lock --package-lock-only", + "audit": "npm audit", + "postaudit": "rm package-lock.json" + }, + "repository": { + "type": "git", + "url": "git://github.com/ljharb/object-keys.git" + }, + "keywords": [ + "Object.keys", + "keys", + "ES5", + "shim" + ], + "dependencies": {}, + "devDependencies": { + "@ljharb/eslint-config": "^13.1.1", + "covert": "^1.1.1", + "eslint": "^5.13.0", + "foreach": "^2.0.5", + "indexof": "^0.0.1", + "is": "^3.3.0", + "tape": "^4.9.2" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/object-keys/test/index.js b/node_modules/object-keys/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5402465a19b5b697128197df09d014c791542c51 --- /dev/null +++ b/node_modules/object-keys/test/index.js @@ -0,0 +1,5 @@ +'use strict'; + +require('./isArguments'); + +require('./shim'); diff --git a/node_modules/object.assign/.editorconfig b/node_modules/object.assign/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..bc228f8269443bf772b437890dde7756a3e8a894 --- /dev/null +++ b/node_modules/object.assign/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/object.assign/.eslintrc b/node_modules/object.assign/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..131851698feacc552ca62b379186430f0257b2b0 --- /dev/null +++ b/node_modules/object.assign/.eslintrc @@ -0,0 +1,28 @@ +{ + "root": true, + + "extends": "@ljharb", + + "ignorePatterns": ["dist/"], + + "rules": { + "eqeqeq": [2, "allow-null"], + "id-length": [2, { "min": 1, "max": 30 }], + "max-statements": [2, 33], + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": [1, { "ignore": [0] }], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "no-invalid-this": 1, + "max-lines-per-function": 0, + "max-statements-per-line": [2, { "max": 3 }], + "no-magic-numbers": 0, + }, + }, + ], +} diff --git a/node_modules/object.assign/.github/FUNDING.yml b/node_modules/object.assign/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..ef7fdbfa08a090928219b6ae36796c5d73b4a952 --- /dev/null +++ b/node_modules/object.assign/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/object.assign +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/object.assign/.nycrc b/node_modules/object.assign/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/node_modules/object.assign/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/object.assign/CHANGELOG.md b/node_modules/object.assign/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..509f766dc90e71776ab3af19b422915f887b4c0f --- /dev/null +++ b/node_modules/object.assign/CHANGELOG.md @@ -0,0 +1,246 @@ +4.1.7 / 2024-12-18 +================== + * [Deps] add missing `es-object-atoms` (#86) + +4.1.6 / 2024-12-18 +================== + * [Refactor] use `call-bound` directly; use `es-object-atoms` + * [Deps] update `call-bind`, `has-symbols` + * [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `hasown`, `mock-property`, `ses`, `tape` + * [actions] split out node 10-20, and 20+ + * [actions] remove redundant finisher + * [Tests] replace `aud` with `npm audit` + +4.1.5 / 2023-11-30 +================== + * [meta] republish without testing HTML file (#85) + * [Deps] update `call-bind`, `define-properties` + * [Dev Deps] use `hasown` instead of `has` + * [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `npmignore`, `mock-property`, `tape` + * [actions] update rebase action + +4.1.4 / 2022-08-16 +================== + * [meta] fix `npmignore` integration (#83) + +4.1.3 / 2022-08-05 +================== + * [Refactor] make steps closer to actual spec + * [Refactor] simplify object coercible check + * [readme] remove defunct badges, add coverage and actions badges + * [eslint] ignore coverage output + * [meta] use `npmignore` to autogenerate an npmignore file + * [meta] remove audit-level + * [Deps] update `call-bind`, `define-properties`, `has-symbols` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `aud`, `functions-have-names`, `safe-publish-latest`, `ses`, `tape` + * [actions] use `node/install` instead of `node/run`; use `codecov` action + * [actions] reuse common workflows + * [actions] update codecov uploader + * [Tests] add implementation tests + * [Tests] use `mock-property` + * [Tests] disable posttest pending `aud` handling `file:` deps + * [Tests] migrate remaining tests to Github Actions (#81) + * [Tests] gitignore coverage output + * [Tests] test node v1-v9 on Github Actions instead of travis; resume testing all minors (#80) + +4.1.2 / 2020-10-30 +================== + * [Refactor] use extracted `call-bind` instead of full `es-abstract` + * [Dev Deps] update `eslint`, `ses`, `browserify` + * [Tests] run tests in SES + * [Tests] ses-compat: show error stacks + +4.1.1 / 2020-09-11 +================== + * [Fix] avoid mutating `Object.assign` in modern engines + * [Refactor] use `callBind` from `es-abstract` instead of `function-bind` + * [Deps] update `has-symbols`, `object-keys`, `define-properties` + * [meta] add `funding` field, FUNDING.yml + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `browserify`, `covert`, `for-each`, `is`, `tape`, `functions-have-names`; add `aud`, `safe-publish-latest`; remove `jscs` + * [actions] add Require Allow Edits workflow + * [actions] add automatic rebasing / merge commit blocking + * [Tests] ses-compat - add test to ensure package initializes correctly after ses lockdown (#77) + * [Tests] Add passing test for a source of `window.location` (#68) + * [Tests] use shared travis-ci config + * [Tests] use `npx aud` instead of `npm audit` with hoops or `nsp` + * [Tests] use `functions-have-names` + +4.1.0 / 2017-12-21 +================== + * [New] add `auto` entry point (#52) + * [Refactor] Use `has-symbols` module + * [Deps] update `function-bind`, `object-keys` + * [Dev Deps] update `@es-shims/api`, `browserify`, `nsp`, `eslint`, `@ljharb/eslint-config`, `is` + * [Tests] up to `node` `v9.3`, `v8.9`, `v6.12`; use `nvm install-latest-npm`; pin included builds to LTS + +4.0.4 / 2016-07-04 +================== + * [Fix] Cache original `getOwnPropertySymbols`, and use that when `Object.getOwnPropertySymbols` is unavailable + * [Deps] update `object-keys` + * [Dev Deps] update `eslint`, `get-own-property-symbols`, `core-js`, `jscs`, `nsp`, `browserify`, `@ljharb/eslint-config`, `tape`, `@es-shims/api` + * [Tests] up to `node` `v6.2`, `v5.10`, `v4.4` + * [Tests] run sham tests on node 0.10 + * [Tests] use pretest/posttest for linting/security + +4.0.3 / 2015-10-21 +================== + * [Fix] Support core-js's Symbol sham (#17) + * [Fix] Ensure that properties removed or made non-enumerable during enumeration are not assigned (#16) + * [Fix] Avoid looking up keys and values more than once + * [Tests] Avoid using `reduce` so `npm run test:shams:corejs` passes in `node` `v0.8` ([core-js#122](https://github.com/zloirock/core-js/issues/122)) + * [Tests] Refactor to use my conventional structure that separates shimmed, implementation, and common tests + * [Tests] Create `npm run test:shams` and better organize tests for symbol shams + * [Tests] Remove `nsp` in favor of `requiresafe` + +4.0.2 / 2015-10-20 +================== + * [Fix] Ensure correct property enumeration order, particularly in v8 (#15) + * [Deps] update `object-keys`, `define-properties` + * [Dev Deps] update `browserify`, `is`, `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` + * [Tests] up to `io.js` `v3.3`, `node` `v4.2` + +4.0.1 / 2015-08-16 +================== + * [Docs] Add `Symbol` note to readme + +4.0.0 / 2015-08-15 +================== + * [Breaking] Implement the [es-shim API](es-shims/api). + * [Robustness] Make implementation robust against later modification of environment methods. + * [Refactor] Move implementation to `implementation.js` + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + * [Deps] update `object-keys`, `define-properties` + * [Dev Deps] update `browserify`, `tape`, `eslint`, `jscs`, `browserify` + * [Tests] Add `npm run tests-only` + * [Tests] use my personal shared `eslint` config. + * [Tests] up to `io.js` `v3.0` + +3.0.1 / 2015-06-28 +================== + * Cache `Object` and `Array#push` to make the shim more robust. + * [Fix] Remove use of `Array#filter`, which isn't in ES3. + * [Deps] Update `object-keys`, `define-properties` + * [Dev Deps] Update `get-own-property-symbols`, `browserify`, `eslint`, `nsp` + * [Tests] Test up to `io.js` `v2.3` + * [Tests] Adding `Object.assign` tests for non-object targets, per https://github.com/paulmillr/es6-shim/issues/348 + +3.0.0 / 2015-05-20 +================== + * Attempt to feature-detect Symbols, even if `typeof Symbol() !== 'symbol'` (#12) + * Make a separate `hasSymbols` internal module + * Update `browserify`, `eslint` + +2.0.3 / 2015-06-28 +================== + * Cache `Object` and `Array#push` to make the shim more robust. + * [Fix] Remove use of `Array#filter`, which isn't in ES3 + * [Deps] Update `object-keys`, `define-properties` + * [Dev Deps] Update `browserify`, `nsp`, `eslint` + * [Tests] Test up to `io.js` `v2.3` + +2.0.2 / 2015-05-20 +================== + * Make sure `.shim` is non-enumerable. + * Refactor `.shim` implementation to use `define-properties` predicates, rather than `delete`ing the original. + * Update docs to match spec/implementation. (#11) + * Add `npm run eslint` + * Test up to `io.js` `v2.0` + * Update `jscs`, `browserify`, `covert` + +2.0.1 / 2015-04-12 +================== + * Make sure non-enumerable Symbols are excluded. + +2.0.0 / 2015-04-12 +================== + * Make sure the shim function overwrites a broken implementation with pending exceptions. + * Ensure shim is not enumerable using `define-properties` + * Ensure `Object.assign` includes symbols. + * All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. + * Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. + * Add `npm run security` via `nsp` + * Update `browserify`, `jscs`, `tape`, `object-keys`, `is` + +1.1.1 / 2014-12-14 +================== + * Actually include the browser build in `npm` + +1.1.0 / 2014-12-14 +================== + * Add `npm run build`, and build an automatic-shimming browser distribution as part of the npm publish process. + * Update `is`, `jscs` + +1.0.3 / 2014-11-29 +================== + * Revert "optimize --production installs" + +1.0.2 / 2014-11-27 +================== + * Update `jscs`, `is`, `object-keys`, `tape` + * Add badges to README + * Name URLs in README + * Lock `covert` to `v1.0.0` + * Optimize --production installs + +1.0.1 / 2014-08-26 +================== + * Update `is`, `covert` + +1.0.0 / 2014-08-07 +================== + * Update `object-keys`, `tape` + +0.5.0 / 2014-07-31 +================== + * Object.assign no longer throws on null or undefined sources, per https://bugs.ecmascript.org/show_bug.cgi?id=3096 + +0.4.3 / 2014-07-30 +================== + * Don’t modify vars in the function signature, since it deoptimizes v8 + +0.4.2 / 2014-07-30 +================== + * Fixing the version number: v0.4.2 + +0.4.1 / 2014-07-19 +================== + * Revert "Use the native Object.keys if it’s available." + +0.4.0 / 2014-07-19 +================== + * Use the native Object.keys if it’s available. + * Fixes [#2](https://github.com/ljharb/object.assign/issues/2). + * Adding failing tests for [#2](https://github.com/ljharb/object.assign/issues/2). + * Fix indentation. + * Adding `npm run lint` + * Update `tape`, `covert` + * README: Use SVG badge for Travis [#1](https://github.com/ljharb/object.assign/issues/1) from mathiasbynens/patch-1 + +0.3.1 / 2014-04-10 +================== + * Object.assign does partially modify objects if it throws, per https://twitter.com/awbjs/status/454320863093862400 + +0.3.0 / 2014-04-10 +================== + * Update with newest ES6 behavior - Object.assign now takes a variable number of source objects. + * Update `tape` + * Make sure old and unstable nodes don’t fail Travis + +0.2.1 / 2014-03-16 +================== + * Let object-keys handle the fallback + * Update dependency badges + * Adding bower.json + +0.2.0 / 2014-03-16 +================== + * Use a for loop, because ES3 browsers don’t have "reduce" + +0.1.1 / 2014-03-14 +================== + * Updating readme + +0.1.0 / 2014-03-14 +================== + * Initial release. + diff --git a/node_modules/object.assign/LICENSE b/node_modules/object.assign/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ab29cbd63b72d5d30b0cc92162db190f2e4b9a36 --- /dev/null +++ b/node_modules/object.assign/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +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. \ No newline at end of file diff --git a/node_modules/object.assign/README.md b/node_modules/object.assign/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8e933fee6260157922ea8ebd8f46795e030d6df4 --- /dev/null +++ b/node_modules/object.assign/README.md @@ -0,0 +1,136 @@ +# object.assign [![Version Badge][npm-version-svg]][npm-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][npm-url] + +An Object.assign shim. Invoke its "shim" method to shim Object.assign if it is unavailable. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-object.assign). In an ES6 environment, it will also work properly with `Symbol`s. + +Takes a minimum of 2 arguments: `target` and `source`. +Takes a variable sized list of source arguments - at least 1, as many as you want. +Throws a TypeError if the `target` argument is `null` or `undefined`. + +Most common usage: +```js +var assign = require('object.assign').getPolyfill(); // returns native method if compliant + /* or */ +var assign = require('object.assign/polyfill')(); // returns native method if compliant +``` + +## Example + +```js +var assert = require('assert'); + +// Multiple sources! +var target = { a: true }; +var source1 = { b: true }; +var source2 = { c: true }; +var sourceN = { n: true }; + +var expected = { + a: true, + b: true, + c: true, + n: true +}; + +assign(target, source1, source2, sourceN); +assert.deepEqual(target, expected); // AWESOME! +``` + +```js +var target = { + a: true, + b: true, + c: true +}; +var source1 = { + c: false, + d: false +}; +var sourceN = { + e: false +}; + +var assigned = assign(target, source1, sourceN); +assert.equal(target, assigned); // returns the target object +assert.deepEqual(assigned, { + a: true, + b: true, + c: false, + d: false, + e: false +}); +``` + +```js +/* when Object.assign is not present */ +delete Object.assign; +var shimmedAssign = require('object.assign').shim(); + /* or */ +var shimmedAssign = require('object.assign/shim')(); + +assert.equal(shimmedAssign, assign); + +var target = { + a: true, + b: true, + c: true +}; +var source = { + c: false, + d: false, + e: false +}; + +var assigned = assign(target, source); +assert.deepEqual(Object.assign(target, source), assign(target, source)); +``` + +```js +/* when Object.assign is present */ +var shimmedAssign = require('object.assign').shim(); +assert.equal(shimmedAssign, Object.assign); + +var target = { + a: true, + b: true, + c: true +}; +var source = { + c: false, + d: false, + e: false +}; + +assert.deepEqual(Object.assign(target, source), assign(target, source)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[npm-url]: https://npmjs.org/package/object.assign +[npm-version-svg]: http://versionbadg.es/ljharb/object.assign.svg +[travis-svg]: https://travis-ci.org/ljharb/object.assign.svg +[travis-url]: https://travis-ci.org/ljharb/object.assign +[deps-svg]: https://david-dm.org/ljharb/object.assign.svg?theme=shields.io +[deps-url]: https://david-dm.org/ljharb/object.assign +[dev-deps-svg]: https://david-dm.org/ljharb/object.assign/dev-status.svg?theme=shields.io +[dev-deps-url]: https://david-dm.org/ljharb/object.assign#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/object.assign.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/object.assign.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/object.assign.svg +[downloads-url]: http://npm-stat.com/charts.html?package=object.assign +[codecov-image]: https://codecov.io/gh/ljharb/object.assign/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/object.assign/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/object.assign +[actions-url]: https://github.com/ljharb/object.assign/actions diff --git a/node_modules/object.assign/auto.js b/node_modules/object.assign/auto.js new file mode 100644 index 0000000000000000000000000000000000000000..8ebf606cb02ff3a8c6ef786afa37d21a19254f46 --- /dev/null +++ b/node_modules/object.assign/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/node_modules/object.assign/hasSymbols.js b/node_modules/object.assign/hasSymbols.js new file mode 100644 index 0000000000000000000000000000000000000000..34841e01199eb2cc5e607665b22679da2eeb6a43 --- /dev/null +++ b/node_modules/object.assign/hasSymbols.js @@ -0,0 +1,43 @@ +'use strict'; + +var keys = require('object-keys'); + +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + /* + * temp disabled per https://github.com/ljharb/object.assign/issues/17 + * if (sym instanceof Symbol) { return false; } + * temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + * if (!(symObj instanceof Symbol)) { return false; } + */ + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-unreachable-loop + if (keys(obj).length !== 0) { return false; } + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; diff --git a/node_modules/object.assign/implementation.js b/node_modules/object.assign/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..4f4b4256f57ecb9478548853ad4cb61ec98cbbe8 --- /dev/null +++ b/node_modules/object.assign/implementation.js @@ -0,0 +1,46 @@ +'use strict'; + +// modified from https://github.com/es-shims/es6-shim +var objectKeys = require('object-keys'); +var hasSymbols = require('has-symbols/shams')(); +var callBound = require('call-bound'); +var $Object = require('es-object-atoms'); +var $push = callBound('Array.prototype.push'); +var $propIsEnumerable = callBound('Object.prototype.propertyIsEnumerable'); +var originalGetSymbols = hasSymbols ? $Object.getOwnPropertySymbols : null; + +// eslint-disable-next-line no-unused-vars +module.exports = function assign(target, source1) { + if (target == null) { throw new TypeError('target must be an object'); } + var to = $Object(target); // step 1 + if (arguments.length === 1) { + return to; // step 2 + } + for (var s = 1; s < arguments.length; ++s) { + var from = $Object(arguments[s]); // step 3.a.i + + // step 3.a.ii: + var keys = objectKeys(from); + var getSymbols = hasSymbols && ($Object.getOwnPropertySymbols || originalGetSymbols); + if (getSymbols) { + var syms = getSymbols(from); + for (var j = 0; j < syms.length; ++j) { + var key = syms[j]; + if ($propIsEnumerable(from, key)) { + $push(keys, key); + } + } + } + + // step 3.a.iii: + for (var i = 0; i < keys.length; ++i) { + var nextKey = keys[i]; + if ($propIsEnumerable(from, nextKey)) { // step 3.a.iii.2 + var propValue = from[nextKey]; // step 3.a.iii.2.a + to[nextKey] = propValue; // step 3.a.iii.2.b + } + } + } + + return to; // step 4 +}; diff --git a/node_modules/object.assign/index.js b/node_modules/object.assign/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9b50603769174865159dd05b178f9f18d890d63a --- /dev/null +++ b/node_modules/object.assign/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var defineProperties = require('define-properties'); +var callBind = require('call-bind'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var polyfill = callBind.apply(getPolyfill()); +// eslint-disable-next-line no-unused-vars +var bound = function assign(target, source1) { + return polyfill(Object, arguments); +}; + +defineProperties(bound, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = bound; diff --git a/node_modules/object.assign/package.json b/node_modules/object.assign/package.json new file mode 100644 index 0000000000000000000000000000000000000000..996fee0cd4b5ab41d7c1da5812adacdaadecb8e4 --- /dev/null +++ b/node_modules/object.assign/package.json @@ -0,0 +1,96 @@ +{ + "name": "object.assign", + "version": "4.1.7", + "author": "Jordan Harband", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "ES6 spec-compliant Object.assign shim. From https://github.com/es-shims/es6-shim", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "pretest": "npm run lint && es-shim-api --bound", + "test": "npm run tests-only && npm run test:ses", + "posttest": "npx npm@'>=10.2' audit --production", + "tests-only": "npm run test:implementation && npm run test:shim", + "test:native": "nyc node test/native", + "test:shim": "nyc node test/shimmed", + "test:implementation": "nyc node test", + "test:ses": "node test/ses-compat", + "lint": "eslint .", + "build": "mkdir -p dist && browserify browserShim.js > dist/browser.js", + "prepublishOnly": "safe-publish-latest && npm run build", + "prepublish": "not-in-publish || npm run prepublishOnly" + }, + "repository": { + "type": "git", + "url": "git://github.com/ljharb/object.assign.git" + }, + "keywords": [ + "Object.assign", + "assign", + "ES6", + "extend", + "$.extend", + "jQuery", + "_.extend", + "Underscore", + "es-shim API", + "polyfill", + "shim" + ], + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "devDependencies": { + "@es-shims/api": "^2.5.1", + "@ljharb/eslint-config": "^21.1.1", + "browserify": "^16.5.2", + "eslint": "=8.8.0", + "for-each": "^0.3.3", + "functions-have-names": "^1.2.3", + "has-strict-mode": "^1.0.1", + "hasown": "^2.0.2", + "mock-property": "^1.1.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "ses": "^1.10.0", + "tape": "^5.9.0" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "bower.json", + "browserShim.js", + "!dist/" + ] + } +} diff --git a/node_modules/object.assign/polyfill.js b/node_modules/object.assign/polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..ca94aea9ba30d7435bb481b8f8bfb098a9f007c0 --- /dev/null +++ b/node_modules/object.assign/polyfill.js @@ -0,0 +1,55 @@ +'use strict'; + +var implementation = require('./implementation'); + +var lacksProperEnumerationOrder = function () { + if (!Object.assign) { + return false; + } + /* + * v8, specifically in node 4.x, has a bug with incorrect property enumeration order + * note: this does not detect the bug unless there's 20 characters + */ + var str = 'abcdefghijklmnopqrst'; + var letters = str.split(''); + var map = {}; + for (var i = 0; i < letters.length; ++i) { + map[letters[i]] = letters[i]; + } + var obj = Object.assign({}, map); + var actual = ''; + for (var k in obj) { + actual += k; + } + return str !== actual; +}; + +var assignHasPendingExceptions = function () { + if (!Object.assign || !Object.preventExtensions) { + return false; + } + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: 2 }); + try { + Object.assign(thrower, 'xy'); + } catch (e) { + return thrower[1] === 'y'; + } + return false; +}; + +module.exports = function getPolyfill() { + if (!Object.assign) { + return implementation; + } + if (lacksProperEnumerationOrder()) { + return implementation; + } + if (assignHasPendingExceptions()) { + return implementation; + } + return Object.assign; +}; diff --git a/node_modules/object.assign/shim.js b/node_modules/object.assign/shim.js new file mode 100644 index 0000000000000000000000000000000000000000..9f896ae3cf90a39f574d789020c40cda3eb4e9bf --- /dev/null +++ b/node_modules/object.assign/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var define = require('define-properties'); +var getPolyfill = require('./polyfill'); + +module.exports = function shimAssign() { + var polyfill = getPolyfill(); + define( + Object, + { assign: polyfill }, + { assign: function () { return Object.assign !== polyfill; } } + ); + return polyfill; +}; diff --git a/node_modules/object.assign/test/implementation.js b/node_modules/object.assign/test/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..05d7d7ada705b5518cf0827899513f46e1e8751e --- /dev/null +++ b/node_modules/object.assign/test/implementation.js @@ -0,0 +1,19 @@ +'use strict'; + +var implementation = require('../implementation'); +var callBind = require('call-bind'); +var test = require('tape'); +var hasStrictMode = require('has-strict-mode')(); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad first arg/receiver', { skip: !hasStrictMode }, function (st) { + st['throws'](function () { implementation(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { implementation(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(callBind(implementation, Object), t); + + t.end(); +}); diff --git a/node_modules/object.assign/test/index.js b/node_modules/object.assign/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..776b2b3342e636b0c172d9192111cf7c37888454 --- /dev/null +++ b/node_modules/object.assign/test/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var assign = require('../'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', function (st) { + st['throws'](function () { assign(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { assign(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(assign, t); + + t.end(); +}); diff --git a/node_modules/object.assign/test/native.js b/node_modules/object.assign/test/native.js new file mode 100644 index 0000000000000000000000000000000000000000..49a70f7987691ee4b0f6193b434b83d4c97699b5 --- /dev/null +++ b/node_modules/object.assign/test/native.js @@ -0,0 +1,49 @@ +'use strict'; + +var test = require('tape'); +var defineProperties = require('define-properties'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); + +var runTests = require('./tests'); + +test('native', function (t) { + t.equal(Object.assign.length, 2, 'Object.assign has a length of 2'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(Object.assign.name, 'assign', 'Object.assign has name "assign"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(Object, 'assign'), 'Object.assign is not enumerable'); + et.end(); + }); + + var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); + + t.test('bad object value', { skip: !supportsStrictMode }, function (st) { + st['throws'](function () { return Object.assign(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return Object.assign(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + // v8 in node 0.8 and 0.10 have non-enumerable string properties + var stringCharsAreEnumerable = isEnumerable.call('xy', 0); + t.test('when Object.assign is present and has pending exceptions', { skip: !stringCharsAreEnumerable || !Object.preventExtensions }, function (st) { + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: '2' }); + var error; + try { Object.assign(thrower, 'xy'); } catch (e) { error = e; } + st.equal(error instanceof TypeError, true, 'error is TypeError'); + st.equal(thrower[1], '2', 'thrower[1] === "2"'); + + st.end(); + }); + + runTests(Object.assign, t); + + t.end(); +}); diff --git a/node_modules/object.assign/test/ses-compat.js b/node_modules/object.assign/test/ses-compat.js new file mode 100644 index 0000000000000000000000000000000000000000..9669eb9a98e3931ad02a22b6a834e28f7234489e --- /dev/null +++ b/node_modules/object.assign/test/ses-compat.js @@ -0,0 +1,12 @@ +'use strict'; + +/* globals lockdown */ + +// requiring ses exposes "lockdown" on the global +require('ses'); + +// lockdown freezes the primordials +lockdown({ errorTaming: 'unsafe' }); + +// initialize the module +require('./'); diff --git a/node_modules/object.assign/test/shimmed.js b/node_modules/object.assign/test/shimmed.js new file mode 100644 index 0000000000000000000000000000000000000000..ee577587a8961307b30651c9bfe56559eccc5c54 --- /dev/null +++ b/node_modules/object.assign/test/shimmed.js @@ -0,0 +1,52 @@ +'use strict'; + +var assign = require('../'); +assign.shim(); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); + +var runTests = require('./tests'); + +test('shimmed', function (t) { + t.equal(Object.assign.length, 2, 'Object.assign has a length of 2'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(Object.assign.name, 'assign', 'Object.assign has name "assign"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(Object, 'assign'), 'Object.assign is not enumerable'); + et.end(); + }); + + var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); + + t.test('bad object value', { skip: !supportsStrictMode }, function (st) { + st['throws'](function () { return Object.assign(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return Object.assign(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + // v8 in node 0.8 and 0.10 have non-enumerable string properties + var stringCharsAreEnumerable = isEnumerable.call('xy', 0); + t.test('when Object.assign is present and has pending exceptions', { skip: !stringCharsAreEnumerable || !Object.preventExtensions }, function (st) { + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: '2' }); + var error; + try { Object.assign(thrower, 'xy'); } catch (e) { error = e; } + st.equal(error instanceof TypeError, true, 'error is TypeError'); + st.equal(thrower[1], '2', 'thrower[1] === "2"'); + + st.end(); + }); + + runTests(Object.assign, t); + + t.end(); +}); diff --git a/node_modules/object.assign/test/tests.js b/node_modules/object.assign/test/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..eff2793d3000ccfd92f3a8f18ec0f85518369f90 --- /dev/null +++ b/node_modules/object.assign/test/tests.js @@ -0,0 +1,232 @@ +'use strict'; + +var hasSymbols = require('has-symbols/shams')(); +var forEach = require('for-each'); +var hasOwn = require('hasown'); +var mockProperty = require('mock-property'); + +module.exports = function (assign, t) { + t.test('error cases', function (st) { + st['throws'](function () { assign(null); }, TypeError, 'target must be an object'); + st['throws'](function () { assign(undefined); }, TypeError, 'target must be an object'); + st['throws'](function () { assign(null, {}); }, TypeError, 'target must be an object'); + st['throws'](function () { assign(undefined, {}); }, TypeError, 'target must be an object'); + st.end(); + }); + + t.test('non-object target, no sources', function (st) { + var bool = assign(true); + st.equal(typeof bool, 'object', 'bool is object'); + st.equal(Boolean.prototype.valueOf.call(bool), true, 'bool coerces to `true`'); + + var number = assign(1); + st.equal(typeof number, 'object', 'number is object'); + st.equal(Number.prototype.valueOf.call(number), 1, 'number coerces to `1`'); + + var string = assign('1'); + st.equal(typeof string, 'object', 'number is object'); + st.equal(String.prototype.valueOf.call(string), '1', 'number coerces to `"1"`'); + + st.end(); + }); + + t.test('non-object target, with sources', function (st) { + var signal = {}; + + st.test('boolean', function (st2) { + var bool = assign(true, { a: signal }); + st2.equal(typeof bool, 'object', 'bool is object'); + st2.equal(Boolean.prototype.valueOf.call(bool), true, 'bool coerces to `true`'); + st2.equal(bool.a, signal, 'source properties copied'); + st2.end(); + }); + + st.test('number', function (st2) { + var number = assign(1, { a: signal }); + st2.equal(typeof number, 'object', 'number is object'); + st2.equal(Number.prototype.valueOf.call(number), 1, 'number coerces to `1`'); + st2.equal(number.a, signal, 'source properties copied'); + st2.end(); + }); + + st.test('string', function (st2) { + var string = assign('1', { a: signal }); + st2.equal(typeof string, 'object', 'number is object'); + st2.equal(String.prototype.valueOf.call(string), '1', 'number coerces to `"1"`'); + st2.equal(string.a, signal, 'source properties copied'); + st2.end(); + }); + + st.end(); + }); + + t.test('non-object sources', function (st) { + st.deepEqual(assign({ a: 1 }, null, { b: 2 }), { a: 1, b: 2 }, 'ignores null source'); + st.deepEqual(assign({ a: 1 }, { b: 2 }, undefined), { a: 1, b: 2 }, 'ignores undefined source'); + st.end(); + }); + + t.test('returns the modified target object', function (st) { + var target = {}; + var returned = assign(target, { a: 1 }); + st.equal(returned, target, 'returned object is the same reference as the target object'); + st.end(); + }); + + t.test('has the right length', function (st) { + st.equal(assign.length, 2, 'length is 2 => 2 required arguments'); + st.end(); + }); + + t.test('merge two objects', function (st) { + var target = { a: 1 }; + var returned = assign(target, { b: 2 }); + st.deepEqual(returned, { a: 1, b: 2 }, 'returned object has properties from both'); + st.end(); + }); + + t.test('works with functions', function (st) { + var target = function () {}; + target.a = 1; + var returned = assign(target, { b: 2 }); + st.equal(target, returned, 'returned object is target'); + st.equal(returned.a, 1); + st.equal(returned.b, 2); + st.end(); + }); + + t.test('works with primitives', function (st) { + var target = 2; + var source = { b: 42 }; + var returned = assign(target, source); + st.equal(Object.prototype.toString.call(returned), '[object Number]', 'returned is object form of number primitive'); + st.equal(Number(returned), target, 'returned and target have same valueOf'); + st.equal(returned.b, source.b); + st.end(); + }); + + /* globals window */ + t.test('works with window.location', { skip: typeof window === 'undefined' }, function (st) { + var target = {}; + assign(target, window.location); + for (var prop in window.location) { + if (hasOwn(window.location, prop)) { + st.deepEqual(target[prop], window.location[prop], prop + ' is copied'); + } + } + st.end(); + }); + + t.test('merge N objects', function (st) { + var target = { a: 1 }; + var source1 = { b: 2 }; + var source2 = { c: 3 }; + var returned = assign(target, source1, source2); + st.deepEqual(returned, { a: 1, b: 2, c: 3 }, 'returned object has properties from all sources'); + st.end(); + }); + + t.test('only iterates over own keys', function (st) { + var Foo = function () {}; + Foo.prototype.bar = true; + var foo = new Foo(); + foo.baz = true; + var target = { a: 1 }; + var returned = assign(target, foo); + st.equal(returned, target, 'returned object is the same reference as the target object'); + st.deepEqual(target, { a: 1, baz: true }, 'returned object has only own properties from both'); + st.end(); + }); + + t.test('includes enumerable symbols, after keys', { skip: !hasSymbols }, function (st) { + var visited = []; + var obj = {}; + Object.defineProperty(obj, 'a', { enumerable: true, get: function () { visited.push('a'); return 42; } }); + var symbol = Symbol('enumerable'); + Object.defineProperty(obj, symbol, { + enumerable: true, + get: function () { visited.push(symbol); return Infinity; } + }); + var nonEnumSymbol = Symbol('non-enumerable'); + Object.defineProperty(obj, nonEnumSymbol, { + enumerable: false, + get: function () { visited.push(nonEnumSymbol); return -Infinity; } + }); + var target = assign({}, obj); + st.deepEqual(visited, ['a', symbol], 'key is visited first, then symbol'); + st.equal(target.a, 42, 'target.a is 42'); + st.equal(target[symbol], Infinity, 'target[symbol] is Infinity'); + st.notEqual(target[nonEnumSymbol], -Infinity, 'target[nonEnumSymbol] is not -Infinity'); + st.end(); + }); + + t.test('does not fail when symbols are not present', { skip: !Object.isFrozen || Object.isFrozen(Object) }, function (st) { + st.teardown(mockProperty(Object, 'getOwnPropertySymbols', { 'delete': true })); + + var visited = []; + var obj = {}; + Object.defineProperty(obj, 'a', { enumerable: true, get: function () { visited.push('a'); return 42; } }); + var keys = ['a']; + if (hasSymbols) { + var symbol = Symbol('sym'); + Object.defineProperty(obj, symbol, { + enumerable: true, + get: function () { visited.push(symbol); return Infinity; } + }); + keys.push(symbol); + } + var target = assign({}, obj); + st.deepEqual(visited, keys, 'assign visits expected keys'); + st.equal(target.a, 42, 'target.a is 42'); + + if (hasSymbols) { + st.equal(target[symbol], Infinity); + } + st.end(); + }); + + t.test('preserves correct property enumeration order', function (st) { + var str = 'abcdefghijklmnopqrst'; + var letters = {}; + forEach(str.split(''), function (letter) { + letters[letter] = letter; + }); + + var n = 5; + st.comment('run the next test ' + n + ' times'); + var object = assign({}, letters); + var actual = ''; + for (var k in object) { + actual += k; + } + for (var i = 0; i < n; ++i) { + st.equal(actual, str, 'property enumeration order should be followed'); + } + st.end(); + }); + + t.test('checks enumerability and existence, in case of modification during [[Get]]', { skip: !Object.defineProperty }, function (st) { + var targetBvalue = {}; + var targetCvalue = {}; + var target = { b: targetBvalue, c: targetCvalue }; + var source = {}; + Object.defineProperty(source, 'a', { + enumerable: true, + get: function () { + delete this.b; + Object.defineProperty(this, 'c', { enumerable: false }); + return 'a'; + } + }); + var sourceBvalue = {}; + var sourceCvalue = {}; + source.b = sourceBvalue; + source.c = sourceCvalue; + var result = assign(target, source); + st.equal(result, target, 'sanity check: result is === target'); + st.equal(result.b, targetBvalue, 'target key not overwritten by deleted source key'); + st.equal(result.c, targetCvalue, 'target key not overwritten by non-enumerable source key'); + + st.end(); + }); +}; diff --git a/node_modules/obug/LICENSE b/node_modules/obug/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..12eb1480b950f145a3ef976671da3337d621e5b8 --- /dev/null +++ b/node_modules/obug/LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright © 2025-PRESENT Kevin Deng (https://github.com/sxzz) +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon + +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. diff --git a/node_modules/obug/README.md b/node_modules/obug/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ae9d9fc3f4d137fa95c1c791ed1975716b4daec3 --- /dev/null +++ b/node_modules/obug/README.md @@ -0,0 +1,251 @@ +# obug + +[![npm version][npm-version-src]][npm-version-href] +[![npm downloads][npm-downloads-src]][npm-downloads-href] +[![JSR][jsr-badge-src]][jsr-badge-href] +[![Unit Test][unit-test-src]][unit-test-href] + +A lightweight JavaScript debugging utility, forked from [debug](https://www.npmjs.com/package/debug), featuring TypeScript and ESM support. + +> [!NOTE] +> obug v1 retains most of the compatibility with [debug](https://github.com/debug-js/debug), but drops support for older browsers and Node.js, making it a drop-in replacement. +> +> obug v2 refactors some API imports and usage for better support of ESM and TypeScript, easier customization, and an even smaller package size. + +## Key Differences from `debug` + +- ✨ Minimal footprint + - 7.7 kB package size + - 1.4 KB minified + gzipped for browsers +- 📦 Zero dependencies +- 📝 Full TypeScript support +- 🚀 Native ESM compatibility +- 🌐 Optimized for modern runtimes + - ES2015+ browsers + - Modern Node.js versions +- 🎨 Customizable formatting + +## Installation + +```bash +npm install obug +``` + +## Usage + +```ts +import { createDebug, disable, enable, enabled, namespaces } from 'obug' + +// Get the currently enabled namespaces +console.log(namespaces()) + +const debug = createDebug('my-namespace', { + // All options are optional + + useColors: true, // false, true, undefined for auto-detect + color: 2, // custom color + // custom formatArgs + formatArgs(args) {}, + formatters: {}, + // Node.js only + inspectOpts: {}, + + // custom log + log: console.log, +}) + +debug('This is a debug message') +console.log( + debug.namespace, // 'my-namespace' + debug.enabled, // Check if enabled + debug.useColors, // true + debug.color, // 2 + debug.formatArgs, // custom formatArgs + debug.formatters, // {} + debug.inspectOpts, // {} + debug.log, // implemented log function +) + +// Create a sub-namespace, and it will inherit options from the parent debugger +const sub = debug.extend('sub-namespace') +sub('This is a sub-namespace debug message') +console.log(sub.namespace) // 'my-namespace:sub-namespace' +``` + +## How to use + +### Enabling debug output + +obug picks up enabled namespaces from the `DEBUG` environment variable in Node.js, or from `localStorage.debug` in browsers. + +In Node.js: + +```bash +DEBUG=app:* node app.js +``` + +On Windows (CMD): + +```cmd +set DEBUG=app:* & node app.js +``` + +On Windows (PowerShell): + +```powershell +$env:DEBUG='app:*'; node app.js +``` + +In the browser, set the value in DevTools and refresh the page: + +```js +localStorage.debug = 'app:*' +``` + +### Wildcards and exclusion + +The `*` character is a wildcard. Suppose your library has debuggers named `connect:bodyParser`, `connect:compress`, and `connect:session` — instead of listing each one, use `DEBUG=connect:*`. Use `DEBUG=*` to enable everything. + +Exclude namespaces by prefixing them with `-`: + +```bash +DEBUG=*,-connect:* node app.js +``` + +### Namespace conventions + +If you're using obug in a library, prefix your namespaces with the library name and use `:` to separate features (e.g. `connect:bodyParser`). This lets users opt into the parts they care about without guessing names. + +### Extending a namespace + +Use `.extend()` to create a sub-namespace that inherits options from its parent: + +```ts +const log = createDebug('auth') +const logSign = log.extend('sign') // 'auth:sign' +const logLogin = log.extend('login') // 'auth:login' + +log('hello') // auth hello +logSign('hello') // auth:sign hello +logLogin('hello') // auth:login hello +``` + +### Formatters + +obug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Built-in formatters: + +| Formatter | Representation | +| --------- | -------------------------------------------------- | +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%%` | Single percent sign. Does not consume an argument. | + +Other format specifiers supported by Node's `util.format` (`%s`, `%d`, `%j`, …) and the browser console pass through to the underlying logger. + +#### Custom formatters + +Register custom formatters via the `formatters` option. For example, to render a `Buffer` as hex with `%h`: + +```ts +const debug = createDebug('foo', { + formatters: { + h: (v) => v.toString('hex'), + }, +}) + +debug('this is hex: %h', Buffer.from('hello world')) +// foo this is hex: 68656c6c6f20776f726c64 +0ms +``` + +### Dynamic enable / disable + +You can toggle namespaces at runtime: + +```ts +import { disable, enable, enabled, namespaces } from 'obug' + +enable('app:*') +console.log(enabled('app:server')) // true + +const previous = disable() +console.log(enabled('app:server')) // false + +// Restore later +enable(previous) +``` + +`namespaces()` returns the string of currently enabled namespaces. Note that calling `enable()` overrides the value initially read from `DEBUG`. + +### Checking whether a debugger is enabled + +Guard expensive work behind the `enabled` property: + +```ts +const debug = createDebug('http') + +if (debug.enabled) { + // expensive computation only when enabled +} +``` + +You can also force the state by assigning to `debug.enabled` directly. + +### Custom output + +By default, obug writes to `stderr` in Node.js and to the console in browsers. Override the `log` option to redirect output per-namespace: + +```ts +const log = createDebug('app:log', { + log: console.log, +}) + +const error = createDebug('app:error') // still goes to stderr +``` + +### Environment variables (Node.js) + +| Name | Purpose | +| ------------------- | ----------------------------------------------- | +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | +| `DEBUG_COLORS` | Whether to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + +Variables prefixed with `DEBUG_` are converted to camelCase keys on the options object passed to Node's [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the `%o` / `%O` formatters. + +## Original Authors + +As obug is a fork of debug with significant modifications, we would like to acknowledge the original authors: + +- TJ Holowaychuk +- Nathan Rajlich +- Andrew Rhyne +- Josh Junon + +## Sponsors + +

+ + + +

+ +## License + +[MIT](./LICENSE) License © 2025-PRESENT [Kevin Deng](https://github.com/sxzz) + +[The MIT License](./LICENSE) Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> + +[The MIT License](./LICENSE) Copyright (c) 2018-2021 Josh Junon + + + +[npm-version-src]: https://img.shields.io/npm/v/obug.svg +[npm-version-href]: https://npmjs.com/package/obug +[npm-downloads-src]: https://img.shields.io/npm/dm/obug +[npm-downloads-href]: https://www.npmcharts.com/compare/obug?interval=30 +[unit-test-src]: https://github.com/sxzz/obug/actions/workflows/unit-test.yml/badge.svg +[unit-test-href]: https://github.com/sxzz/obug/actions/workflows/unit-test.yml +[jsr-badge-src]: https://jsr.io/badges/@sxzz/obug +[jsr-badge-href]: https://jsr.io/@sxzz/obug diff --git a/node_modules/obug/package.json b/node_modules/obug/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a42bed1869349aa4171f2ffa34e2e814041449b2 --- /dev/null +++ b/node_modules/obug/package.json @@ -0,0 +1,73 @@ +{ + "name": "obug", + "type": "module", + "version": "2.1.3", + "description": "A lightweight JavaScript debugging utility, forked from debug, featuring TypeScript and ESM support.", + "author": "Kevin Deng ", + "license": "MIT", + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "homepage": "https://github.com/sxzz/obug#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/sxzz/obug.git" + }, + "bugs": { + "url": "https://github.com/sxzz/obug/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "browser": "./dist/browser.js", + "default": "./dist/node.js" + }, + "./package.json": "./package.json" + }, + "main": "./dist/node.js", + "module": "./dist/node.js", + "unpkg": "./dist/browser.min.js", + "jsdelivr": "./dist/browser.min.js", + "types": "./dist/browser.d.ts", + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "engines": { + "node": ">=12.20.0" + }, + "devDependencies": { + "@sxzz/eslint-config": "^8.1.0", + "@sxzz/prettier-config": "^2.3.1", + "@types/debug": "^4.1.13", + "@types/node": "^25.9.2", + "@typescript/native-preview": "7.0.0-dev.20260609.1", + "@vitest/browser-playwright": "^4.1.8", + "@vitest/coverage-v8": "^4.1.8", + "bumpp": "^11.1.0", + "debug": "^4.4.3", + "eslint": "^10.4.1", + "playwright": "^1.60.0", + "prettier": "^3.8.4", + "tsdown": "^0.22.2", + "typescript": "^6.0.3", + "vite": "^8.0.16", + "vitest": "^4.1.8" + }, + "prettier": "@sxzz/prettier-config", + "scripts": { + "lint": "eslint --cache .", + "lint:fix": "pnpm run lint --fix", + "build": "tsdown", + "dev": "tsdown --watch", + "test": "vitest", + "test:coverage": "vitest --project node --coverage", + "play": "vite playground", + "typecheck": "tsgo --noEmit", + "format": "prettier --cache --write .", + "release": "bumpp" + } +} \ No newline at end of file diff --git a/node_modules/omggif/README b/node_modules/omggif/README new file mode 100644 index 0000000000000000000000000000000000000000..a526f263d37ac2093fb88637adc7d84a226098e9 --- /dev/null +++ b/node_modules/omggif/README @@ -0,0 +1,24 @@ +omggif is a JavaScript implementation of a GIF 89a encoder and decoder. + +https://github.com/deanm/omggif + + +(c) Dean McNamee , 2013. + +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. diff --git a/node_modules/omggif/example_node.js b/node_modules/omggif/example_node.js new file mode 100644 index 0000000000000000000000000000000000000000..b3dadc2ec32843a0b17427cf146ee5349f1ccb50 --- /dev/null +++ b/node_modules/omggif/example_node.js @@ -0,0 +1,116 @@ +// (c) Dean McNamee , 2013. +// Node omggif example to write out a few example images. + +var fs = require('fs'); +var omggif = require('./omggif'); + +// Needs to be large enough for the final full file size. Can be any type of +// buffer that supports [] (an Array, Uint8Array, Node Buffer, etc). +var buf = new Buffer(1024 * 1024); + +function gen_static_global() { + var gf = new omggif.GifWriter(buf, 2, 2, {palette: [0xff0000, 0x0000ff]}); + gf.addFrame(0, 0, 2, 2, + [0, 1, 1, 0]); + return buf.slice(0, gf.end()); +} + +function gen_static_local() { + var gf = new omggif.GifWriter(buf, 2, 2); + gf.addFrame(0, 0, 2, 2, + [0, 1, 1, 0], + {palette: [0xff0000, 0x0000ff]}); + return buf.slice(0, gf.end()); +} + +function gen_anim() { + // The loop parameter is the number of times to loop, or 0 for forever. + // A value of 1 will play twice (first time, and then one loop time). + // To play only once do not specify loop or pass null. + var gf = new omggif.GifWriter(buf, 2, 2, {loop: 1}); + gf.addFrame(0, 0, 2, 2, + [0, 1, 1, 0], + {palette: [0xff0000, 0x0000ff]}); + gf.addFrame(0, 0, 2, 2, + [1, 0, 0, 1], + {palette: [0xff0000, 0x0000ff], + delay: 10}); // Delay in hundredths of a sec (100 = 1s). + return buf.slice(0, gf.end()); +} + +function gen_gray_strip() { + var gf = new omggif.GifWriter(buf, 256, 1); + var palette = [ ]; + var indices = [ ]; + for (var i = 0; i < 256; ++i) { + palette.push(i << 16 | i << 8 | i); + indices.push(i); + } + gf.addFrame(0, 0, 256, 1, indices, {palette: palette}); + return buf.slice(0, gf.end()); +} + +// More than 8-bit color (via tiling of several frames). Browsers seem to +// treat this as an animation though, with an enforced minimum time between +// frames which makes it animated instead of the intended static image. +function gen_color_strip() { + var gf = new omggif.GifWriter(buf, 256, 256, {palette: [0x000000, 0xff0000], + background: 1}); + + var indices = [ ]; + for (var i = 0; i < 256; ++i) indices.push(i); + + for (var j = 0; j < 256; ++j) { + var palette = [ ]; + for (var i = 0; i < 256; ++i) + palette.push(j << 16 | i << 8 | i); + gf.addFrame(0, j, 256, 1, indices, {palette: palette, disposal: 1}); + } + return buf.slice(0, gf.end()); +} + +// 1x1 white, generates the same as Google's 35 byte __utm.gif, except for some +// reason that I'm not sure of they set their background index to 255. +function gen_empty_white() { + var gf = new omggif.GifWriter(buf, 1, 1, {palette: [0xffffff, 0x000000]}); + gf.addFrame(0, 0, 1, 1, [0]); + return buf.slice(0, gf.end()); +} + +// 1x1 transparent 43 bytes. +function gen_empty_trans() { + var gf = new omggif.GifWriter(buf, 1, 1, {palette: [0x000000, 0x000000]}); + gf.addFrame(0, 0, 1, 1, [0], {transparent: 0}); + return buf.slice(0, gf.end()); +} + +// with lzw block of 256. +// see: https://github.com/deanm/omggif/issues/5 +function gen_block256() { + var width = 4840; + var gf = new omggif.GifWriter(buf, width, 1, { + palette: [0x000000, 0x000000, 0x000000, 0x000000, + 0x000000, 0x000000, 0x000000, 0x000000] + }); + var stream = Array(width); + for (var i = 0; i < width; ++i) stream[i] = i & 0x7; + gf.addFrame(0, 0, width, 1, stream, {transparent: 0}); + var data = buf.slice(0, gf.end()); + // Make sure it decodes. + var gr = new omggif.GifReader(data); + var fi0 = gr.frameInfo(0); + /* + console.log(fi0); + console.log(buf.slice(fi0.data_offset, fi0.data_offset + fi0.data_length)); + */ + return data; +} + +fs.writeFileSync('./test_static_global_palette.gif', gen_static_global()); +fs.writeFileSync('./test_static_local_palette.gif', gen_static_local()); +fs.writeFileSync('./test_anim.gif', gen_anim()); +fs.writeFileSync('./test_gray_strip.gif', gen_gray_strip()); +fs.writeFileSync('./test_color_strip.gif', gen_color_strip()); +fs.writeFileSync('./test_empty_white.gif', gen_empty_white()); +fs.writeFileSync('./test_empty_trans.gif', gen_empty_trans()); +fs.writeFileSync('./test_block256.gif', gen_block256()); diff --git a/node_modules/omggif/omggif.js b/node_modules/omggif/omggif.js new file mode 100644 index 0000000000000000000000000000000000000000..4b814fb37953987d670644d53d1663433a95d71e --- /dev/null +++ b/node_modules/omggif/omggif.js @@ -0,0 +1,807 @@ +// (c) Dean McNamee , 2013. +// +// https://github.com/deanm/omggif +// +// 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. +// +// omggif is a JavaScript implementation of a GIF 89a encoder and decoder, +// including animation and compression. It does not rely on any specific +// underlying system, so should run in the browser, Node, or Plask. + +"use strict"; + +function GifWriter(buf, width, height, gopts) { + var p = 0; + + var gopts = gopts === undefined ? { } : gopts; + var loop_count = gopts.loop === undefined ? null : gopts.loop; + var global_palette = gopts.palette === undefined ? null : gopts.palette; + + if (width <= 0 || height <= 0 || width > 65535 || height > 65535) + throw new Error("Width/Height invalid."); + + function check_palette_and_num_colors(palette) { + var num_colors = palette.length; + if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors-1)) { + throw new Error( + "Invalid code/color length, must be power of 2 and 2 .. 256."); + } + return num_colors; + } + + // - Header. + buf[p++] = 0x47; buf[p++] = 0x49; buf[p++] = 0x46; // GIF + buf[p++] = 0x38; buf[p++] = 0x39; buf[p++] = 0x61; // 89a + + // Handling of Global Color Table (palette) and background index. + var gp_num_colors_pow2 = 0; + var background = 0; + if (global_palette !== null) { + var gp_num_colors = check_palette_and_num_colors(global_palette); + while (gp_num_colors >>= 1) ++gp_num_colors_pow2; + gp_num_colors = 1 << gp_num_colors_pow2; + --gp_num_colors_pow2; + if (gopts.background !== undefined) { + background = gopts.background; + if (background >= gp_num_colors) + throw new Error("Background index out of range."); + // The GIF spec states that a background index of 0 should be ignored, so + // this is probably a mistake and you really want to set it to another + // slot in the palette. But actually in the end most browsers, etc end + // up ignoring this almost completely (including for dispose background). + if (background === 0) + throw new Error("Background index explicitly passed as 0."); + } + } + + // - Logical Screen Descriptor. + // NOTE(deanm): w/h apparently ignored by implementations, but set anyway. + buf[p++] = width & 0xff; buf[p++] = width >> 8 & 0xff; + buf[p++] = height & 0xff; buf[p++] = height >> 8 & 0xff; + // NOTE: Indicates 0-bpp original color resolution (unused?). + buf[p++] = (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag. + gp_num_colors_pow2; // NOTE: No sort flag (unused?). + buf[p++] = background; // Background Color Index. + buf[p++] = 0; // Pixel aspect ratio (unused?). + + // - Global Color Table + if (global_palette !== null) { + for (var i = 0, il = global_palette.length; i < il; ++i) { + var rgb = global_palette[i]; + buf[p++] = rgb >> 16 & 0xff; + buf[p++] = rgb >> 8 & 0xff; + buf[p++] = rgb & 0xff; + } + } + + if (loop_count !== null) { // Netscape block for looping. + if (loop_count < 0 || loop_count > 65535) + throw new Error("Loop count invalid.") + // Extension code, label, and length. + buf[p++] = 0x21; buf[p++] = 0xff; buf[p++] = 0x0b; + // NETSCAPE2.0 + buf[p++] = 0x4e; buf[p++] = 0x45; buf[p++] = 0x54; buf[p++] = 0x53; + buf[p++] = 0x43; buf[p++] = 0x41; buf[p++] = 0x50; buf[p++] = 0x45; + buf[p++] = 0x32; buf[p++] = 0x2e; buf[p++] = 0x30; + // Sub-block + buf[p++] = 0x03; buf[p++] = 0x01; + buf[p++] = loop_count & 0xff; buf[p++] = loop_count >> 8 & 0xff; + buf[p++] = 0x00; // Terminator. + } + + + var ended = false; + + this.addFrame = function(x, y, w, h, indexed_pixels, opts) { + if (ended === true) { --p; ended = false; } // Un-end. + + opts = opts === undefined ? { } : opts; + + // TODO(deanm): Bounds check x, y. Do they need to be within the virtual + // canvas width/height, I imagine? + if (x < 0 || y < 0 || x > 65535 || y > 65535) + throw new Error("x/y invalid.") + + if (w <= 0 || h <= 0 || w > 65535 || h > 65535) + throw new Error("Width/Height invalid.") + + if (indexed_pixels.length < w * h) + throw new Error("Not enough pixels for the frame size."); + + var using_local_palette = true; + var palette = opts.palette; + if (palette === undefined || palette === null) { + using_local_palette = false; + palette = global_palette; + } + + if (palette === undefined || palette === null) + throw new Error("Must supply either a local or global palette."); + + var num_colors = check_palette_and_num_colors(palette); + + // Compute the min_code_size (power of 2), destroying num_colors. + var min_code_size = 0; + while (num_colors >>= 1) ++min_code_size; + num_colors = 1 << min_code_size; // Now we can easily get it back. + + var delay = opts.delay === undefined ? 0 : opts.delay; + + // From the spec: + // 0 - No disposal specified. The decoder is + // not required to take any action. + // 1 - Do not dispose. The graphic is to be left + // in place. + // 2 - Restore to background color. The area used by the + // graphic must be restored to the background color. + // 3 - Restore to previous. The decoder is required to + // restore the area overwritten by the graphic with + // what was there prior to rendering the graphic. + // 4-7 - To be defined. + // NOTE(deanm): Dispose background doesn't really work, apparently most + // browsers ignore the background palette index and clear to transparency. + var disposal = opts.disposal === undefined ? 0 : opts.disposal; + if (disposal < 0 || disposal > 3) // 4-7 is reserved. + throw new Error("Disposal out of range."); + + var use_transparency = false; + var transparent_index = 0; + if (opts.transparent !== undefined && opts.transparent !== null) { + use_transparency = true; + transparent_index = opts.transparent; + if (transparent_index < 0 || transparent_index >= num_colors) + throw new Error("Transparent color index."); + } + + if (disposal !== 0 || use_transparency || delay !== 0) { + // - Graphics Control Extension + buf[p++] = 0x21; buf[p++] = 0xf9; // Extension / Label. + buf[p++] = 4; // Byte size. + + buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0); + buf[p++] = delay & 0xff; buf[p++] = delay >> 8 & 0xff; + buf[p++] = transparent_index; // Transparent color index. + buf[p++] = 0; // Block Terminator. + } + + // - Image Descriptor + buf[p++] = 0x2c; // Image Seperator. + buf[p++] = x & 0xff; buf[p++] = x >> 8 & 0xff; // Left. + buf[p++] = y & 0xff; buf[p++] = y >> 8 & 0xff; // Top. + buf[p++] = w & 0xff; buf[p++] = w >> 8 & 0xff; + buf[p++] = h & 0xff; buf[p++] = h >> 8 & 0xff; + // NOTE: No sort flag (unused?). + // TODO(deanm): Support interlace. + buf[p++] = using_local_palette === true ? (0x80 | (min_code_size-1)) : 0; + + // - Local Color Table + if (using_local_palette === true) { + for (var i = 0, il = palette.length; i < il; ++i) { + var rgb = palette[i]; + buf[p++] = rgb >> 16 & 0xff; + buf[p++] = rgb >> 8 & 0xff; + buf[p++] = rgb & 0xff; + } + } + + p = GifWriterOutputLZWCodeStream( + buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels); + + return p; + }; + + this.end = function() { + if (ended === false) { + buf[p++] = 0x3b; // Trailer. + ended = true; + } + return p; + }; + + this.getOutputBuffer = function() { return buf; }; + this.setOutputBuffer = function(v) { buf = v; }; + this.getOutputBufferPosition = function() { return p; }; + this.setOutputBufferPosition = function(v) { p = v; }; +} + +// Main compression routine, palette indexes -> LZW code stream. +// |index_stream| must have at least one entry. +function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) { + buf[p++] = min_code_size; + var cur_subblock = p++; // Pointing at the length field. + + var clear_code = 1 << min_code_size; + var code_mask = clear_code - 1; + var eoi_code = clear_code + 1; + var next_code = eoi_code + 1; + + var cur_code_size = min_code_size + 1; // Number of bits per code. + var cur_shift = 0; + // We have at most 12-bit codes, so we should have to hold a max of 19 + // bits here (and then we would write out). + var cur = 0; + + function emit_bytes_to_buffer(bit_block_size) { + while (cur_shift >= bit_block_size) { + buf[p++] = cur & 0xff; + cur >>= 8; cur_shift -= 8; + if (p === cur_subblock + 256) { // Finished a subblock. + buf[cur_subblock] = 255; + cur_subblock = p++; + } + } + } + + function emit_code(c) { + cur |= c << cur_shift; + cur_shift += cur_code_size; + emit_bytes_to_buffer(8); + } + + // I am not an expert on the topic, and I don't want to write a thesis. + // However, it is good to outline here the basic algorithm and the few data + // structures and optimizations here that make this implementation fast. + // The basic idea behind LZW is to build a table of previously seen runs + // addressed by a short id (herein called output code). All data is + // referenced by a code, which represents one or more values from the + // original input stream. All input bytes can be referenced as the same + // value as an output code. So if you didn't want any compression, you + // could more or less just output the original bytes as codes (there are + // some details to this, but it is the idea). In order to achieve + // compression, values greater then the input range (codes can be up to + // 12-bit while input only 8-bit) represent a sequence of previously seen + // inputs. The decompressor is able to build the same mapping while + // decoding, so there is always a shared common knowledge between the + // encoding and decoder, which is also important for "timing" aspects like + // how to handle variable bit width code encoding. + // + // One obvious but very important consequence of the table system is there + // is always a unique id (at most 12-bits) to map the runs. 'A' might be + // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship + // can be used for an effecient lookup strategy for the code mapping. We + // need to know if a run has been seen before, and be able to map that run + // to the output code. Since we start with known unique ids (input bytes), + // and then from those build more unique ids (table entries), we can + // continue this chain (almost like a linked list) to always have small + // integer values that represent the current byte chains in the encoder. + // This means instead of tracking the input bytes (AAAABCD) to know our + // current state, we can track the table entry for AAAABC (it is guaranteed + // to exist by the nature of the algorithm) and the next character D. + // Therefor the tuple of (table_entry, byte) is guaranteed to also be + // unique. This allows us to create a simple lookup key for mapping input + // sequences to codes (table indices) without having to store or search + // any of the code sequences. So if 'AAAA' has a table entry of 12, the + // tuple of ('AAAA', K) for any input byte K will be unique, and can be our + // key. This leads to a integer value at most 20-bits, which can always + // fit in an SMI value and be used as a fast sparse array / object key. + + // Output code for the current contents of the index buffer. + var ib_code = index_stream[0] & code_mask; // Load first input index. + var code_table = { }; // Key'd on our 20-bit "tuple". + + emit_code(clear_code); // Spec says first code should be a clear code. + + // First index already loaded, process the rest of the stream. + for (var i = 1, il = index_stream.length; i < il; ++i) { + var k = index_stream[i] & code_mask; + var cur_key = ib_code << 8 | k; // (prev, k) unique tuple. + var cur_code = code_table[cur_key]; // buffer + k. + + // Check if we have to create a new code table entry. + if (cur_code === undefined) { // We don't have buffer + k. + // Emit index buffer (without k). + // This is an inline version of emit_code, because this is the core + // writing routine of the compressor (and V8 cannot inline emit_code + // because it is a closure here in a different context). Additionally + // we can call emit_byte_to_buffer less often, because we can have + // 30-bits (from our 31-bit signed SMI), and we know our codes will only + // be 12-bits, so can safely have 18-bits there without overflow. + // emit_code(ib_code); + cur |= ib_code << cur_shift; + cur_shift += cur_code_size; + while (cur_shift >= 8) { + buf[p++] = cur & 0xff; + cur >>= 8; cur_shift -= 8; + if (p === cur_subblock + 256) { // Finished a subblock. + buf[cur_subblock] = 255; + cur_subblock = p++; + } + } + + if (next_code === 4096) { // Table full, need a clear. + emit_code(clear_code); + next_code = eoi_code + 1; + cur_code_size = min_code_size + 1; + code_table = { }; + } else { // Table not full, insert a new entry. + // Increase our variable bit code sizes if necessary. This is a bit + // tricky as it is based on "timing" between the encoding and + // decoder. From the encoders perspective this should happen after + // we've already emitted the index buffer and are about to create the + // first table entry that would overflow our current code bit size. + if (next_code >= (1 << cur_code_size)) ++cur_code_size; + code_table[cur_key] = next_code++; // Insert into code table. + } + + ib_code = k; // Index buffer to single input k. + } else { + ib_code = cur_code; // Index buffer to sequence in code table. + } + } + + emit_code(ib_code); // There will still be something in the index buffer. + emit_code(eoi_code); // End Of Information. + + // Flush / finalize the sub-blocks stream to the buffer. + emit_bytes_to_buffer(1); + + // Finish the sub-blocks, writing out any unfinished lengths and + // terminating with a sub-block of length 0. If we have already started + // but not yet used a sub-block it can just become the terminator. + if (cur_subblock + 1 === p) { // Started but unused. + buf[cur_subblock] = 0; + } else { // Started and used, write length and additional terminator block. + buf[cur_subblock] = p - cur_subblock - 1; + buf[p++] = 0; + } + return p; +} + +function GifReader(buf) { + var p = 0; + + // - Header (GIF87a or GIF89a). + if (buf[p++] !== 0x47 || buf[p++] !== 0x49 || buf[p++] !== 0x46 || + buf[p++] !== 0x38 || (buf[p++]+1 & 0xfd) !== 0x38 || buf[p++] !== 0x61) { + throw new Error("Invalid GIF 87a/89a header."); + } + + // - Logical Screen Descriptor. + var width = buf[p++] | buf[p++] << 8; + var height = buf[p++] | buf[p++] << 8; + var pf0 = buf[p++]; // . + var global_palette_flag = pf0 >> 7; + var num_global_colors_pow2 = pf0 & 0x7; + var num_global_colors = 1 << (num_global_colors_pow2 + 1); + var background = buf[p++]; + buf[p++]; // Pixel aspect ratio (unused?). + + var global_palette_offset = null; + var global_palette_size = null; + + if (global_palette_flag) { + global_palette_offset = p; + global_palette_size = num_global_colors; + p += num_global_colors * 3; // Seek past palette. + } + + var no_eof = true; + + var frames = [ ]; + + var delay = 0; + var transparent_index = null; + var disposal = 0; // 0 - No disposal specified. + var loop_count = null; + + this.width = width; + this.height = height; + + while (no_eof && p < buf.length) { + switch (buf[p++]) { + case 0x21: // Graphics Control Extension Block + switch (buf[p++]) { + case 0xff: // Application specific block + // Try if it's a Netscape block (with animation loop counter). + if (buf[p ] !== 0x0b || // 21 FF already read, check block size. + // NETSCAPE2.0 + buf[p+1 ] == 0x4e && buf[p+2 ] == 0x45 && buf[p+3 ] == 0x54 && + buf[p+4 ] == 0x53 && buf[p+5 ] == 0x43 && buf[p+6 ] == 0x41 && + buf[p+7 ] == 0x50 && buf[p+8 ] == 0x45 && buf[p+9 ] == 0x32 && + buf[p+10] == 0x2e && buf[p+11] == 0x30 && + // Sub-block + buf[p+12] == 0x03 && buf[p+13] == 0x01 && buf[p+16] == 0) { + p += 14; + loop_count = buf[p++] | buf[p++] << 8; + p++; // Skip terminator. + } else { // We don't know what it is, just try to get past it. + p += 12; + while (true) { // Seek through subblocks. + var block_size = buf[p++]; + // Bad block size (ex: undefined from an out of bounds read). + if (!(block_size >= 0)) throw Error("Invalid block size"); + if (block_size === 0) break; // 0 size is terminator + p += block_size; + } + } + break; + + case 0xf9: // Graphics Control Extension + if (buf[p++] !== 0x4 || buf[p+4] !== 0) + throw new Error("Invalid graphics extension block."); + var pf1 = buf[p++]; + delay = buf[p++] | buf[p++] << 8; + transparent_index = buf[p++]; + if ((pf1 & 1) === 0) transparent_index = null; + disposal = pf1 >> 2 & 0x7; + p++; // Skip terminator. + break; + + case 0xfe: // Comment Extension. + while (true) { // Seek through subblocks. + var block_size = buf[p++]; + // Bad block size (ex: undefined from an out of bounds read). + if (!(block_size >= 0)) throw Error("Invalid block size"); + if (block_size === 0) break; // 0 size is terminator + // console.log(buf.slice(p, p+block_size).toString('ascii')); + p += block_size; + } + break; + + default: + throw new Error( + "Unknown graphic control label: 0x" + buf[p-1].toString(16)); + } + break; + + case 0x2c: // Image Descriptor. + var x = buf[p++] | buf[p++] << 8; + var y = buf[p++] | buf[p++] << 8; + var w = buf[p++] | buf[p++] << 8; + var h = buf[p++] | buf[p++] << 8; + var pf2 = buf[p++]; + var local_palette_flag = pf2 >> 7; + var interlace_flag = pf2 >> 6 & 1; + var num_local_colors_pow2 = pf2 & 0x7; + var num_local_colors = 1 << (num_local_colors_pow2 + 1); + var palette_offset = global_palette_offset; + var palette_size = global_palette_size; + var has_local_palette = false; + if (local_palette_flag) { + var has_local_palette = true; + palette_offset = p; // Override with local palette. + palette_size = num_local_colors; + p += num_local_colors * 3; // Seek past palette. + } + + var data_offset = p; + + p++; // codesize + while (true) { + var block_size = buf[p++]; + // Bad block size (ex: undefined from an out of bounds read). + if (!(block_size >= 0)) throw Error("Invalid block size"); + if (block_size === 0) break; // 0 size is terminator + p += block_size; + } + + frames.push({x: x, y: y, width: w, height: h, + has_local_palette: has_local_palette, + palette_offset: palette_offset, + palette_size: palette_size, + data_offset: data_offset, + data_length: p - data_offset, + transparent_index: transparent_index, + interlaced: !!interlace_flag, + delay: delay, + disposal: disposal}); + break; + + case 0x3b: // Trailer Marker (end of file). + no_eof = false; + break; + + default: + throw new Error("Unknown gif block: 0x" + buf[p-1].toString(16)); + break; + } + } + + this.numFrames = function() { + return frames.length; + }; + + this.loopCount = function() { + return loop_count; + }; + + this.frameInfo = function(frame_num) { + if (frame_num < 0 || frame_num >= frames.length) + throw new Error("Frame index out of range."); + return frames[frame_num]; + } + + this.decodeAndBlitFrameBGRA = function(frame_num, pixels) { + var frame = this.frameInfo(frame_num); + var num_pixels = frame.width * frame.height; + var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices. + GifReaderLZWOutputIndexStream( + buf, frame.data_offset, index_stream, num_pixels); + var palette_offset = frame.palette_offset; + + // NOTE(deanm): It seems to be much faster to compare index to 256 than + // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in + // the profile, not sure if it's related to using a Uint8Array. + var trans = frame.transparent_index; + if (trans === null) trans = 256; + + // We are possibly just blitting to a portion of the entire frame. + // That is a subrect within the framerect, so the additional pixels + // must be skipped over after we finished a scanline. + var framewidth = frame.width; + var framestride = width - framewidth; + var xleft = framewidth; // Number of subrect pixels left in scanline. + + // Output indicies of the top left and bottom right corners of the subrect. + var opbeg = ((frame.y * width) + frame.x) * 4; + var opend = ((frame.y + frame.height) * width + frame.x) * 4; + var op = opbeg; + + var scanstride = framestride * 4; + + // Use scanstride to skip past the rows when interlacing. This is skipping + // 7 rows for the first two passes, then 3 then 1. + if (frame.interlaced === true) { + scanstride += width * 4 * 7; // Pass 1. + } + + var interlaceskip = 8; // Tracking the row interval in the current pass. + + for (var i = 0, il = index_stream.length; i < il; ++i) { + var index = index_stream[i]; + + if (xleft === 0) { // Beginning of new scan line + op += scanstride; + xleft = framewidth; + if (op >= opend) { // Catch the wrap to switch passes when interlacing. + scanstride = framestride * 4 + width * 4 * (interlaceskip-1); + // interlaceskip / 2 * 4 is interlaceskip << 1. + op = opbeg + (framewidth + framestride) * (interlaceskip << 1); + interlaceskip >>= 1; + } + } + + if (index === trans) { + op += 4; + } else { + var r = buf[palette_offset + index * 3]; + var g = buf[palette_offset + index * 3 + 1]; + var b = buf[palette_offset + index * 3 + 2]; + pixels[op++] = b; + pixels[op++] = g; + pixels[op++] = r; + pixels[op++] = 255; + } + --xleft; + } + }; + + // I will go to copy and paste hell one day... + this.decodeAndBlitFrameRGBA = function(frame_num, pixels) { + var frame = this.frameInfo(frame_num); + var num_pixels = frame.width * frame.height; + var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices. + GifReaderLZWOutputIndexStream( + buf, frame.data_offset, index_stream, num_pixels); + var palette_offset = frame.palette_offset; + + // NOTE(deanm): It seems to be much faster to compare index to 256 than + // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in + // the profile, not sure if it's related to using a Uint8Array. + var trans = frame.transparent_index; + if (trans === null) trans = 256; + + // We are possibly just blitting to a portion of the entire frame. + // That is a subrect within the framerect, so the additional pixels + // must be skipped over after we finished a scanline. + var framewidth = frame.width; + var framestride = width - framewidth; + var xleft = framewidth; // Number of subrect pixels left in scanline. + + // Output indicies of the top left and bottom right corners of the subrect. + var opbeg = ((frame.y * width) + frame.x) * 4; + var opend = ((frame.y + frame.height) * width + frame.x) * 4; + var op = opbeg; + + var scanstride = framestride * 4; + + // Use scanstride to skip past the rows when interlacing. This is skipping + // 7 rows for the first two passes, then 3 then 1. + if (frame.interlaced === true) { + scanstride += width * 4 * 7; // Pass 1. + } + + var interlaceskip = 8; // Tracking the row interval in the current pass. + + for (var i = 0, il = index_stream.length; i < il; ++i) { + var index = index_stream[i]; + + if (xleft === 0) { // Beginning of new scan line + op += scanstride; + xleft = framewidth; + if (op >= opend) { // Catch the wrap to switch passes when interlacing. + scanstride = framestride * 4 + width * 4 * (interlaceskip-1); + // interlaceskip / 2 * 4 is interlaceskip << 1. + op = opbeg + (framewidth + framestride) * (interlaceskip << 1); + interlaceskip >>= 1; + } + } + + if (index === trans) { + op += 4; + } else { + var r = buf[palette_offset + index * 3]; + var g = buf[palette_offset + index * 3 + 1]; + var b = buf[palette_offset + index * 3 + 2]; + pixels[op++] = r; + pixels[op++] = g; + pixels[op++] = b; + pixels[op++] = 255; + } + --xleft; + } + }; +} + +function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) { + var min_code_size = code_stream[p++]; + + var clear_code = 1 << min_code_size; + var eoi_code = clear_code + 1; + var next_code = eoi_code + 1; + + var cur_code_size = min_code_size + 1; // Number of bits per code. + // NOTE: This shares the same name as the encoder, but has a different + // meaning here. Here this masks each code coming from the code stream. + var code_mask = (1 << cur_code_size) - 1; + var cur_shift = 0; + var cur = 0; + + var op = 0; // Output pointer. + + var subblock_size = code_stream[p++]; + + // TODO(deanm): Would using a TypedArray be any faster? At least it would + // solve the fast mode / backing store uncertainty. + // var code_table = Array(4096); + var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits. + + var prev_code = null; // Track code-1. + + while (true) { + // Read up to two bytes, making sure we always 12-bits for max sized code. + while (cur_shift < 16) { + if (subblock_size === 0) break; // No more data to be read. + + cur |= code_stream[p++] << cur_shift; + cur_shift += 8; + + if (subblock_size === 1) { // Never let it get to 0 to hold logic above. + subblock_size = code_stream[p++]; // Next subblock. + } else { + --subblock_size; + } + } + + // TODO(deanm): We should never really get here, we should have received + // and EOI. + if (cur_shift < cur_code_size) + break; + + var code = cur & code_mask; + cur >>= cur_code_size; + cur_shift -= cur_code_size; + + // TODO(deanm): Maybe should check that the first code was a clear code, + // at least this is what you're supposed to do. But actually our encoder + // now doesn't emit a clear code first anyway. + if (code === clear_code) { + // We don't actually have to clear the table. This could be a good idea + // for greater error checking, but we don't really do any anyway. We + // will just track it with next_code and overwrite old entries. + + next_code = eoi_code + 1; + cur_code_size = min_code_size + 1; + code_mask = (1 << cur_code_size) - 1; + + // Don't update prev_code ? + prev_code = null; + continue; + } else if (code === eoi_code) { + break; + } + + // We have a similar situation as the decoder, where we want to store + // variable length entries (code table entries), but we want to do in a + // faster manner than an array of arrays. The code below stores sort of a + // linked list within the code table, and then "chases" through it to + // construct the dictionary entries. When a new entry is created, just the + // last byte is stored, and the rest (prefix) of the entry is only + // referenced by its table entry. Then the code chases through the + // prefixes until it reaches a single byte code. We have to chase twice, + // first to compute the length, and then to actually copy the data to the + // output (backwards, since we know the length). The alternative would be + // storing something in an intermediate stack, but that doesn't make any + // more sense. I implemented an approach where it also stored the length + // in the code table, although it's a bit tricky because you run out of + // bits (12 + 12 + 8), but I didn't measure much improvements (the table + // entries are generally not the long). Even when I created benchmarks for + // very long table entries the complexity did not seem worth it. + // The code table stores the prefix entry in 12 bits and then the suffix + // byte in 8 bits, so each entry is 20 bits. + + var chase_code = code < next_code ? code : prev_code; + + // Chase what we will output, either {CODE} or {CODE-1}. + var chase_length = 0; + var chase = chase_code; + while (chase > clear_code) { + chase = code_table[chase] >> 8; + ++chase_length; + } + + var k = chase; + + var op_end = op + chase_length + (chase_code !== code ? 1 : 0); + if (op_end > output_length) { + console.log("Warning, gif stream longer than expected."); + return; + } + + // Already have the first byte from the chase, might as well write it fast. + output[op++] = k; + + op += chase_length; + var b = op; // Track pointer, writing backwards. + + if (chase_code !== code) // The case of emitting {CODE-1} + k. + output[op++] = k; + + chase = chase_code; + while (chase_length--) { + chase = code_table[chase]; + output[--b] = chase & 0xff; // Write backwards. + chase >>= 8; // Pull down to the prefix code. + } + + if (prev_code !== null && next_code < 4096) { + code_table[next_code++] = prev_code << 8 | k; + // TODO(deanm): Figure out this clearing vs code growth logic better. I + // have an feeling that it should just happen somewhere else, for now it + // is awkward between when we grow past the max and then hit a clear code. + // For now just check if we hit the max 12-bits (then a clear code should + // follow, also of course encoded in 12-bits). + if (next_code >= code_mask+1 && cur_code_size < 12) { + ++cur_code_size; + code_mask = code_mask << 1 | 1; + } + } + + prev_code = code; + } + + if (op !== output_length) { + console.log("Warning, gif stream shorter than expected."); + } + + return output; +} + +// CommonJS. +try { exports.GifWriter = GifWriter; exports.GifReader = GifReader } catch(e) {} diff --git a/node_modules/omggif/package.json b/node_modules/omggif/package.json new file mode 100644 index 0000000000000000000000000000000000000000..83766f5116567ffe44b2406e700ae0086482b018 --- /dev/null +++ b/node_modules/omggif/package.json @@ -0,0 +1,12 @@ +{ + "name": "omggif", + "version": "1.0.10", + "author": "Dean McNamee ", + "license": "MIT", + "keywords": ["gif", "gif89a", "gif87a", "plask"], + "repository": { + "type": "git", + "url": "https://github.com/deanm/omggif" + }, + "main": "omggif.js" +} diff --git a/node_modules/omggif/plask_viewer.js b/node_modules/omggif/plask_viewer.js new file mode 100644 index 0000000000000000000000000000000000000000..b2bd61725037d09a6910ff6a933a9a1be567037b --- /dev/null +++ b/node_modules/omggif/plask_viewer.js @@ -0,0 +1,42 @@ + +var plask = require('plask'); +var fs = require('fs'); +var omggif = require('./omggif'); + +if (process.argv.length < 3) throw "Usage: "; +var buf = fs.readFileSync(process.argv[2]); +var gr = new omggif.GifReader(buf); + +var pixels = plask.SkCanvas.create(gr.width, gr.height); + +plask.simpleWindow({ + settings: { + width: 800, + height: 600 + }, + + init: function() { + var canvas = this.canvas, paint = this.paint; + + canvas.clear(230, 230, 230, 255); // Draw the background, just once. + }, + + draw: function() { + var canvas = this.canvas, paint = this.paint; + + var frame_num = this.framenum % gr.numFrames(); + var frame_info = gr.frameInfo(frame_num); + + if (frame_num === 0 || frame_info.disposal === 2 /* restore to bg */) + pixels.clear(0, 0, 0, 255); + + var start = Date.now(); + gr.decodeAndBlitFrameBGRA(frame_num, pixels.pixels || pixels); + console.log('Decoded and blit frame in: ' + (Date.now() - start) + 'ms'); + + canvas.drawCanvas(paint, pixels, 0, 0, gr.width, gr.height); + + var this_ = this; + setTimeout(function() { this_.redraw(); }, frame_info.delay * 10); + } +}); diff --git a/node_modules/on-finished/HISTORY.md b/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..1917595a714e11049ec9402d87aa625c68caa080 --- /dev/null +++ b/node_modules/on-finished/HISTORY.md @@ -0,0 +1,98 @@ +2.4.1 / 2022-02-22 +================== + + * Fix error on early async hooks implementations + +2.4.0 / 2022-02-21 +================== + + * Prevent loss of async hooks context + +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +2.2.1 / 2015-04-22 +================== + + * Fix `isFinished(req)` when data buffered + +2.2.0 / 2014-12-22 +================== + + * Add message object to callback arguments + +2.1.1 / 2014-10-22 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/node_modules/on-finished/LICENSE b/node_modules/on-finished/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5931fd23eab9dd3be559cd4bd81253df87a5297c --- /dev/null +++ b/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +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. diff --git a/node_modules/on-finished/README.md b/node_modules/on-finished/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8973cded6589a6cc5a9e1718e3fb0d709fe6e8d8 --- /dev/null +++ b/node_modules/on-finished/README.md @@ -0,0 +1,162 @@ +# on-finished + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to an error, the first argument will contain the error. If the response +has already finished, the listener will be invoked. + +Listening to the end of a response would be used to close things associated +with the response, like open files. + +Listener is invoked as `listener(err, res)`. + + + +```js +onFinished(res, function (err, res) { + // clean up open fds, etc. + // err contains the error if request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to an error, the first argument will contain the error. If the request +has already finished, the listener will be invoked. + +Listening to the end of a request would be used to know when to continue +after reading the data. + +Listener is invoked as `listener(err, req)`. + + + +```js +var data = '' + +req.setEncoding('utf8') +req.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var fs = require('fs') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest (req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function () { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/on-finished/master?label=ci +[ci-url]: https://github.com/jshttp/on-finished/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-finished/master +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[node-image]: https://badgen.net/npm/node/on-finished +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/on-finished +[npm-url]: https://npmjs.org/package/on-finished +[npm-version-image]: https://badgen.net/npm/v/on-finished diff --git a/node_modules/on-finished/index.js b/node_modules/on-finished/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e68df7bde39bb47aa1fd7eff4b317b3969de75bd --- /dev/null +++ b/node_modules/on-finished/index.js @@ -0,0 +1,234 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var asyncHooks = tryRequireAsyncHooks() +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished (msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, wrap(listener)) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished (msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener (msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish (error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket (socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // istanbul ignore next: node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener (msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener (msg) { + function listener (err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +// istanbul ignore next: node.js 0.8 patch +function patchAssignSocket (res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket (socket) { + assignSocket.call(this, socket) + callback(socket) + } +} + +/** + * Try to require async_hooks + * @private + */ + +function tryRequireAsyncHooks () { + try { + return require('async_hooks') + } catch (e) { + return {} + } +} + +/** + * Wrap function with async resource, if possible. + * AsyncResource.bind static method backported. + * @private + */ + +function wrap (fn) { + var res + + // create anonymous resource + if (asyncHooks.AsyncResource) { + res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') + } + + // incompatible node.js + if (!res || !res.runInAsyncScope) { + return fn + } + + // return bound function + return res.runInAsyncScope.bind(res, fn, null) +} diff --git a/node_modules/on-finished/package.json b/node_modules/on-finished/package.json new file mode 100644 index 0000000000000000000000000000000000000000..644cd814b9d745714e4d16753de8bc8856e201e4 --- /dev/null +++ b/node_modules/on-finished/package.json @@ -0,0 +1,39 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.4.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/on-finished", + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/once/LICENSE b/node_modules/once/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..19129e315fe593965a2fdd50ec0d1253bcbd2ece --- /dev/null +++ b/node_modules/once/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/once/README.md b/node_modules/once/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1f1ffca9330e3ceddd54106e1ba63322fc9751f8 --- /dev/null +++ b/node_modules/once/README.md @@ -0,0 +1,79 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. + +To check whether you function has been called, use `fn.called`. Once the +function is called for the first time the return value of the original +function is saved in `fn.value` and subsequent calls will continue to +return this value. + +```javascript +var once = require('once') + +function load (cb) { + cb = once(cb) + var stream = createStream() + stream.once('data', cb) + stream.once('end', function () { + if (!cb.called) cb(new Error('not found')) + }) +} +``` + +## `once.strict(func)` + +Throw an error if the function is called twice. + +Some functions are expected to be called only once. Using `once` for them would +potentially hide logical errors. + +In the example below, the `greet` function has to call the callback only once: + +```javascript +function greet (name, cb) { + // return is missing from the if statement + // when no name is passed, the callback is called twice + if (!name) cb('Hello anonymous') + cb('Hello ' + name) +} + +function log (msg) { + console.log(msg) +} + +// this will print 'Hello anonymous' but the logical error will be missed +greet(null, once(msg)) + +// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time +greet(null, once.strict(msg)) +``` diff --git a/node_modules/once/once.js b/node_modules/once/once.js new file mode 100644 index 0000000000000000000000000000000000000000..235406736d9d9485bbc0dd0820dd661110da7a4d --- /dev/null +++ b/node_modules/once/once.js @@ -0,0 +1,42 @@ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} diff --git a/node_modules/once/package.json b/node_modules/once/package.json new file mode 100644 index 0000000000000000000000000000000000000000..16815b2fa111936c9681a1b76c5fce98421c1631 --- /dev/null +++ b/node_modules/once/package.json @@ -0,0 +1,33 @@ +{ + "name": "once", + "version": "1.4.0", + "description": "Run a function exactly one time", + "main": "once.js", + "directories": { + "test": "test" + }, + "dependencies": { + "wrappy": "1" + }, + "devDependencies": { + "tap": "^7.0.1" + }, + "scripts": { + "test": "tap test/*.js" + }, + "files": [ + "once.js" + ], + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once" + }, + "keywords": [ + "once", + "function", + "one", + "single" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC" +} diff --git a/node_modules/optionator/CHANGELOG.md b/node_modules/optionator/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..2928cc2ced55510e091a38d82516d3b97a196de0 --- /dev/null +++ b/node_modules/optionator/CHANGELOG.md @@ -0,0 +1,59 @@ +# 0.9.0 +- update dependencies, in particular `levn` and `type-check` - this could affect behaviour of argument parsing + +# 0.8.3 +- changes dependency from `wordwrap` to `word-wrap` due to license issue +- update dependencies + +# 0.8.2 +- fix bug #18 - detect missing value when flag is last item +- update dependencies + +# 0.8.1 +- update `fast-levenshtein` dependency + +# 0.8.0 +- update `levn` dependency - supplying a float value to an option with type `Int` now throws an error, instead of silently converting to an `Int` + +# 0.7.1 +- fix bug with use of `defaults` and `concatRepeatedArrays` or `mergeRepeatedObjects` + +# 0.7.0 +- added `concatrepeatedarrays` option: `oneValuePerFlag`, only allows one array value per flag +- added `typeAliases` option +- added `parseArgv` which takes an array and parses with the first two items sliced off +- changed enum help style +- bug fixes (#12) +- use of `concatRepeatedArrays` and `mergeRepeatedObjects` at the top level is deprecated, use it as either a per-option option, or set them in the `defaults` object to set them for all objects + +# 0.6.0 +- added `defaults` lib-option flag, allowing one to set default properties for all options +- added `concatRepeatedArrays` and `mergeRepeatedObjects` as option level properties, allowing you to turn this feature on for specific options only + +# 0.5.0 +- `Boolean` flags with `default: 'true'`, and no short aliases, will by default show the `--no` version in help + +# 0.4.0 +- add `mergeRepeatedObjects` setting + +# 0.3.0 +- add `concatRepeatedArrays` setting +- add `overrideRequired` option setting +- use just Levenshtein string compare algo rather than Levenshtein Damerau to due dependency license issue + +# 0.2.2 +- bug fixes + +# 0.2.1 +- improved interpolation +- added changelog + +# 0.2.0 +- add dependency checks to options - added `dependsOn` as an option property +- add interpolation for `prepend` and `append` text with new `generateHelp` option, `interpolate` + +# 0.1.1 +- update dependencies + +# 0.1.0 +- initial release diff --git a/node_modules/optionator/LICENSE b/node_modules/optionator/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..525b11850e6f2cc73b10854d14a4532797ed0a07 --- /dev/null +++ b/node_modules/optionator/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) George Zahariev + +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. diff --git a/node_modules/optionator/README.md b/node_modules/optionator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9cd0bb43e2bbab62df993780ce433ebde012c28b --- /dev/null +++ b/node_modules/optionator/README.md @@ -0,0 +1,238 @@ +# Optionator + + +Optionator is a JavaScript/Node.js option parsing and help generation library used by [eslint](http://eslint.org), [Grasp](http://graspjs.com), [LiveScript](http://livescript.net), [esmangle](https://github.com/estools/esmangle), [escodegen](https://github.com/estools/escodegen), and [many more](https://www.npmjs.com/browse/depended/optionator). + +For an online demo, check out the [Grasp online demo](http://www.graspjs.com/#demo). + +[About](#about) · [Usage](#usage) · [Settings Format](#settings-format) · [Argument Format](#argument-format) + +## Why? +The problem with other option parsers, such as `yargs` or `minimist`, is they just accept all input, valid or not. +With Optionator, if you mistype an option, it will give you an error (with a suggestion for what you meant). +If you give the wrong type of argument for an option, it will give you an error rather than supplying the wrong input to your application. + + $ cmd --halp + Invalid option '--halp' - perhaps you meant '--help'? + + $ cmd --count str + Invalid value for option 'count' - expected type Int, received value: str. + +Other helpful features include reformatting the help text based on the size of the console, so that it fits even if the console is narrow, and accepting not just an array (eg. process.argv), but a string or object as well, making things like testing much easier. + +## About +Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types. + +MIT license. Version 0.9.4 + + npm install optionator + +For updates on Optionator, [follow me on twitter](https://twitter.com/gkzahariev). + +Optionator is a Node.js module, but can be used in the browser as well if packed with webpack/browserify. + +## Usage +`require('optionator');` returns a function. It has one property, `VERSION`, the current version of the library as a string. This function is called with an object specifying your options and other information, see the [settings format section](#settings-format). This in turn returns an object with three properties, `parse`, `parseArgv`, `generateHelp`, and `generateHelpForOption`, which are all functions. + +```js +var optionator = require('optionator')({ + prepend: 'Usage: cmd [options]', + append: 'Version 1.0.0', + options: [{ + option: 'help', + alias: 'h', + type: 'Boolean', + description: 'displays help' + }, { + option: 'count', + alias: 'c', + type: 'Int', + description: 'number of things', + example: 'cmd --count 2' + }] +}); + +var options = optionator.parseArgv(process.argv); +if (options.help) { + console.log(optionator.generateHelp()); +} +... +``` + +### parse(input, parseOptions) +`parse` processes the `input` according to your settings, and returns an object with the results. + +##### arguments +* input - `[String] | Object | String` - the input you wish to parse +* parseOptions - `{slice: Int}` - all options optional + - `slice` specifies how much to slice away from the beginning if the input is an array or string - by default `0` for string, `2` for array (works with `process.argv`) + +##### returns +`Object` - the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the `_` key. + +##### example +```js +parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']} +parse('--count 2 positional'); // {count: 2, _: ['positional']} +parse({count: 2, _:['positional']}); // {count: 2, _: ['positional']} +``` + +### parseArgv(input) +`parseArgv` works exactly like `parse`, but only for array input and it slices off the first two elements. + +##### arguments +* input - `[String]` - the input you wish to parse + +##### returns +See "returns" section in "parse" + +##### example +```js +parseArgv(process.argv); +``` + +### generateHelp(helpOptions) +`generateHelp` produces help text based on your settings. + +##### arguments +* helpOptions - `{showHidden: Boolean, interpolate: Object}` - all options optional + - `showHidden` specifies whether to show options with `hidden: true` specified, by default it is `false` + - `interpolate` specify data to be interpolated in `prepend` and `append` text, `{{key}}` is the format - eg. `generateHelp({interpolate:{version: '0.4.2'}})`, will change this `append` text: `Version {{version}}` to `Version 0.4.2` + +##### returns +`String` - the generated help text + +##### example +```js +generateHelp(); /* +"Usage: cmd [options] positional + + -h, --help displays help + -c, --count Int number of things + +Version 1.0.0 +"*/ +``` + +### generateHelpForOption(optionName) +`generateHelpForOption` produces expanded help text for the specified with `optionName` option. If an `example` was specified for the option, it will be displayed, and if a `longDescription` was specified, it will display that instead of the `description`. + +##### arguments +* optionName - `String` - the name of the option to display + +##### returns +`String` - the generated help text for the option + +##### example +```js +generateHelpForOption('count'); /* +"-c, --count Int +description: number of things +example: cmd --count 2 +"*/ +``` + +## Settings Format +When your `require('optionator')`, you get a function that takes in a settings object. This object has the type: + + { + prepend: String, + append: String, + options: [{heading: String} | { + option: String, + alias: [String] | String, + type: String, + enum: [String], + default: String, + restPositional: Boolean, + required: Boolean, + overrideRequired: Boolean, + dependsOn: [String] | String, + concatRepeatedArrays: Boolean | (Boolean, Object), + mergeRepeatedObjects: Boolean, + description: String, + longDescription: String, + example: [String] | String + }], + helpStyle: { + aliasSeparator: String, + typeSeparator: String, + descriptionSeparator: String, + initialIndent: Int, + secondaryIndent: Int, + maxPadFactor: Number + }, + mutuallyExclusive: [[String | [String]]], + concatRepeatedArrays: Boolean | (Boolean, Object), // deprecated, set in defaults object + mergeRepeatedObjects: Boolean, // deprecated, set in defaults object + positionalAnywhere: Boolean, + typeAliases: Object, + defaults: Object + } + +All of the properties are optional (the `Maybe` has been excluded for brevities sake), except for having either `heading: String` or `option: String` in each object in the `options` array. + +### Top Level Properties +* `prepend` is an optional string to be placed before the options in the help text +* `append` is an optional string to be placed after the options in the help text +* `options` is a required array specifying your options and headings, the options and headings will be displayed in the order specified +* `helpStyle` is an optional object which enables you to change the default appearance of some aspects of the help text +* `mutuallyExclusive` is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is present +* `concatRepeatedArrays` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property +* `mergeRepeatedObjects` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property +* `positionalAnywhere` is an optional boolean (defaults to `true`) - when `true` it allows positional arguments anywhere, when `false`, all arguments after the first positional one are taken to be positional as well, even if they look like a flag. For example, with `positionalAnywhere: false`, the arguments `--flag --boom 12 --crack` would have two positional arguments: `12` and `--crack` +* `typeAliases` is an optional object, it allows you to set aliases for types, eg. `{Path: 'String'}` would allow you to use the type `Path` as an alias for the type `String` +* `defaults` is an optional object following the option properties format, which specifies default values for all options. A default will be overridden if manually set. For example, you can do `default: { type: "String" }` to set the default type of all options to `String`, and then override that default in an individual option by setting the `type` property + +#### Heading Properties +* `heading` a required string, the name of the heading + +#### Option Properties +* `option` the required name of the option - use dash-case, without the leading dashes +* `alias` is an optional string or array of strings which specify any aliases for the option +* `type` is a required string in the [type check](https://github.com/gkz/type-check) [format](https://github.com/gkz/type-check#type-format), this will be used to cast the inputted value and validate it +* `enum` is an optional array of strings, each string will be parsed by [levn](https://github.com/gkz/levn) - the argument value must be one of the resulting values - each potential value must validate against the specified `type` +* `default` is a optional string, which will be parsed by [levn](https://github.com/gkz/levn) and used as the default value if none is set - the value must validate against the specified `type` +* `restPositional` is an optional boolean - if set to `true`, everything after the option will be taken to be a positional argument, even if it looks like a named argument +* `required` is an optional boolean - if set to `true`, the option parsing will fail if the option is not defined +* `overrideRequired` is a optional boolean - if set to `true` and the option is used, and there is another option which is required but not set, it will override the need for the required option and there will be no error - this is useful if you have required options and want to use `--help` or `--version` flags +* `concatRepeatedArrays` is an optional boolean or tuple with boolean and options object (defaults to `false`) - when set to `true` and an option contains an array value and is repeated, the subsequent values for the flag will be appended rather than overwriting the original value - eg. option `g` of type `[String]`: `-g a -g b -g c,d` will result in `['a','b','c','d']` + + You can supply an options object by giving the following value: `[true, options]`. The one currently supported option is `oneValuePerFlag`, this only allows one array value per flag. This is useful if your potential values contain a comma. +* `mergeRepeatedObjects` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an object value and is repeated, the subsequent values for the flag will be merged rather than overwriting the original value - eg. option `g` of type `Object`: `-g a:1 -g b:2 -g c:3,d:4` will result in `{a: 1, b: 2, c: 3, d: 4}` +* `dependsOn` is an optional string or array of strings - if simply a string (the name of another option), it will make sure that that other option is set, if an array of strings, depending on whether `'and'` or `'or'` is first, it will either check whether all (`['and', 'option-a', 'option-b']`), or at least one (`['or', 'option-a', 'option-b']`) other options are set +* `description` is an optional string, which will be displayed next to the option in the help text +* `longDescription` is an optional string, it will be displayed instead of the `description` when `generateHelpForOption` is used +* `example` is an optional string or array of strings with example(s) for the option - these will be displayed when `generateHelpForOption` is used + +#### Help Style Properties +* `aliasSeparator` is an optional string, separates multiple names from each other - default: ' ,' +* `typeSeparator` is an optional string, separates the type from the names - default: ' ' +* `descriptionSeparator` is an optional string , separates the description from the padded name and type - default: ' ' +* `initialIndent` is an optional int - the amount of indent for options - default: 2 +* `secondaryIndent` is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4 +* `maxPadFactor` is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5 + +## Argument Format +At the highest level there are two types of arguments: named, and positional. + +Name arguments of any length are prefixed with `--` (eg. `--go`), and those of one character may be prefixed with either `--` or `-` (eg. `-g`). + +There are two types of named arguments: boolean flags (eg. `--problemo`, `-p`) which take no value and result in a `true` if they are present, the falsey `undefined` if they are not present, or `false` if present and explicitly prefixed with `no` (eg. `--no-problemo`). Named arguments with values (eg. `--tseries 800`, `-t 800`) are the other type. If the option has a type `Boolean` it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value. + +For more information about how to properly set types to get the value you want, take a look at the [type check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) pages. + +You can group single character arguments that use a single `-`, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. `-ba 2` is equivalent to `-b -a 2`. + +Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in `cmd -b one -a 2 two` where `b` is a boolean flag, and `a` has the type `Number`, there are two positional arguments, `one` and `two`. + +Everything after an `--` is positional, even if it looks like a named argument. + +You may optionally use `=` to separate option names from values, for example: `--count=2`. + +If you specify the option `NUM`, then any argument using a single `-` followed by a number will be valid and will set the value of `NUM`. Eg. `-2` will be parsed into `NUM: 2`. + +If duplicate named arguments are present, the last one will be taken. + +## Technical About +`optionator` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [levn](https://github.com/gkz/levn) to cast arguments to their specified type, and uses [type-check](https://github.com/gkz/type-check) to validate values. It also uses the [prelude.ls](http://preludels.com/) library. diff --git a/node_modules/optionator/lib/help.js b/node_modules/optionator/lib/help.js new file mode 100644 index 0000000000000000000000000000000000000000..59e6f9694c95847ad99da3a9c442790a56d2ee3a --- /dev/null +++ b/node_modules/optionator/lib/help.js @@ -0,0 +1,260 @@ +// Generated by LiveScript 1.6.0 +(function(){ + var ref$, id, find, sort, min, max, map, unlines, nameToRaw, dasherize, naturalJoin, wordWrap, wordwrap, getPreText, setHelpStyleDefaults, generateHelpForOption, generateHelp; + ref$ = require('prelude-ls'), id = ref$.id, find = ref$.find, sort = ref$.sort, min = ref$.min, max = ref$.max, map = ref$.map, unlines = ref$.unlines; + ref$ = require('./util'), nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin; + wordWrap = require('word-wrap'); + wordwrap = function(a, b){ + var ref$, indent, width; + ref$ = b === undefined + ? ['', a - 1] + : [repeatString$(' ', a), b - a - 1], indent = ref$[0], width = ref$[1]; + return function(text){ + return wordWrap(text, { + indent: indent, + width: width, + trim: true + }); + }; + }; + getPreText = function(option, arg$, maxWidth){ + var mainName, shortNames, ref$, longNames, type, description, aliasSeparator, typeSeparator, initialIndent, names, namesString, namesStringLen, typeSeparatorString, typeSeparatorStringLen, wrap; + mainName = option.option, shortNames = (ref$ = option.shortNames) != null + ? ref$ + : [], longNames = (ref$ = option.longNames) != null + ? ref$ + : [], type = option.type, description = option.description; + aliasSeparator = arg$.aliasSeparator, typeSeparator = arg$.typeSeparator, initialIndent = arg$.initialIndent; + if (option.negateName) { + mainName = "no-" + mainName; + if (longNames) { + longNames = map(function(it){ + return "no-" + it; + }, longNames); + } + } + names = mainName.length === 1 + ? [mainName].concat(shortNames, longNames) + : shortNames.concat([mainName], longNames); + namesString = map(nameToRaw, names).join(aliasSeparator); + namesStringLen = namesString.length; + typeSeparatorString = mainName === 'NUM' ? '::' : typeSeparator; + typeSeparatorStringLen = typeSeparatorString.length; + if (maxWidth != null && !option.boolean && initialIndent + namesStringLen + typeSeparatorStringLen + type.length > maxWidth) { + wrap = wordwrap(initialIndent + namesStringLen + typeSeparatorStringLen, maxWidth); + return namesString + "" + typeSeparatorString + wrap(type).replace(/^\s+/, ''); + } else { + return namesString + "" + (option.boolean + ? '' + : typeSeparatorString + "" + type); + } + }; + setHelpStyleDefaults = function(helpStyle){ + helpStyle.aliasSeparator == null && (helpStyle.aliasSeparator = ', '); + helpStyle.typeSeparator == null && (helpStyle.typeSeparator = ' '); + helpStyle.descriptionSeparator == null && (helpStyle.descriptionSeparator = ' '); + helpStyle.initialIndent == null && (helpStyle.initialIndent = 2); + helpStyle.secondaryIndent == null && (helpStyle.secondaryIndent = 4); + helpStyle.maxPadFactor == null && (helpStyle.maxPadFactor = 1.5); + }; + generateHelpForOption = function(getOption, arg$){ + var stdout, helpStyle, ref$; + stdout = arg$.stdout, helpStyle = (ref$ = arg$.helpStyle) != null + ? ref$ + : {}; + setHelpStyleDefaults(helpStyle); + return function(optionName){ + var maxWidth, wrap, option, e, pre, defaultString, restPositionalString, description, fullDescription, that, preDescription, descriptionString, exampleString, examples, seperator; + maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null; + wrap = maxWidth ? wordwrap(maxWidth) : id; + try { + option = getOption(dasherize(optionName)); + } catch (e$) { + e = e$; + return e.message; + } + pre = getPreText(option, helpStyle); + defaultString = option['default'] && !option.negateName ? "\ndefault: " + option['default'] : ''; + restPositionalString = option.restPositional ? 'Everything after this option is considered a positional argument, even if it looks like an option.' : ''; + description = option.longDescription || option.description && sentencize(option.description); + fullDescription = description && restPositionalString + ? description + " " + restPositionalString + : (that = description || restPositionalString) ? that : ''; + preDescription = 'description:'; + descriptionString = !fullDescription + ? '' + : maxWidth && fullDescription.length - 1 - preDescription.length > maxWidth + ? "\n" + preDescription + "\n" + wrap(fullDescription) + : "\n" + preDescription + " " + fullDescription; + exampleString = (that = option.example) ? (examples = [].concat(that), examples.length > 1 + ? "\nexamples:\n" + unlines(examples) + : "\nexample: " + examples[0]) : ''; + seperator = defaultString || descriptionString || exampleString ? "\n" + repeatString$('=', pre.length) : ''; + return pre + "" + seperator + defaultString + descriptionString + exampleString; + }; + }; + generateHelp = function(arg$){ + var options, prepend, append, helpStyle, ref$, stdout, aliasSeparator, typeSeparator, descriptionSeparator, maxPadFactor, initialIndent, secondaryIndent; + options = arg$.options, prepend = arg$.prepend, append = arg$.append, helpStyle = (ref$ = arg$.helpStyle) != null + ? ref$ + : {}, stdout = arg$.stdout; + setHelpStyleDefaults(helpStyle); + aliasSeparator = helpStyle.aliasSeparator, typeSeparator = helpStyle.typeSeparator, descriptionSeparator = helpStyle.descriptionSeparator, maxPadFactor = helpStyle.maxPadFactor, initialIndent = helpStyle.initialIndent, secondaryIndent = helpStyle.secondaryIndent; + return function(arg$){ + var ref$, showHidden, interpolate, maxWidth, output, out, data, optionCount, totalPreLen, preLens, i$, len$, item, that, pre, descParts, desc, preLen, sortedPreLens, maxPreLen, preLenMean, x, padAmount, descSepLen, fullWrapCount, partialWrapCount, descLen, totalLen, initialSpace, wrapAllFull, i, wrap; + ref$ = arg$ != null + ? arg$ + : {}, showHidden = ref$.showHidden, interpolate = ref$.interpolate; + maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null; + output = []; + out = function(it){ + return output.push(it != null ? it : ''); + }; + if (prepend) { + out(interpolate ? interp(prepend, interpolate) : prepend); + out(); + } + data = []; + optionCount = 0; + totalPreLen = 0; + preLens = []; + for (i$ = 0, len$ = (ref$ = options).length; i$ < len$; ++i$) { + item = ref$[i$]; + if (showHidden || !item.hidden) { + if (that = item.heading) { + data.push({ + type: 'heading', + value: that + }); + } else { + pre = getPreText(item, helpStyle, maxWidth); + descParts = []; + if ((that = item.description) != null) { + descParts.push(that); + } + if (that = item['enum']) { + descParts.push("either: " + naturalJoin(that)); + } + if (item['default'] && !item.negateName) { + descParts.push("default: " + item['default']); + } + desc = descParts.join(' - '); + data.push({ + type: 'option', + pre: pre, + desc: desc, + descLen: desc.length + }); + preLen = pre.length; + optionCount++; + totalPreLen += preLen; + preLens.push(preLen); + } + } + } + sortedPreLens = sort(preLens); + maxPreLen = sortedPreLens[sortedPreLens.length - 1]; + preLenMean = initialIndent + totalPreLen / optionCount; + x = optionCount > 2 ? min(preLenMean * maxPadFactor, maxPreLen) : maxPreLen; + for (i$ = sortedPreLens.length - 1; i$ >= 0; --i$) { + preLen = sortedPreLens[i$]; + if (preLen <= x) { + padAmount = preLen; + break; + } + } + descSepLen = descriptionSeparator.length; + if (maxWidth != null) { + fullWrapCount = 0; + partialWrapCount = 0; + for (i$ = 0, len$ = data.length; i$ < len$; ++i$) { + item = data[i$]; + if (item.type === 'option') { + pre = item.pre, desc = item.desc, descLen = item.descLen; + if (descLen === 0) { + item.wrap = 'none'; + } else { + preLen = max(padAmount, pre.length) + initialIndent + descSepLen; + totalLen = preLen + descLen; + if (totalLen > maxWidth) { + if (descLen / 2.5 > maxWidth - preLen) { + fullWrapCount++; + item.wrap = 'full'; + } else { + partialWrapCount++; + item.wrap = 'partial'; + } + } else { + item.wrap = 'none'; + } + } + } + } + } + initialSpace = repeatString$(' ', initialIndent); + wrapAllFull = optionCount > 1 && fullWrapCount + partialWrapCount * 0.5 > optionCount * 0.5; + for (i$ = 0, len$ = data.length; i$ < len$; ++i$) { + i = i$; + item = data[i$]; + if (item.type === 'heading') { + if (i !== 0) { + out(); + } + out(item.value + ":"); + } else { + pre = item.pre, desc = item.desc, descLen = item.descLen, wrap = item.wrap; + if (maxWidth != null) { + if (wrapAllFull || wrap === 'full') { + wrap = wordwrap(initialIndent + secondaryIndent, maxWidth); + out(initialSpace + "" + pre + "\n" + wrap(desc)); + continue; + } else if (wrap === 'partial') { + wrap = wordwrap(initialIndent + descSepLen + max(padAmount, pre.length), maxWidth); + out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + wrap(desc).replace(/^\s+/, '')); + continue; + } + } + if (descLen === 0) { + out(initialSpace + "" + pre); + } else { + out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + desc); + } + } + } + if (append) { + out(); + out(interpolate ? interp(append, interpolate) : append); + } + return unlines(output); + }; + }; + function pad(str, num){ + var len, padAmount; + len = str.length; + padAmount = num - len; + return str + "" + repeatString$(' ', padAmount > 0 ? padAmount : 0); + } + function sentencize(str){ + var first, rest, period; + first = str.charAt(0).toUpperCase(); + rest = str.slice(1); + period = /[\.!\?]$/.test(str) ? '' : '.'; + return first + "" + rest + period; + } + function interp(string, object){ + return string.replace(/{{([a-zA-Z$_][a-zA-Z$_0-9]*)}}/g, function(arg$, key){ + var ref$; + return (ref$ = object[key]) != null + ? ref$ + : "{{" + key + "}}"; + }); + } + module.exports = { + generateHelp: generateHelp, + generateHelpForOption: generateHelpForOption + }; + function repeatString$(str, n){ + for (var r = ''; n > 0; (n >>= 1) && (str += str)) if (n & 1) r += str; + return r; + } +}).call(this); diff --git a/node_modules/optionator/lib/index.js b/node_modules/optionator/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..436b7cc929c99729bb462fa57d045766db56ce2e --- /dev/null +++ b/node_modules/optionator/lib/index.js @@ -0,0 +1,465 @@ +// Generated by LiveScript 1.6.0 +(function(){ + var VERSION, ref$, id, map, compact, any, groupBy, partition, chars, isItNaN, keys, Obj, camelize, deepIs, closestString, nameToRaw, dasherize, naturalJoin, generateHelp, generateHelpForOption, parsedTypeCheck, parseType, parseLevn, camelizeKeys, parseString, main, toString$ = {}.toString, slice$ = [].slice, arrayFrom$ = Array.from || function(x){return slice$.call(x);}; + VERSION = '0.9.4'; + ref$ = require('prelude-ls'), id = ref$.id, map = ref$.map, compact = ref$.compact, any = ref$.any, groupBy = ref$.groupBy, partition = ref$.partition, chars = ref$.chars, isItNaN = ref$.isItNaN, keys = ref$.keys, Obj = ref$.Obj, camelize = ref$.camelize; + deepIs = require('deep-is'); + ref$ = require('./util'), closestString = ref$.closestString, nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin; + ref$ = require('./help'), generateHelp = ref$.generateHelp, generateHelpForOption = ref$.generateHelpForOption; + ref$ = require('type-check'), parsedTypeCheck = ref$.parsedTypeCheck, parseType = ref$.parseType; + parseLevn = require('levn').parsedTypeParse; + camelizeKeys = function(obj){ + var key, value, resultObj$ = {}; + for (key in obj) { + value = obj[key]; + resultObj$[camelize(key)] = value; + } + return resultObj$; + }; + parseString = function(string){ + var assignOpt, regex, replaceRegex, result; + assignOpt = '--?[a-zA-Z][-a-z-A-Z0-9]*='; + regex = RegExp('(?:' + assignOpt + ')?(?:\'(?:\\\\\'|[^\'])+\'|"(?:\\\\"|[^"])+")|[^\'"\\s]+', 'g'); + replaceRegex = RegExp('^(' + assignOpt + ')?[\'"]([\\s\\S]*)[\'"]$'); + result = map(function(it){ + return it.replace(replaceRegex, '$1$2'); + }, string.match(regex) || []); + return result; + }; + main = function(libOptions){ + var opts, defaults, required, traverse, getOption, parse; + opts = {}; + defaults = {}; + required = []; + if (toString$.call(libOptions.stdout).slice(8, -1) === 'Undefined') { + libOptions.stdout = process.stdout; + } + libOptions.positionalAnywhere == null && (libOptions.positionalAnywhere = true); + libOptions.typeAliases == null && (libOptions.typeAliases = {}); + libOptions.defaults == null && (libOptions.defaults = {}); + if (libOptions.concatRepeatedArrays != null) { + libOptions.defaults.concatRepeatedArrays = libOptions.concatRepeatedArrays; + } + if (libOptions.mergeRepeatedObjects != null) { + libOptions.defaults.mergeRepeatedObjects = libOptions.mergeRepeatedObjects; + } + traverse = function(options){ + var i$, len$, option, name, k, ref$, v, type, that, e, parsedPossibilities, parsedType, j$, len1$, possibility, rawDependsType, dependsOpts, dependsType, cra, alias, shortNames, longNames; + if (toString$.call(options).slice(8, -1) !== 'Array') { + throw new Error('No options defined.'); + } + for (i$ = 0, len$ = options.length; i$ < len$; ++i$) { + option = options[i$]; + if (option.heading == null) { + name = option.option; + if (opts[name] != null) { + throw new Error("Option '" + name + "' already defined."); + } + for (k in ref$ = libOptions.defaults) { + v = ref$[k]; + option[k] == null && (option[k] = v); + } + if (option.type === 'Boolean') { + option.boolean == null && (option.boolean = true); + } + if (option.parsedType == null) { + if (!option.type) { + throw new Error("No type defined for option '" + name + "'."); + } + try { + type = (that = libOptions.typeAliases[option.type]) != null + ? that + : option.type; + option.parsedType = parseType(type); + } catch (e$) { + e = e$; + throw new Error("Option '" + name + "': Error parsing type '" + option.type + "': " + e.message); + } + } + if (option['default']) { + try { + defaults[name] = parseLevn(option.parsedType, option['default']); + } catch (e$) { + e = e$; + throw new Error("Option '" + name + "': Error parsing default value '" + option['default'] + "' for type '" + option.type + "': " + e.message); + } + } + if (option['enum'] && !option.parsedPossiblities) { + parsedPossibilities = []; + parsedType = option.parsedType; + for (j$ = 0, len1$ = (ref$ = option['enum']).length; j$ < len1$; ++j$) { + possibility = ref$[j$]; + try { + parsedPossibilities.push(parseLevn(parsedType, possibility)); + } catch (e$) { + e = e$; + throw new Error("Option '" + name + "': Error parsing enum value '" + possibility + "' for type '" + option.type + "': " + e.message); + } + } + option.parsedPossibilities = parsedPossibilities; + } + if (that = option.dependsOn) { + if (that.length) { + ref$ = [].concat(option.dependsOn), rawDependsType = ref$[0], dependsOpts = slice$.call(ref$, 1); + dependsType = rawDependsType.toLowerCase(); + if (dependsOpts.length) { + if (dependsType === 'and' || dependsType === 'or') { + option.dependsOn = [dependsType].concat(arrayFrom$(dependsOpts)); + } else { + throw new Error("Option '" + name + "': If you have more than one dependency, you must specify either 'and' or 'or'"); + } + } else { + if ((ref$ = dependsType.toLowerCase()) === 'and' || ref$ === 'or') { + option.dependsOn = null; + } else { + option.dependsOn = ['and', rawDependsType]; + } + } + } else { + option.dependsOn = null; + } + } + if (option.required) { + required.push(name); + } + opts[name] = option; + if (option.concatRepeatedArrays != null) { + cra = option.concatRepeatedArrays; + if ('Boolean' === toString$.call(cra).slice(8, -1)) { + option.concatRepeatedArrays = [cra, {}]; + } else if (cra.length === 1) { + option.concatRepeatedArrays = [cra[0], {}]; + } else if (cra.length !== 2) { + throw new Error("Invalid setting for concatRepeatedArrays"); + } + } + if (option.alias || option.aliases) { + if (name === 'NUM') { + throw new Error("-NUM option can't have aliases."); + } + if (option.alias) { + option.aliases == null && (option.aliases = [].concat(option.alias)); + } + for (j$ = 0, len1$ = (ref$ = option.aliases).length; j$ < len1$; ++j$) { + alias = ref$[j$]; + if (opts[alias] != null) { + throw new Error("Option '" + alias + "' already defined."); + } + opts[alias] = option; + } + ref$ = partition(fn$, option.aliases), shortNames = ref$[0], longNames = ref$[1]; + option.shortNames == null && (option.shortNames = shortNames); + option.longNames == null && (option.longNames = longNames); + } + if ((!option.aliases || option.shortNames.length === 0) && option.type === 'Boolean' && option['default'] === 'true') { + option.negateName = true; + } + } + } + function fn$(it){ + return it.length === 1; + } + }; + traverse(libOptions.options); + getOption = function(name){ + var opt, possiblyMeant; + opt = opts[name]; + if (opt == null) { + possiblyMeant = closestString(keys(opts), name); + throw new Error("Invalid option '" + nameToRaw(name) + "'" + (possiblyMeant ? " - perhaps you meant '" + nameToRaw(possiblyMeant) + "'?" : '.')); + } + return opt; + }; + parse = function(input, arg$){ + var slice, obj, positional, restPositional, overrideRequired, prop, setValue, setDefaults, checkRequired, mutuallyExclusiveError, checkMutuallyExclusive, checkDependency, checkDependencies, checkProp, args, key, value, option, ref$, i$, len$, arg, that, result, short, argName, usingAssign, val, flags, len, j$, len1$, i, flag, opt, name, valPrime, negated, noedName; + slice = (arg$ != null + ? arg$ + : {}).slice; + obj = {}; + positional = []; + restPositional = false; + overrideRequired = false; + prop = null; + setValue = function(name, value){ + var opt, val, cra, e, currentType; + opt = getOption(name); + if (opt.boolean) { + val = value; + } else { + try { + cra = opt.concatRepeatedArrays; + if (cra != null && cra[0] && cra[1].oneValuePerFlag && opt.parsedType.length === 1 && opt.parsedType[0].structure === 'array') { + val = [parseLevn(opt.parsedType[0].of, value)]; + } else { + val = parseLevn(opt.parsedType, value); + } + } catch (e$) { + e = e$; + throw new Error("Invalid value for option '" + name + "' - expected type " + opt.type + ", received value: " + value + "."); + } + if (opt['enum'] && !any(function(it){ + return deepIs(it, val); + }, opt.parsedPossibilities)) { + throw new Error("Option " + name + ": '" + val + "' not one of " + naturalJoin(opt['enum']) + "."); + } + } + currentType = toString$.call(obj[name]).slice(8, -1); + if (obj[name] != null) { + if (opt.concatRepeatedArrays != null && opt.concatRepeatedArrays[0] && currentType === 'Array') { + obj[name] = obj[name].concat(val); + } else if (opt.mergeRepeatedObjects && currentType === 'Object') { + import$(obj[name], val); + } else { + obj[name] = val; + } + } else { + obj[name] = val; + } + if (opt.restPositional) { + restPositional = true; + } + if (opt.overrideRequired) { + overrideRequired = true; + } + }; + setDefaults = function(){ + var name, ref$, value; + for (name in ref$ = defaults) { + value = ref$[name]; + if (obj[name] == null) { + obj[name] = value; + } + } + }; + checkRequired = function(){ + var i$, ref$, len$, name; + if (overrideRequired) { + return; + } + for (i$ = 0, len$ = (ref$ = required).length; i$ < len$; ++i$) { + name = ref$[i$]; + if (!obj[name]) { + throw new Error("Option " + nameToRaw(name) + " is required."); + } + } + }; + mutuallyExclusiveError = function(first, second){ + throw new Error("The options " + nameToRaw(first) + " and " + nameToRaw(second) + " are mutually exclusive - you cannot use them at the same time."); + }; + checkMutuallyExclusive = function(){ + var rules, i$, len$, rule, present, j$, len1$, element, k$, len2$, opt; + rules = libOptions.mutuallyExclusive; + if (!rules) { + return; + } + for (i$ = 0, len$ = rules.length; i$ < len$; ++i$) { + rule = rules[i$]; + present = null; + for (j$ = 0, len1$ = rule.length; j$ < len1$; ++j$) { + element = rule[j$]; + if (toString$.call(element).slice(8, -1) === 'Array') { + for (k$ = 0, len2$ = element.length; k$ < len2$; ++k$) { + opt = element[k$]; + if (opt in obj) { + if (present != null) { + mutuallyExclusiveError(present, opt); + } else { + present = opt; + break; + } + } + } + } else { + if (element in obj) { + if (present != null) { + mutuallyExclusiveError(present, element); + } else { + present = element; + } + } + } + } + } + }; + checkDependency = function(option){ + var dependsOn, type, targetOptionNames, i$, len$, targetOptionName, targetOption; + dependsOn = option.dependsOn; + if (!dependsOn || option.dependenciesMet) { + return true; + } + type = dependsOn[0], targetOptionNames = slice$.call(dependsOn, 1); + for (i$ = 0, len$ = targetOptionNames.length; i$ < len$; ++i$) { + targetOptionName = targetOptionNames[i$]; + targetOption = obj[targetOptionName]; + if (targetOption && checkDependency(targetOption)) { + if (type === 'or') { + return true; + } + } else if (type === 'and') { + throw new Error("The option '" + option.option + "' did not have its dependencies met."); + } + } + if (type === 'and') { + return true; + } else { + throw new Error("The option '" + option.option + "' did not meet any of its dependencies."); + } + }; + checkDependencies = function(){ + var name; + for (name in obj) { + checkDependency(opts[name]); + } + }; + checkProp = function(){ + if (prop) { + throw new Error("Value for '" + prop + "' of type '" + getOption(prop).type + "' required."); + } + }; + switch (toString$.call(input).slice(8, -1)) { + case 'String': + args = parseString(input.slice(slice != null ? slice : 0)); + break; + case 'Array': + args = input.slice(slice != null ? slice : 2); + break; + case 'Object': + obj = {}; + for (key in input) { + value = input[key]; + if (key !== '_') { + option = getOption(dasherize(key)); + if (parsedTypeCheck(option.parsedType, value)) { + obj[option.option] = value; + } else { + throw new Error("Option '" + option.option + "': Invalid type for '" + value + "' - expected type '" + option.type + "'."); + } + } + } + checkMutuallyExclusive(); + checkDependencies(); + setDefaults(); + checkRequired(); + return ref$ = camelizeKeys(obj), ref$._ = input._ || [], ref$; + default: + throw new Error("Invalid argument to 'parse': " + input + "."); + } + for (i$ = 0, len$ = args.length; i$ < len$; ++i$) { + arg = args[i$]; + if (arg === '--') { + restPositional = true; + } else if (restPositional) { + positional.push(arg); + } else { + if (that = arg.match(/^(--?)([a-zA-Z][-a-zA-Z0-9]*)(=)?(.*)?$/)) { + result = that; + checkProp(); + short = result[1].length === 1; + argName = result[2]; + usingAssign = result[3] != null; + val = result[4]; + if (usingAssign && val == null) { + throw new Error("No value for '" + argName + "' specified."); + } + if (short) { + flags = chars(argName); + len = flags.length; + for (j$ = 0, len1$ = flags.length; j$ < len1$; ++j$) { + i = j$; + flag = flags[j$]; + opt = getOption(flag); + name = opt.option; + if (restPositional) { + positional.push(flag); + } else if (i === len - 1) { + if (usingAssign) { + valPrime = opt.boolean ? parseLevn([{ + type: 'Boolean' + }], val) : val; + setValue(name, valPrime); + } else if (opt.boolean) { + setValue(name, true); + } else { + prop = name; + } + } else if (opt.boolean) { + setValue(name, true); + } else { + throw new Error("Can't set argument '" + flag + "' when not last flag in a group of short flags."); + } + } + } else { + negated = false; + if (that = argName.match(/^no-(.+)$/)) { + negated = true; + noedName = that[1]; + opt = getOption(noedName); + } else { + opt = getOption(argName); + } + name = opt.option; + if (opt.boolean) { + valPrime = usingAssign ? parseLevn([{ + type: 'Boolean' + }], val) : true; + if (negated) { + setValue(name, !valPrime); + } else { + setValue(name, valPrime); + } + } else { + if (negated) { + throw new Error("Only use 'no-' prefix for Boolean options, not with '" + noedName + "'."); + } + if (usingAssign) { + setValue(name, val); + } else { + prop = name; + } + } + } + } else if (that = arg.match(/^-([0-9]+(?:\.[0-9]+)?)$/)) { + opt = opts.NUM; + if (!opt) { + throw new Error('No -NUM option defined.'); + } + setValue(opt.option, that[1]); + } else { + if (prop) { + setValue(prop, arg); + prop = null; + } else { + positional.push(arg); + if (!libOptions.positionalAnywhere) { + restPositional = true; + } + } + } + } + } + checkProp(); + checkMutuallyExclusive(); + checkDependencies(); + setDefaults(); + checkRequired(); + return ref$ = camelizeKeys(obj), ref$._ = positional, ref$; + }; + return { + parse: parse, + parseArgv: function(it){ + return parse(it, { + slice: 2 + }); + }, + generateHelp: generateHelp(libOptions), + generateHelpForOption: generateHelpForOption(getOption, libOptions) + }; + }; + main.VERSION = VERSION; + module.exports = main; + function import$(obj, src){ + var own = {}.hasOwnProperty; + for (var key in src) if (own.call(src, key)) obj[key] = src[key]; + return obj; + } +}).call(this); diff --git a/node_modules/optionator/lib/util.js b/node_modules/optionator/lib/util.js new file mode 100644 index 0000000000000000000000000000000000000000..5bc0cbb69e66aab262d0c2f400c4588a49c0da55 --- /dev/null +++ b/node_modules/optionator/lib/util.js @@ -0,0 +1,54 @@ +// Generated by LiveScript 1.6.0 +(function(){ + var prelude, map, sortBy, fl, closestString, nameToRaw, dasherize, naturalJoin; + prelude = require('prelude-ls'), map = prelude.map, sortBy = prelude.sortBy; + fl = require('fast-levenshtein'); + closestString = function(possibilities, input){ + var distances, ref$, string, distance; + if (!possibilities.length) { + return; + } + distances = map(function(it){ + var ref$, longer, shorter; + ref$ = input.length > it.length + ? [input, it] + : [it, input], longer = ref$[0], shorter = ref$[1]; + return { + string: it, + distance: fl.get(longer, shorter) + }; + })( + possibilities); + ref$ = sortBy(function(it){ + return it.distance; + }, distances)[0], string = ref$.string, distance = ref$.distance; + return string; + }; + nameToRaw = function(name){ + if (name.length === 1 || name === 'NUM') { + return "-" + name; + } else { + return "--" + name; + } + }; + dasherize = function(string){ + if (/^[A-Z]/.test(string)) { + return string; + } else { + return prelude.dasherize(string); + } + }; + naturalJoin = function(array){ + if (array.length < 3) { + return array.join(' or '); + } else { + return array.slice(0, -1).join(', ') + ", or " + array[array.length - 1]; + } + }; + module.exports = { + closestString: closestString, + nameToRaw: nameToRaw, + dasherize: dasherize, + naturalJoin: naturalJoin + }; +}).call(this);