This commit is contained in:
nik
2025-10-01 22:50:58 +03:00
parent 0b35b5b968
commit 2767145612
296 changed files with 39425 additions and 0 deletions

96
Jenkinsfile vendored Normal file
View File

@@ -0,0 +1,96 @@
pipeline {
agent any
parameters {
string(name: 'ALLOWED_TELEGRAM_IDS', defaultValue: '792742394', description: '')
}
environment {
BOT_TOKEN = credentials('tg-bot-token')
BASE_DIR = '/srv/files'
BOT_HOST = 'storage.fymio.us'
REMOTE_USER = 'deploy'
SSH_CRED = 'bot-ssh'
REMOTE_DIR = '/srv/tg-bot'
REPO_URL = 'https://git.fymio.us/nik/fymious_tg_bot'
BRANCH = 'main'
}
stages {
stage('Checkout') {
steps { checkout scm }
}
stage('TrustHost') {
steps {
sh '''
mkdir -p ~/.ssh
ssh-keyscan -H ${BOT_HOST} >> ~/.ssh/known_hosts
'''
}
}
stage('Ship & Restart') {
steps {
sshagent(credentials: [env.SSH_CRED]) {
sh '''
ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${BOT_HOST} "
export REMOTE_DIR='${REMOTE_DIR}'
export REPO_URL='${REPO_URL}'
export BRANCH='${BRANCH}'
export REMOTE_USER='${REMOTE_USER}'
export BOT_TOKEN='${BOT_TOKEN}'
export BASE_DIR='${BASE_DIR}'
export ALLOWED_TELEGRAM_IDS='${ALLOWED_TELEGRAM_IDS}'
set -euo pipefail
DIR=\\$REMOTE_DIR
REPO=\\$REPO_URL
BR=\\$BRANCH
# Create directory without sudo first
mkdir -p \\$DIR || echo 'Directory might already exist'
# Clone or update repository
if [ -d \\\"\\$DIR/.git\\\" ]; then
cd \\$DIR
git fetch origin \\$BR
git reset --hard origin/\\$BR
else
if [ -z \\\"\\\$(ls -A \\\"\\$DIR\\\" 2>/dev/null || true)\\\" ]; then
git clone --depth 1 -b \\$BR \\$REPO \\$DIR
else
rm -rf \\$DIR/*
git clone --depth 1 -b \\$BR \\$REPO \\$DIR
fi
fi
# Create .env file
cd \\$DIR
echo \\\"BOT_TOKEN=\\$BOT_TOKEN\\\" > .env
echo \\\"BASE_DIR=\\$BASE_DIR\\\" >> .env
echo \\\"ALLOWED_TELEGRAM_IDS=\\$ALLOWED_TELEGRAM_IDS\\\" >> .env
# Install npm dependencies if needed
if [ -f package.json ]; then
if command -v npm >/dev/null 2>&1; then
npm ci || npm install
fi
fi
# Try to restart service with sudo (might need NOPASSWD configured)
echo 'Attempting to restart service...'
sudo systemctl restart tg_filebrowser_bot || echo 'Service restart failed - might need manual restart'
# Show service status for debugging
sudo systemctl status tg_filebrowser_bot || systemctl --user status tg_filebrowser_bot || echo 'Could not get service status'
"
'''
}
}
}
stage('LogsIfFailed') {
when { expression { currentBuild.currentResult == 'FAILURE' } }
steps {
sshagent(credentials: [env.SSH_CRED]) {
sh 'ssh ${REMOTE_USER}@${BOT_HOST} "journalctl -u tg_filebrowser_bot -n 200 --no-pager || journalctl --user -u tg_filebrowser_bot -n 200 --no-pager || echo \\"Could not get logs\\""'
}
}
}
}
}

13
deploy.sh Executable file
View File

@@ -0,0 +1,13 @@
#!/usr/bin/env bash
set -euo pipefail
APP_DIR="/srv/tg-bot"
mkdir -p "$APP_DIR"
rsync -a --delete --exclude ".git" ./ "$APP_DIR"/
cd "$APP_DIR"
if [ -f package.json ]; then
if command -v npm >/dev/null 2>&1; then
npm ci || npm install
fi
fi
systemctl restart tg_filebrowser_bot

1
node_modules/.bin/telegraf generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../telegraf/lib/cli.mjs

192
node_modules/.package-lock.json generated vendored Normal file
View File

@@ -0,0 +1,192 @@
{
"name": "tg-bot",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/@telegraf/types": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/@telegraf/types/-/types-7.1.0.tgz",
"integrity": "sha512-kGevOIbpMcIlCDeorKGpwZmdH7kHbqlk/Yj6dEpJMKEQw5lk0KVQY0OLXaCswy8GqlIVLd5625OB+rAntP9xVw==",
"license": "MIT"
},
"node_modules/abort-controller": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
"integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
"license": "MIT",
"dependencies": {
"event-target-shim": "^5.0.0"
},
"engines": {
"node": ">=6.5"
}
},
"node_modules/buffer-alloc": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/buffer-alloc/-/buffer-alloc-1.2.0.tgz",
"integrity": "sha512-CFsHQgjtW1UChdXgbyJGtnm+O/uLQeZdtbDo8mfUgYXCHSM1wgrVxXm6bSyrUuErEb+4sYVGCzASBRot7zyrow==",
"license": "MIT",
"dependencies": {
"buffer-alloc-unsafe": "^1.1.0",
"buffer-fill": "^1.0.0"
}
},
"node_modules/buffer-alloc-unsafe": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/buffer-alloc-unsafe/-/buffer-alloc-unsafe-1.1.0.tgz",
"integrity": "sha512-TEM2iMIEQdJ2yjPJoSIsldnleVaAk1oW3DBVUykyOLsEsFmEc9kn+SFFPz+gl54KQNxlDnAwCXosOS9Okx2xAg==",
"license": "MIT"
},
"node_modules/buffer-fill": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/buffer-fill/-/buffer-fill-1.0.0.tgz",
"integrity": "sha512-T7zexNBwiiaCOGDg9xNX9PBmjrubblRkENuptryuI64URkXDFum9il/JGL8Lm8wYfAXpredVXXZz7eMHilimiQ==",
"license": "MIT"
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
"integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/event-target-shim": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
"integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/mri": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",
"integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"license": "MIT",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/p-timeout": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-4.1.0.tgz",
"integrity": "sha512-+/wmHtzJuWii1sXn3HCuH/FTwGhrp4tmJTxSKJbfS+vkipci6osxXM5mY0jUiRzWKMTgUT8l7HFbeSwZAynqHw==",
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/safe-compare": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/safe-compare/-/safe-compare-1.1.4.tgz",
"integrity": "sha512-b9wZ986HHCo/HbKrRpBJb2kqXMK9CEWIE1egeEvZsYn69ay3kdfl9nG3RyOcR+jInTDf7a86WQ1d4VJX7goSSQ==",
"license": "MIT",
"dependencies": {
"buffer-alloc": "^1.2.0"
}
},
"node_modules/sandwich-stream": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/sandwich-stream/-/sandwich-stream-2.0.2.tgz",
"integrity": "sha512-jLYV0DORrzY3xaz/S9ydJL6Iz7essZeAfnAavsJ+zsJGZ1MOnsS52yRjU3uF3pJa/lla7+wisp//fxOwOH8SKQ==",
"license": "Apache-2.0",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/telegraf": {
"version": "4.16.3",
"resolved": "https://registry.npmjs.org/telegraf/-/telegraf-4.16.3.tgz",
"integrity": "sha512-yjEu2NwkHlXu0OARWoNhJlIjX09dRktiMQFsM678BAH/PEPVwctzL67+tvXqLCRQQvm3SDtki2saGO9hLlz68w==",
"license": "MIT",
"dependencies": {
"@telegraf/types": "^7.1.0",
"abort-controller": "^3.0.0",
"debug": "^4.3.4",
"mri": "^1.2.0",
"node-fetch": "^2.7.0",
"p-timeout": "^4.1.0",
"safe-compare": "^1.1.4",
"sandwich-stream": "^2.0.2"
},
"bin": {
"telegraf": "lib/cli.mjs"
},
"engines": {
"node": "^12.20.0 || >=14.13.1"
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"license": "MIT"
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"license": "BSD-2-Clause"
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"license": "MIT",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
}
}
}

21
node_modules/@telegraf/types/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) KnorpelSenf & Telegraf 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.

113
node_modules/@telegraf/types/README.md generated vendored Normal file
View File

@@ -0,0 +1,113 @@
# Types for the Telegram Bot API [![Deno shield](https://img.shields.io/static/v1?label=Built%20for&message=Deno&style=flat-square&logo=deno&labelColor=000&color=fff)](https://deno.land/x/telegraf_types)
[![Bot API Version](https://img.shields.io/badge/Bot%20API-v6.9-f36caf.svg?style=flat-square&logo=Telegram&labelColor=white&color=blue)](https://core.telegram.org/bots/api) [![NPM version](https://img.shields.io/npm/v/@telegraf/types?style=flat-square&logo=npm&labelColor=fff&color=c53635)](https://npmjs.com/package/@telegraf/types)
This project is a fork of [@KnorpelSenf/typegram](https://github.com/KnorpelSenf/typegram), specialised for Telegraf. Typegram is legacy, and now backported from [@grammyjs/types](https://github.com/grammyjs/types).
This fork keeps Telegram Bot API types updated for Telegraf. This project provides TypeScript types for the entire [Telegram Bot API](https://core.telegram.org/bots/api).
It contains zero bytes of executable code.
## Installation
```bash
npm install --save-dev @telegraf/types
```
## Available Types
Generally, this package just exposes a huge load of `interface`s that correspond to the **types** used throughout the Telegram Bot API.
Note that the API specification sometimes only has one name for multiple variants of a type, e.g. there are a number of different `Update`s you can receive, but they're all just called `Update`.
This package represents such types as large unions of all possible options of what an `Update` could be, such that type narrowing can work as expected on your side.
If you need to access the individual variants of an `Update`, refer to `Update.MessageUpdate` and its siblings.
In fact, this pattern is used for various types, namely:
- `Update`
- `Message`
- `CallbackQuery`
- `Chat`
- `ChatFromGetChat`
- `InlineKeyboardButton`
- `KeyboardButton`
- `MessageEntity`
- `Location`
(Naturally, when the API specification is actually modelling types to be unions (e.g. `InlineQueryResult`), this is reflected here as a union type, too.)
## Using API Response objects
The Telegram Bot API does not return just the requested data in the body of the response objects.
Instead, they are wrapped inside an object that has an `ok: boolean` status flag, indicating success or failure of the preceding API request.
This outer object is modelled in `@telegraf/types` by the `ApiResponse` type.
## Customizing `InputFile` and accessing API methods
The Telegram Bot API lets bots send files in [three different ways](https://core.telegram.org/bots/api#sending-files).
Two of those ways are by specifying a `string`—either a `file_id` or a URL.
The third option, however, is by uploading files to the server using multipart/form-data.
The first two means to send a file are already covered by the type annotations across the library.
In all places where a `file_id` or a URL is permitted, the corresponding property allows a `string`.
We will now look at the type declarations that are relevant for uploading files directly.
Depending on the code you're using the types for, you may want to support different ways to specify the file to be uploaded.
As an example, you may want to be able to make calls to `sendDocument` with an object that conforms to `{ path: string }` in order to specify the location of a local file.
(Your code is then assumed to able to translate calls to `sendDocument` and the like to multipart/form-data uploads when supplied with an object alike `{ path: '/tmp/file.txt' }` in the `document` property of the argument object.)
This library cannot automatically know what objects you want to support as `InputFile`s.
However, you can specify your own version of what an `InputFile` is throughout all affected methods and interfaces.
For instance, let's stick with our example and say that you want to support `InputFile`s of the following type.
```ts
interface MyInputFile {
path: string;
}
```
You can then customize the types to fit your needs by passing your custom `InputFile` to the `ApiMethods` type.
```ts
import * as Telegram from "@telegraf/types";
type API = Telegram.ApiMethods<MyInputFile>;
```
You can now access all types that must respect `MyInputFile` through the `API` type:
```ts
// The utility types `Opts` and `Ret`:
type Opts<M extends keyof API> = Telegram.Opts<MyInputFile>[M];
type Ret<M extends keyof API> = Telegram.Ret<MyInputFile>[M];
```
Each method takes just a single argument with a structure that corresponds to the object expected by Telegram.
If you need to directly access that type, consider using `Opts<M>` where `M` is the method name (e.g. `Opts<'getMe'>`).
Each method returns the object that is specified by Telegram.
If you directly need to access the return type of a method, consider using `Ret<M>` where `M` is the method name (e.g. `Opts<'getMe'>`).
```ts
// The adjusted `InputMedia*` types:
type InputMedia = Telegram.InputMedia<MyInputFile>;
type InputMediaPhoto = Telegram.InputMediaPhoto<MyInputFile>;
type InputMediaVideo = Telegram.InputMediaVideo<MyInputFile>;
type InputMediaAnimation = Telegram.InputMediaAnimation<MyInputFile>;
type InputMediaAudio = Telegram.InputMediaAudio<MyInputFile>;
type InputMediaDocument = Telegram.InputMediaDocument<MyInputFile>;
```
Note that interfaces other than the ones mentioned above are unaffected by the customization through `MyInputFile`.
They can simply continue to be imported directly.
## Development
This project is written for Deno and built for Node. Running `npm prepare` runs the deno2node script to build for Node.
## Where do the types come from
They're handwritten. Typegram was started by [@KnorpelSenf](https://github.com/KnorpelSenf), who eventually used it as a starting point for [the grammY types package](https://github.com/grammyjs/types). `@telegraf/types` is based on both packages, and regularly syncs with them and the Bot API.

22
node_modules/@telegraf/types/api.d.ts generated vendored Normal file
View File

@@ -0,0 +1,22 @@
export interface ApiError {
ok: false;
error_code: number;
description: string;
parameters?: ResponseParameters;
}
export interface ApiSuccess<T> {
ok: true;
result: T;
}
/** The response contains an object, which always has a Boolean field 'ok' and may have an optional String field 'description' with a human-readable description of the result. If 'ok' equals true, the request was successful and the result of the query can be found in the 'result' field. In case of an unsuccessful request, 'ok' equals false and the error is explained in the 'description'. An Integer 'error_code' field is also returned, but its contents are subject to change in the future. Some errors may also have an optional field 'parameters' of the type ResponseParameters, which can help to automatically handle the error.
All methods in the Bot API are case-insensitive.
All queries must be made using UTF-8. */
export type ApiResponse<T> = ApiError | ApiSuccess<T>;
/** Describes why a request was unsuccessful. */
export interface ResponseParameters {
/** The group has been migrated to a supergroup with the specified identifier. */
migrate_to_chat_id?: number;
/** In case of exceeding flood control, the number of seconds left to wait before the request can be repeated */
retry_after?: number;
}

40
node_modules/@telegraf/types/default.d.ts generated vendored Normal file
View File

@@ -0,0 +1,40 @@
import { Typegram } from "./proxied";
/** This object represents the contents of a file to be uploaded. Must be posted using multipart/form-data in the usual way that files are uploaded via the browser. */
export type InputFile = never;
type DefaultTypegram = Typegram<InputFile>;
/** Wrapper type to bundle all methods of the Telegram API */
export type Telegram = DefaultTypegram["Telegram"];
/** Utility type providing the argument type for the given method name or `{}` if the method does not take any parameters */
export type Opts<M extends keyof DefaultTypegram["Telegram"]> =
DefaultTypegram["Opts"][M];
export type Ret<M extends keyof DefaultTypegram["Telegram"]> =
DefaultTypegram["Ret"][M];
/** Utility type providing a promisified version of Telegram */
export type TelegramP = DefaultTypegram["TelegramP"];
/** Utility type providing a version Telegram where all methods return ApiResponse objects instead of raw data */
export type TelegramR = DefaultTypegram["TelegramR"];
/** Utility type providing a version Telegram where all methods return Promises of ApiResponse objects, combination of TelegramP and TelegramR */
export type TelegramPR = DefaultTypegram["TelegramPR"];
/** This object represents the content of a media message to be sent. It should be one of
- InputMediaAnimation
- InputMediaDocument
- InputMediaAudio
- InputMediaPhoto
- InputMediaVideo */
export type InputMedia = DefaultTypegram["InputMedia"];
/** Represents a photo to be sent. */
export type InputMediaPhoto = DefaultTypegram["InputMediaPhoto"];
/** Represents a video to be sent. */
export type InputMediaVideo = DefaultTypegram["InputMediaVideo"];
/** Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent. */
export type InputMediaAnimation = DefaultTypegram["InputMediaAnimation"];
/** Represents an audio file to be treated as music to be sent. */
export type InputMediaAudio = DefaultTypegram["InputMediaAudio"];
/** Represents a general file to be sent. */
export type InputMediaDocument = DefaultTypegram["InputMediaDocument"];

10
node_modules/@telegraf/types/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
export * from "./api.js";
export * from "./inline.js";
export * from "./manage.js";
export * from "./markup.js";
export * from "./message.js";
export * from "./methods.js";
export * from "./passport.js";
export * from "./payment.js";
export * from "./settings.js";
export * from "./update.js";

697
node_modules/@telegraf/types/inline.d.ts generated vendored Normal file
View File

@@ -0,0 +1,697 @@
import type { Chat, User } from "./manage.js";
import type { InlineKeyboardMarkup, WebAppInfo } from "./markup.js";
import type { LinkPreviewOptions, Location, MessageEntity, ParseMode } from "./message.js";
import type { LabeledPrice } from "./payment.js";
/** This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results. */
export interface InlineQuery {
/** Unique identifier for this query */
id: string;
/** Sender */
from: User;
/** Text of the query (up to 256 characters) */
query: string;
/** Offset of the results to be returned, can be controlled by the bot */
offset: string;
/** Type of the chat from which the inline query was sent. Can be either “sender” for a private chat with the inline query sender, “private”, “group”, “supergroup”, or “channel”. The chat type should be always known for requests sent from official clients and most third-party clients, unless the request was sent from a secret chat */
chat_type?: "sender" | Chat["type"];
/** Sender location, only for bots that request user location */
location?: Location;
}
/** This object represents one result of an inline query. Telegram clients currently support results of the following 20 types:
- InlineQueryResultCachedAudio
- InlineQueryResultCachedDocument
- InlineQueryResultCachedGif
- InlineQueryResultCachedMpeg4Gif
- InlineQueryResultCachedPhoto
- InlineQueryResultCachedSticker
- InlineQueryResultCachedVideo
- InlineQueryResultCachedVoice
- InlineQueryResultArticle
- InlineQueryResultAudio
- InlineQueryResultContact
- InlineQueryResultGame
- InlineQueryResultDocument
- InlineQueryResultGif
- InlineQueryResultLocation
- InlineQueryResultMpeg4Gif
- InlineQueryResultPhoto
- InlineQueryResultVenue
- InlineQueryResultVideo
- InlineQueryResultVoice
Note: All URLs passed in inline query results will be available to end users and therefore must be assumed to be public. */
export type InlineQueryResult = InlineQueryResultCachedAudio | InlineQueryResultCachedDocument | InlineQueryResultCachedGif | InlineQueryResultCachedMpeg4Gif | InlineQueryResultCachedPhoto | InlineQueryResultCachedSticker | InlineQueryResultCachedVideo | InlineQueryResultCachedVoice | InlineQueryResultArticle | InlineQueryResultAudio | InlineQueryResultContact | InlineQueryResultGame | InlineQueryResultDocument | InlineQueryResultGif | InlineQueryResultLocation | InlineQueryResultMpeg4Gif | InlineQueryResultPhoto | InlineQueryResultVenue | InlineQueryResultVideo | InlineQueryResultVoice;
/** Represents a link to an article or web page. */
export interface InlineQueryResultArticle {
/** Type of the result, must be article */
type: "article";
/** Unique identifier for this result, 1-64 Bytes */
id: string;
/** Title of the result */
title: string;
/** Content of the message to be sent */
input_message_content: InputMessageContent;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** URL of the result */
url?: string;
/** Pass True if you don't want the URL to be shown in the message */
hide_url?: boolean;
/** Short description of the result */
description?: string;
/** Url of the thumbnail for the result */
thumbnail_url?: string;
/** Thumbnail width */
thumbnail_width?: number;
/** Thumbnail height */
thumbnail_height?: number;
}
/** Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo. */
export interface InlineQueryResultPhoto {
/** Type of the result, must be photo */
type: "photo";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid URL of the photo. Photo must be in JPEG format. Photo size must not exceed 5MB */
photo_url: string;
/** URL of the thumbnail for the photo */
thumbnail_url: string;
/** Width of the photo */
photo_width?: number;
/** Height of the photo */
photo_height?: number;
/** Title for the result */
title?: string;
/** Short description of the result */
description?: string;
/** Caption of the photo to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the photo caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the photo */
input_message_content?: InputMessageContent;
}
/** Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. */
export interface InlineQueryResultGif {
/** Type of the result, must be gif */
type: "gif";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid URL for the GIF file. File size must not exceed 1MB */
gif_url: string;
/** Width of the GIF */
gif_width?: number;
/** Height of the GIF */
gif_height?: number;
/** Duration of the GIF in seconds */
gif_duration?: number;
/** URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result */
thumbnail_url: string;
/** MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg” */
thumbnail_mime_type?: "image/jpeg" | "image/gif" | "video/mp4";
/** Title for the result */
title?: string;
/** Caption of the GIF file to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the GIF animation */
input_message_content?: InputMessageContent;
}
/** Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. */
export interface InlineQueryResultMpeg4Gif {
/** Type of the result, must be mpeg4_gif */
type: "mpeg4_gif";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid URL for the MPEG4 file. File size must not exceed 1MB */
mpeg4_url: string;
/** Video width */
mpeg4_width?: number;
/** Video height */
mpeg4_height?: number;
/** Video duration in seconds */
mpeg4_duration?: number;
/** URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result */
thumbnail_url: string;
/** MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg” */
thumbnail_mime_type?: "image/jpeg" | "image/gif" | "video/mp4";
/** Title for the result */
title?: string;
/** Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the video animation */
input_message_content?: InputMessageContent;
}
/** Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.
> If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must replace its content using input_message_content. */
export interface InlineQueryResultVideo {
/** Type of the result, must be video */
type: "video";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid URL for the embedded video player or video file */
video_url: string;
/** MIME type of the content of the video URL, “text/html” or “video/mp4” */
mime_type: "text/html" | "video/mp4";
/** URL of the thumbnail (JPEG only) for the video */
thumbnail_url: string;
/** Title for the result */
title: string;
/** Caption of the video to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the video caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Video width */
video_width?: number;
/** Video height */
video_height?: number;
/** Video duration in seconds */
video_duration?: number;
/** Short description of the result */
description?: string;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the video. This field is required if InlineQueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video). */
input_message_content?: InputMessageContent;
}
/** Represents a link to an MP3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultAudio {
/** Type of the result, must be audio */
type: "audio";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid URL for the audio file */
audio_url: string;
/** Title */
title: string;
/** Caption, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the audio caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Performer */
performer?: string;
/** Audio duration in seconds */
audio_duration?: number;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the audio */
input_message_content?: InputMessageContent;
}
/** Represents a link to a voice recording in an .OGG container encoded with OPUS. By default, this voice recording will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the the voice message.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultVoice {
/** Type of the result, must be voice */
type: "voice";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid URL for the voice recording */
voice_url: string;
/** Recording title */
title: string;
/** Caption, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the voice message caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Recording duration in seconds */
voice_duration?: number;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the voice recording */
input_message_content?: InputMessageContent;
}
/** Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. Currently, only .PDF and .ZIP files can be sent using this method.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultDocument {
/** Type of the result, must be document */
type: "document";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** Title for the result */
title: string;
/** Caption of the document to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the document caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** A valid URL for the file */
document_url: string;
/** MIME type of the content of the file, either “application/pdf” or “application/zip” */
mime_type: "application/pdf" | "application/zip";
/** Short description of the result */
description?: string;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the file */
input_message_content?: InputMessageContent;
/** URL of the thumbnail (JPEG only) for the file */
thumbnail_url?: string;
/** Thumbnail width */
thumbnail_width?: number;
/** Thumbnail height */
thumbnail_height?: number;
}
/** Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the location.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultLocation {
/** Type of the result, must be location */
type: "location";
/** Unique identifier for this result, 1-64 Bytes */
id: string;
/** Location latitude in degrees */
latitude: number;
/** Location longitude in degrees */
longitude: number;
/** Location title */
title: string;
/** The radius of uncertainty for the location, measured in meters; 0-1500 */
horizontal_accuracy?: number;
/** Period in seconds for which the location can be updated, should be between 60 and 86400. */
live_period?: number;
/** For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. */
heading?: number;
/** For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. */
proximity_alert_radius?: number;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the location */
input_message_content?: InputMessageContent;
/** Url of the thumbnail for the result */
thumbnail_url?: string;
/** Thumbnail width */
thumbnail_width?: number;
/** Thumbnail height */
thumbnail_height?: number;
}
/** Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the venue.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultVenue {
/** Type of the result, must be venue */
type: "venue";
/** Unique identifier for this result, 1-64 Bytes */
id: string;
/** Latitude of the venue location in degrees */
latitude: number;
/** Longitude of the venue location in degrees */
longitude: number;
/** Title of the venue */
title: string;
/** Address of the venue */
address: string;
/** Foursquare identifier of the venue if known */
foursquare_id?: string;
/** Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) */
foursquare_type?: string;
/** Google Places identifier of the venue */
google_place_id?: string;
/** Google Places type of the venue. (See supported types.) */
google_place_type?: string;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the venue */
input_message_content?: InputMessageContent;
/** Url of the thumbnail for the result */
thumbnail_url?: string;
/** Thumbnail width */
thumbnail_width?: number;
/** Thumbnail height */
thumbnail_height?: number;
}
/** Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the contact.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultContact {
/** Type of the result, must be contact */
type: "contact";
/** Unique identifier for this result, 1-64 Bytes */
id: string;
/** Contact's phone number */
phone_number: string;
/** Contact's first name */
first_name: string;
/** Contact's last name */
last_name?: string;
/** Additional data about the contact in the form of a vCard, 0-2048 bytes */
vcard?: string;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the contact */
input_message_content?: InputMessageContent;
/** Url of the thumbnail for the result */
thumbnail_url?: string;
/** Thumbnail width */
thumbnail_width?: number;
/** Thumbnail height */
thumbnail_height?: number;
}
/** Represents a Game.
Note: This will only work in Telegram versions released after October 1, 2016. Older clients will not display any inline results if a game result is among them. */
export interface InlineQueryResultGame {
/** Type of the result, must be game */
type: "game";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** Short name of the game */
game_short_name: string;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
}
/** Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo. */
export interface InlineQueryResultCachedPhoto {
/** Type of the result, must be photo */
type: "photo";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier of the photo */
photo_file_id: string;
/** Title for the result */
title?: string;
/** Short description of the result */
description?: string;
/** Caption of the photo to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the photo caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the photo */
input_message_content?: InputMessageContent;
}
/** Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with specified content instead of the animation. */
export interface InlineQueryResultCachedGif {
/** Type of the result, must be gif */
type: "gif";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier for the GIF file */
gif_file_id: string;
/** Title for the result */
title?: string;
/** Caption of the GIF file to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the GIF animation */
input_message_content?: InputMessageContent;
}
/** Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. */
export interface InlineQueryResultCachedMpeg4Gif {
/** Type of the result, must be mpeg4_gif */
type: "mpeg4_gif";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier for the MPEG4 file */
mpeg4_file_id: string;
/** Title for the result */
title?: string;
/** Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the video animation */
input_message_content?: InputMessageContent;
}
/** Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the sticker.
Note: This will only work in Telegram versions released after 9 April, 2016 for static stickers and after 06 July, 2019 for animated stickers. Older clients will ignore them. */
export interface InlineQueryResultCachedSticker {
/** Type of the result, must be sticker */
type: "sticker";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier of the sticker */
sticker_file_id: string;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the sticker */
input_message_content?: InputMessageContent;
}
/** Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultCachedDocument {
/** Type of the result, must be document */
type: "document";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** Title for the result */
title: string;
/** A valid file identifier for the file */
document_file_id: string;
/** Short description of the result */
description?: string;
/** Caption of the document to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the document caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the file */
input_message_content?: InputMessageContent;
}
/** Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video. */
export interface InlineQueryResultCachedVideo {
/** Type of the result, must be video */
type: "video";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier for the video file */
video_file_id: string;
/** Title for the result */
title: string;
/** Short description of the result */
description?: string;
/** Caption of the video to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the video caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the video */
input_message_content?: InputMessageContent;
}
/** Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the voice message.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultCachedVoice {
/** Type of the result, must be voice */
type: "voice";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier for the voice message */
voice_file_id: string;
/** Voice message title */
title: string;
/** Caption, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the voice message caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the voice message */
input_message_content?: InputMessageContent;
}
/** Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultCachedAudio {
/** Type of the result, must be audio */
type: "audio";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier for the audio file */
audio_file_id: string;
/** Caption, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the audio caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the audio */
input_message_content?: InputMessageContent;
}
/** This object represents the content of a message to be sent as a result of an inline query. Telegram clients currently support the following 5 types:
- InputTextMessageContent
- InputLocationMessageContent
- InputVenueMessageContent
- InputContactMessageContent
- InputInvoiceMessageContent */
export type InputMessageContent = InputTextMessageContent | InputLocationMessageContent | InputVenueMessageContent | InputContactMessageContent | InputInvoiceMessageContent;
/** Represents the content of a text message to be sent as the result of an inline query. */
export interface InputTextMessageContent {
/** Text of the message to be sent, 1-4096 characters */
message_text: string;
/** Mode for parsing entities in the message text. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in message text, which can be specified instead of parse_mode */
entities?: MessageEntity[];
/** Options used for link preview generation for the original message, if it is a text message */
link_preview_options?: LinkPreviewOptions;
}
/** Represents the content of a location message to be sent as the result of an inline query. */
export interface InputLocationMessageContent {
/** Latitude of the location in degrees */
latitude: number;
/** Longitude of the location in degrees */
longitude: number;
/** The radius of uncertainty for the location, measured in meters; 0-1500 */
horizontal_accuracy?: number;
/** Period in seconds for which the location can be updated, should be between 60 and 86400. */
live_period?: number;
/** For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. */
heading?: number;
/** For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. */
proximity_alert_radius?: number;
}
/** Represents the content of a venue message to be sent as the result of an inline query. */
export interface InputVenueMessageContent {
/** Latitude of the venue in degrees */
latitude: number;
/** Longitude of the venue in degrees */
longitude: number;
/** Name of the venue */
title: string;
/** Address of the venue */
address: string;
/** Foursquare identifier of the venue, if known */
foursquare_id?: string;
/** Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) */
foursquare_type?: string;
/** Google Places identifier of the venue */
google_place_id?: string;
/** Google Places type of the venue. (See supported types.) */
google_place_type?: string;
}
/** Represents the content of a contact message to be sent as the result of an inline query. */
export interface InputContactMessageContent {
/** Contact's phone number */
phone_number: string;
/** Contact's first name */
first_name: string;
/** Contact's last name */
last_name?: string;
/** Additional data about the contact in the form of a vCard, 0-2048 bytes */
vcard?: string;
}
/** Represents the content of an invoice message to be sent as the result of an inline query. */
export interface InputInvoiceMessageContent {
/** Product name, 1-32 characters */
title: string;
/** Product description, 1-255 characters */
description: string;
/** Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. */
payload: string;
/** Payment provider token, obtained via BotFather */
provider_token: string;
/** Three-letter ISO 4217 currency code, see more on currencies */
currency: string;
/** Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) */
prices: LabeledPrice[];
/** The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0 */
max_tip_amount?: number;
/** An array of suggested amounts of tip in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. */
suggested_tip_amounts?: number[];
/** Data about the invoice, which will be shared with the payment provider. A detailed description of the required fields should be provided by the payment provider. */
provider_data?: string;
/** URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. */
photo_url?: string;
/** Photo size in bytes */
photo_size?: number;
/** Photo width */
photo_width?: number;
/** Photo height */
photo_height?: number;
/** Pass True if you require the user's full name to complete the order */
need_name?: boolean;
/** Pass True if you require the user's phone number to complete the order */
need_phone_number?: boolean;
/** Pass True if you require the user's email address to complete the order */
need_email?: boolean;
/** Pass True if you require the user's shipping address to complete the order */
need_shipping_address?: boolean;
/** Pass True if the user's phone number should be sent to provider */
send_phone_number_to_provider?: boolean;
/** Pass True if the user's email address should be sent to provider */
send_email_to_provider?: boolean;
/** Pass True if the final price depends on the shipping method */
is_flexible?: boolean;
}
/** Represents a result of an inline query that was chosen by the user and sent to their chat partner.
Note: It is necessary to enable inline feedback via @BotFather in order to receive these objects in updates. */
export interface ChosenInlineResult {
/** The unique identifier for the result that was chosen */
result_id: string;
/** The user that chose the result */
from: User;
/** Sender location, only for bots that require user location */
location?: Location;
/** Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. Will be also received in callback queries and can be used to edit the message. */
inline_message_id?: string;
/** The query that was used to obtain the result */
query: string;
}
export interface AbstractInlineQueryResultsButton {
/** Label text on the button */
text: string;
}
export interface InlineQueryResultsWebAppButton extends AbstractInlineQueryResultsButton {
/** Description of the Web App that will be launched when the user presses the button. The Web App will be able to switch back to the inline mode using the method web_app_switch_inline_query inside the Web App. */
web_app: WebAppInfo;
}
export interface InlineQueryResultsStartButton extends AbstractInlineQueryResultsButton {
/** Deep-linking parameter for the /start message sent to the bot when a user presses the button. 1-64 characters, only `A-Z`, `a-z`, `0-9`, `_` and `-` are allowed. */
start_parameter: string;
}
/** This object represents a button to be shown above inline query results.
Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. */
export type InlineQueryResultsButton = InlineQueryResultsWebAppButton | InlineQueryResultsStartButton;

594
node_modules/@telegraf/types/manage.d.ts generated vendored Normal file
View File

@@ -0,0 +1,594 @@
import type { Location, Message, PhotoSize } from "./message.js";
/** Describes the current status of a webhook. */
export interface WebhookInfo {
/** Webhook URL, may be empty if webhook is not set up */
url?: string;
/** True, if a custom certificate was provided for webhook certificate checks */
has_custom_certificate: boolean;
/** Number of updates awaiting delivery */
pending_update_count: number;
/** Currently used webhook IP address */
ip_address?: string;
/** Unix time for the most recent error that happened when trying to deliver an update via webhook */
last_error_date?: number;
/** Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook */
last_error_message?: string;
/** Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters */
last_synchronization_error_date?: number;
/** The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery */
max_connections?: number;
/** A list of update types the bot is subscribed to. Defaults to all update types except chat_member */
allowed_updates?: string[];
}
/** This object represents a Telegram user or bot. */
export interface User {
/** Unique identifier for this user or bot. */
id: number;
/** True, if this user is a bot */
is_bot: boolean;
/** User's or bot's first name */
first_name: string;
/** User's or bot's last name */
last_name?: string;
/** User's or bot's username */
username?: string;
/** IETF language tag of the user's language */
language_code?: string;
/** True, if this user is a Telegram Premium user */
is_premium?: true;
/** True, if this user added the bot to the attachment menu */
added_to_attachment_menu?: true;
}
/** This object represents a Telegram user or bot that was returned by `getMe`. */
export interface UserFromGetMe extends User {
is_bot: true;
username: string;
/** True, if the bot can be invited to groups. Returned only in getMe. */
can_join_groups: boolean;
/** True, if privacy mode is disabled for the bot. Returned only in getMe. */
can_read_all_group_messages: boolean;
/** True, if the bot supports inline queries. Returned only in getMe. */
supports_inline_queries: boolean;
}
export declare namespace Chat {
/** Internal type holding properties that all kinds of chats share. */
interface AbstractChat {
/** Unique identifier for this chat. */
id: number;
/** Type of chat, can be either “private”, “group”, “supergroup” or “channel” */
type: string;
}
/** Internal type holding properties that those chats with user names share. */
interface UserNameChat {
/** Username, for private chats, supergroups and channels if available */
username?: string;
}
/** Internal type holding properties that those chats with titles share. */
interface TitleChat {
/** Title, for supergroups, channels and group chats */
title: string;
}
/** Internal type representing private chats. */
interface PrivateChat extends AbstractChat, UserNameChat {
type: "private";
/** First name of the other party in a private chat */
first_name: string;
/** Last name of the other party in a private chat */
last_name?: string;
}
/** Internal type representing group chats. */
interface GroupChat extends AbstractChat, TitleChat {
type: "group";
}
/** Internal type representing super group chats. */
interface SupergroupChat extends AbstractChat, UserNameChat, TitleChat {
type: "supergroup";
/** True, if the supergroup chat is a forum (has topics enabled) */
is_forum?: true;
}
/** Internal type representing channel chats. */
interface ChannelChat extends AbstractChat, UserNameChat, TitleChat {
type: "channel";
}
/** Internal type holding properties that those chats returned from `getChat` share. */
interface GetChat {
/** Chat photo. Returned only in getChat. */
photo?: ChatPhoto;
/** The most recent pinned message (by sending date). Returned only in getChat. */
pinned_message?: Message;
/** The time after which all messages sent to the chat will be automatically deleted; in seconds. Returned only in getChat. */
message_auto_delete_time?: number;
/** True, if messages from the chat can't be forwarded to other chats. Returned only in getChat. */
has_protected_content?: true;
}
/** Internal type holding properties that private, supergroup, and channel chats returned from `getChat` share. */
interface NonGroupGetChat extends GetChat {
/** If non-empty, the list of all active chat usernames; for private chats, supergroups and channels. Returned only in getChat. */
active_usernames?: string[];
}
/** Internal type holding properties that group, supergroup, and channel chats returned from `getChat` share. */
interface NonPrivateGetChat extends GetChat {
/** List of available reactions allowed in the chat. If omitted, then all emoji reactions are allowed. Returned only in getChat. */
available_reactions?: ReactionType[];
/** Description, for groups, supergroups and channel chats. Returned only in getChat. */
description?: string;
/** Primary invite link, for groups, supergroups and channel chats. Returned only in getChat. */
invite_link?: string;
}
/** Internal type holding properties that group and supergroup chats returned from `getChat` share. */
interface AnyGroupGetChat extends NonPrivateGetChat {
/** Default chat member permissions, for groups and supergroups. Returned only in getChat. */
permissions?: ChatPermissions;
/** True, if the bot can change the group sticker set. Returned only in getChat. */
can_set_sticker_set?: true;
}
/** Internal type holding properties that private and channel chats returned from `getChat` share. */
interface PrivateAndChannelGetChat {
/** Identifier of the accent color for the chat name and backgrounds of the chat photo, reply header, and link preview. See accent colors for more details. Returned only in getChat. */
accent_color_id: number;
/** Custom emoji identifier of emoji chosen by the chat for the reply header and link preview background. Returned only in getChat. */
background_custom_emoji_id?: string;
/** Custom emoji identifier of emoji status of the other party in a private chat. Returned only in getChat. */
emoji_status_custom_emoji_id?: string;
/** Expiration date of the emoji status of the other party in a private chat in Unix time, if any. Returned only in getChat. */
emoji_status_expiration_date?: number;
}
/** Internal type holding properties that supergroup and channel chats returned from `getChat` share. */
interface LargeGetChat extends NonPrivateGetChat {
/** Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. Returned only in getChat. */
linked_chat_id?: number;
}
/** Internal type representing private chats returned from `getChat`. */
interface PrivateGetChat extends PrivateChat, NonGroupGetChat, PrivateAndChannelGetChat {
/** Bio of the other party in a private chat. Returned only in getChat. */
bio?: string;
/** True, if privacy settings of the other party in the private chat allows to use tg://user?id=<user_id> links only in chats with the user. Returned only in getChat. */
has_private_forwards?: true;
/** True, if the privacy settings of the other party restrict sending voice and video note messages in the private chat. Returned only in getChat. */
has_restricted_voice_and_video_messages?: true;
}
/** Internal type representing group chats returned from `getChat`. */
interface GroupGetChat extends GroupChat, AnyGroupGetChat {
}
/** Internal type representing supergroup chats returned from `getChat`. */
interface SupergroupGetChat extends SupergroupChat, NonGroupGetChat, AnyGroupGetChat, LargeGetChat {
/** True, if users need to join the supergroup before they can send messages. Returned only in getChat. */
join_to_send_messages?: true;
/** True, if all users directly joining the supergroup need to be approved by supergroup administrators. Returned only in getChat. */
join_by_request?: true;
/** For supergroups, the minimum allowed delay between consecutive messages sent by each unpriviledged user; in seconds. Returned only in getChat. */
slow_mode_delay?: number;
/** For supergroups, the minimum number of boosts that a non-administrator user needs to add in order to ignore slow mode and chat permissions. Returned only in getChat. */
unrestrict_boost_count?: number;
/** True, if aggressive anti-spam checks are enabled in the supergroup. The field is only available to chat administrators. Returned only in getChat. */
has_aggressive_anti_spam_enabled?: true;
/** True, if new chat members will have access to old messages; available only to chat administrators. Returned only in getChat. */
has_visible_history?: boolean;
/** For supergroups, name of group sticker set. Returned only in getChat. */
sticker_set_name?: string;
/** For supergroups, the name of the group's custom emoji sticker set. Custom emoji from this set can be used by all users and bots in the group. Returned only in getChat. */
custom_emoji_sticker_set_name?: string;
/** For supergroups, the location to which the supergroup is connected. Returned only in getChat. */
location?: ChatLocation;
}
/** Internal type representing channel chats returned from `getChat`. */
interface ChannelGetChat extends ChannelChat, NonGroupGetChat, LargeGetChat, PrivateAndChannelGetChat {
/** Identifier of the accent color for the chat's profile background. See profile accent colors for more details. Returned only in getChat. */
profile_accent_color_id?: number;
/** Custom emoji identifier of the emoji chosen by the chat for its profile background. Returned only in getChat. */
profile_background_custom_emoji_id?: string;
}
}
/** This object represents a chat. */
export type Chat = Chat.PrivateChat | Chat.GroupChat | Chat.SupergroupChat | Chat.ChannelChat;
/** This object represents a Telegram user or bot that was returned by `getChat`. */
export type ChatFromGetChat = Chat.PrivateGetChat | Chat.GroupGetChat | Chat.SupergroupGetChat | Chat.ChannelGetChat;
/** This object represent a user's profile pictures. */
export interface UserProfilePhotos {
/** Total number of profile pictures the target user has */
total_count: number;
/** Requested profile pictures (in up to 4 sizes each) */
photos: PhotoSize[][];
}
/** This object represents a chat photo. */
export interface ChatPhoto {
/** File identifier of small (160x160) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed. */
small_file_id: string;
/** Unique file identifier of small (160x160) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
small_file_unique_id: string;
/** File identifier of big (640x640) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed. */
big_file_id: string;
/** Unique file identifier of big (640x640) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
big_file_unique_id: string;
}
/** Represents an invite link for a chat. */
export interface ChatInviteLink {
/** The invite link. If the link was created by another chat administrator, then the second part of the link will be replaced with “…”. */
invite_link: string;
/** Creator of the link */
creator: User;
/** True, if users joining the chat via the link need to be approved by chat administrators */
creates_join_request: boolean;
/** True, if the link is primary */
is_primary: boolean;
/** True, if the link is revoked */
is_revoked: boolean;
/** Invite link name */
name?: string;
/** Point in time (Unix timestamp) when the link will expire or has been expired */
expire_date?: number;
/** The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 */
member_limit?: number;
/** Number of pending join requests created using this link */
pending_join_request_count?: number;
}
/** Represents the rights of an administrator in a chat. */
export interface ChatAdministratorRights {
/** True, if the user's presence in the chat is hidden */
is_anonymous: boolean;
/** True, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages and ignore slow mode. Implied by any other administrator privilege */
can_manage_chat: boolean;
/** True, if the administrator can delete messages of other users */
can_delete_messages: boolean;
/** True, if the administrator can manage video chats */
can_manage_video_chats: boolean;
/** True, if the administrator can restrict, ban or unban chat members */
can_restrict_members: boolean;
/** True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user) */
can_promote_members: boolean;
/** True, if the user is allowed to change the chat title, photo and other settings */
can_change_info: boolean;
/** True, if the user is allowed to invite new users to the chat */
can_invite_users: boolean;
/** True, if the administrator can post in the channel; channels only */
can_post_messages?: boolean;
/** True, if the administrator can edit messages of other users and can pin messages; channels only */
can_edit_messages?: boolean;
/** True, if the user is allowed to pin messages; groups and supergroups only */
can_pin_messages?: boolean;
/** True, if the administrator can post stories to the chat */
can_post_stories?: boolean;
/** True, if the administrator can edit stories posted by other users */
can_edit_stories?: boolean;
/** True, if the administrator can delete stories posted by other users */
can_delete_stories?: boolean;
/** True, if the user is allowed to create, rename, close, and reopen forum topics; supergroups only */
can_manage_topics?: boolean;
}
/** This object contains information about one member of a chat. Currently, the following 6 types of chat members are supported:
- ChatMemberOwner
- ChatMemberAdministrator
- ChatMemberMember
- ChatMemberRestricted
- ChatMemberLeft
- ChatMemberBanned */
export type ChatMember = ChatMemberOwner | ChatMemberAdministrator | ChatMemberMember | ChatMemberRestricted | ChatMemberLeft | ChatMemberBanned;
export interface AbstractChatMember {
/** The member's status in the chat */
status: string;
/** Information about the user */
user: User;
}
/** Represents a chat member that owns the chat and has all administrator privileges. */
export interface ChatMemberOwner extends AbstractChatMember {
status: "creator";
/** True, if the user's presence in the chat is hidden */
is_anonymous: boolean;
/** Custom title for this user */
custom_title?: string;
}
/** Represents a chat member that has some additional privileges. */
export interface ChatMemberAdministrator extends AbstractChatMember {
status: "administrator";
/** True, if the bot is allowed to edit administrator privileges of that user */
can_be_edited: boolean;
/** True, if the user's presence in the chat is hidden */
is_anonymous: boolean;
/** True, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages and ignore slow mode. Implied by any other administrator privilege */
can_manage_chat: boolean;
/** True, if the administrator can delete messages of other users */
can_delete_messages: boolean;
/** True, if the administrator can manage video chats */
can_manage_video_chats: boolean;
/** True, if the administrator can restrict, ban or unban chat members */
can_restrict_members: boolean;
/** True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user) */
can_promote_members: boolean;
/** True, if the user is allowed to change the chat title, photo and other settings */
can_change_info: boolean;
/** True, if the user is allowed to invite new users to the chat */
can_invite_users: boolean;
/** True, if the administrator can post in the channel; channels only */
can_post_messages?: boolean;
/** True, if the administrator can edit messages of other users and can pin messages; channels only */
can_edit_messages?: boolean;
/** True, if the user is allowed to pin messages; groups and supergroups only */
can_pin_messages?: boolean;
/** True, if the administrator can post stories to the chat */
can_post_stories?: boolean;
/** True, if the administrator can edit stories posted by other users */
can_edit_stories?: boolean;
/** True, if the administrator can delete stories posted by other users */
can_delete_stories?: boolean;
/** True, if the user is allowed to create, rename, close, and reopen forum topics; supergroups only */
can_manage_topics?: boolean;
/** Custom title for this user */
custom_title?: string;
}
/** Represents a chat member that has no additional privileges or restrictions. */
export interface ChatMemberMember extends AbstractChatMember {
status: "member";
}
/** Represents a chat member that is under certain restrictions in the chat. Supergroups only. */
export interface ChatMemberRestricted extends AbstractChatMember {
status: "restricted";
/** True, if the user is a member of the chat at the moment of the request */
is_member: boolean;
/** True, if the user is allowed to send text messages, contacts, giveaways, giveaway winners, invoices, locations and venues */
can_send_messages: boolean;
/** True, if the user is allowed to send audios */
can_send_audios: boolean;
/** True, if the user is allowed to send documents */
can_send_documents: boolean;
/** True, if the user is allowed to send photos */
can_send_photos: boolean;
/** True, if the user is allowed to send videos */
can_send_videos: boolean;
/** True, if the user is allowed to send video notes */
can_send_video_notes: boolean;
/** True, if the user is allowed to send voice notes */
can_send_voice_notes: boolean;
/** True, if the user is allowed to send polls */
can_send_polls: boolean;
/** True, if the user is allowed to send animations, games, stickers and use inline bots */
can_send_other_messages: boolean;
/** True, if the user is allowed to add web page previews to their messages */
can_add_web_page_previews: boolean;
/** True, if the user is allowed to change the chat title, photo and other settings */
can_change_info: boolean;
/** True, if the user is allowed to invite new users to the chat */
can_invite_users: boolean;
/** True, if the user is allowed to pin messages */
can_pin_messages: boolean;
/** True, if the user is allowed to create forum topics */
can_manage_topics: boolean;
/** Date when restrictions will be lifted for this user; Unix time. If 0, then the user is restricted forever */
until_date: number;
}
/** Represents a chat member that isn't currently a member of the chat, but may join it themselves. */
export interface ChatMemberLeft extends AbstractChatMember {
status: "left";
}
/** Represents a chat member that was banned in the chat and can't return to the chat or view chat messages. */
export interface ChatMemberBanned extends AbstractChatMember {
status: "kicked";
/** Date when restrictions will be lifted for this user; Unix time. If 0, then the user is banned forever */
until_date: number;
}
/** This object represents changes in the status of a chat member. */
export interface ChatMemberUpdated {
/** Chat the user belongs to */
chat: Chat;
/** Performer of the action, which resulted in the change */
from: User;
/** Date the change was done in Unix time */
date: number;
/** Previous information about the chat member */
old_chat_member: ChatMember;
/** New information about the chat member */
new_chat_member: ChatMember;
/** Chat invite link, which was used by the user to join the chat; for joining by invite link events only. */
invite_link?: ChatInviteLink;
/** True, if the user joined the chat via a chat folder invite link */
via_chat_folder_invite_link?: boolean;
}
/** Represents a join request sent to a chat. */
export interface ChatJoinRequest {
/** Chat to which the request was sent */
chat: Chat.SupergroupChat | Chat.ChannelChat;
/** User that sent the join request */
from: User;
/** Identifier of a private chat with the user who sent the join request. The bot can use this identifier for 24 hours to send messages until the join request is processed, assuming no other administrator contacted the user. */
user_chat_id: number;
/** Date the request was sent in Unix time */
date: number;
/** Bio of the user. */
bio?: string;
/** Chat invite link that was used by the user to send the join request */
invite_link?: ChatInviteLink;
}
/** Describes actions that a non-administrator user is allowed to take in a chat. */
export interface ChatPermissions {
/** True, if the user is allowed to send text messages, contacts, giveaways, giveaway winners, invoices, locations and venues */
can_send_messages?: boolean;
/** True, if the user is allowed to send audios */
can_send_audios?: boolean;
/** True, if the user is allowed to send documents */
can_send_documents?: boolean;
/** True, if the user is allowed to send photos */
can_send_photos?: boolean;
/** True, if the user is allowed to send videos */
can_send_videos?: boolean;
/** True, if the user is allowed to send video notes */
can_send_video_notes?: boolean;
/** True, if the user is allowed to send voice notes */
can_send_voice_notes?: boolean;
/** True, if the user is allowed to send polls */
can_send_polls?: boolean;
/** True, if the user is allowed to send animations, games, stickers and use inline bots */
can_send_other_messages?: boolean;
/** True, if the user is allowed to add web page previews to their messages */
can_add_web_page_previews?: boolean;
/** True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups */
can_change_info?: boolean;
/** True, if the user is allowed to invite new users to the chat */
can_invite_users?: boolean;
/** True, if the user is allowed to pin messages. Ignored in public supergroups */
can_pin_messages?: boolean;
/** True, if the user is allowed to create forum topics. If omitted defaults to the value of can_pin_messages */
can_manage_topics?: boolean;
}
/** Represents a location to which a chat is connected. */
export interface ChatLocation {
/** The location to which the supergroup is connected. Can't be a live location. */
location: Location;
/** Location address; 1-64 characters, as defined by the chat owner */
address: string;
}
/** This object describes the type of a reaction. Currently, it can be one of
* - ReactionTypeEmoji
* - ReactionTypeCustomEmoji
*/
export type ReactionType = ReactionTypeEmoji | ReactionTypeCustomEmoji;
export interface AbstractReactionType {
/** Type of the reaction */
type: string;
}
export type TelegramEmoji = "👍" | "👎" | "❤" | "🔥" | "🥰" | "👏" | "😁" | "🤔" | "🤯" | "😱" | "🤬" | "😢" | "🎉" | "🤩" | "🤮" | "💩" | "🙏" | "👌" | "🕊" | "🤡" | "🥱" | "🥴" | "😍" | "🐳" | "❤‍🔥" | "🌚" | "🌭" | "💯" | "🤣" | "⚡" | "🍌" | "🏆" | "💔" | "🤨" | "😐" | "🍓" | "🍾" | "💋" | "🖕" | "😈" | "😴" | "😭" | "🤓" | "👻" | "👨‍💻" | "👀" | "🎃" | "🙈" | "😇" | "😨" | "🤝" | "✍" | "🤗" | "🫡" | "🎅" | "🎄" | "☃" | "💅" | "🤪" | "🗿" | "🆒" | "💘" | "🙉" | "🦄" | "😘" | "💊" | "🙊" | "😎" | "👾" | "🤷‍♂" | "🤷" | "🤷‍♀" | "😡";
/** The reaction is based on an emoji. */
export interface ReactionTypeEmoji extends AbstractReactionType {
type: "emoji";
/** Reaction emoji. */
emoji: TelegramEmoji;
}
/** The reaction is based on a custom emoji. */
export interface ReactionTypeCustomEmoji extends AbstractReactionType {
type: "custom_emoji";
/** Custom emoji identifier */
custom_emoji_id: string;
}
/** Represents a reaction added to a message along with the number of times it was added. */
export interface ReactionCount {
/** Type of the reaction */
type: ReactionType;
/** Number of times the reaction was added */
total_count: number;
}
/** This object represents a change of a reaction on a message performed by a user. */
export interface MessageReactionUpdated {
/** The chat containing the message the user reacted to */
chat: Chat;
/** Unique identifier of the message inside the chat */
message_id: number;
/** The user that changed the reaction, if the user isn't anonymous */
user?: User;
/** The chat on behalf of which the reaction was changed, if the user is anonymous */
actor_chat?: Chat;
/** Date of the change in Unix time */
date: number;
/** Previous list of reaction types that were set by the user */
old_reaction: ReactionType[];
/** New list of reaction types that have been set by the user */
new_reaction: ReactionType[];
}
/** This object represents reaction changes on a message with anonymous reactions. */
export interface MessageReactionCountUpdated {
/** The chat containing the message */
chat: Chat;
/** Unique message identifier inside the chat */
message_id: number;
/** Date of the change in Unix time */
date: number;
/** List of reactions that are present on the message */
reactions: ReactionCount[];
}
/** This object represents a forum topic. */
export interface ForumTopic {
/** Unique identifier of the forum topic */
message_thread_id: number;
/** Name of the topic */
name: string;
/** Color of the topic icon in RGB format */
icon_color: number;
/** Unique identifier of the custom emoji shown as the topic icon */
icon_custom_emoji_id?: string;
}
/** This object represents a bot command. */
export interface BotCommand {
/** Text of the command; 1-32 characters. Can contain only lowercase English letters, digits and underscores. */
command: string;
/** Description of the command; 1-256 characters. */
description: string;
}
/** This object describes the source of a chat boost. It can be one of
- ChatBoostSourcePremium
- ChatBoostSourceGiftCode
- ChatBoostSourceGiveaway
*/
type ChatBoostSource = ChatBoostSourcePremium | ChatBoostSourceGiftCode | ChatBoostSourceGiveaway;
export interface AbstractChatBoostSource {
/** Source of the boost */
source: string;
}
/** The boost was obtained by subscribing to Telegram Premium or by gifting a Telegram Premium subscription to another user. */
export interface ChatBoostSourcePremium extends AbstractChatBoostSource {
source: "premium";
/** User that boosted the chat. */
user: User;
}
/** The boost was obtained by the creation of Telegram Premium gift codes to boost a chat. Each such code boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription. */
export interface ChatBoostSourceGiftCode extends AbstractChatBoostSource {
source: "gift_code";
/** User for which the gift code was created. */
user: User;
}
/** The boost was obtained by the creation of a Telegram Premium giveaway. This boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription. */
export interface ChatBoostSourceGiveaway extends AbstractChatBoostSource {
source: "giveaway";
/** Identifier of a message in the chat with the giveaway; the message could have been deleted already. May be 0 if the message isn't sent yet. */
giveaway_message_id: number;
/** User that won the prize in the giveaway if any. */
user?: User;
/** True, if the giveaway was completed, but there was no user to win the prize */
is_unclaimed?: true;
}
/** This object contains information about a chat boost. */
export interface ChatBoost {
/** Unique identifier of the boost */
boost_id: string;
/** Point in time (Unix timestamp) when the chat was boosted */
add_date: number;
/** Point in time (Unix timestamp) when the boost will automatically expire, unless the booster's Telegram Premium subscription is prolonged */
expiration_date: number;
/** Source of the added boost */
source: ChatBoostSource;
}
/** This object represents a boost added to a chat or changed. */
export interface ChatBoostUpdated {
/** Chat which was boosted */
chat: Chat;
/** Infomation about the chat boost */
boost: ChatBoost;
}
/** This object represents a boost removed from a chat. */
export interface ChatBoostRemoved {
/** Chat which was boosted */
chat: Chat;
/** Unique identifier of the boost */
boost_id: string;
/** Point in time (Unix timestamp) when the boost was removed */
remove_date: number;
/** Source of the removed boost */
source: ChatBoostSource;
}
/** This object represents a list of boosts added to a chat by a user. */
export interface UserChatBoosts {
/** The list of boosts added to the chat by the user */
boosts: ChatBoost[];
}
/** This object represents a file ready to be downloaded. The file can be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile.
> The maximum file size to download is 20 MB
*/
export interface File {
/** Identifier for this file, which can be used to download or reuse the file */
file_id: string;
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id: string;
/** File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. */
file_size?: number;
/** File path. Use `https://api.telegram.org/file/bot<token>/<file_path>` to get the file. */
file_path?: string;
}
export {};

228
node_modules/@telegraf/types/markup.d.ts generated vendored Normal file
View File

@@ -0,0 +1,228 @@
import type { ChatAdministratorRights, User } from "./manage.js";
import type { MaybeInaccessibleMessage } from "./message.js";
/** This object represents an inline keyboard that appears right next to the message it belongs to. */
export interface InlineKeyboardMarkup {
/** Array of button rows, each represented by an Array of InlineKeyboardButton objects */
inline_keyboard: InlineKeyboardButton[][];
}
export declare namespace InlineKeyboardButton {
interface AbstractInlineKeyboardButton {
/** Label text on the button */
text: string;
}
interface UrlButton extends AbstractInlineKeyboardButton {
/** HTTP or tg:// URL to be opened when the button is pressed. Links tg://user?id=<user_id> can be used to mention a user by their ID without using a username, if this is allowed by their privacy settings. */
url: string;
}
interface CallbackButton extends AbstractInlineKeyboardButton {
/** Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes */
callback_data: string;
}
interface WebAppButton extends AbstractInlineKeyboardButton {
/** Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only in private chats between a user and the bot. */
web_app: WebAppInfo;
}
interface LoginButton extends AbstractInlineKeyboardButton {
/** An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget. */
login_url: LoginUrl;
}
interface SwitchInlineButton extends AbstractInlineKeyboardButton {
/** If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. Can be empty, in which case just the bot's username will be inserted. */
switch_inline_query: string;
}
interface SwitchInlineCurrentChatButton extends AbstractInlineKeyboardButton {
/** If set, pressing the button will insert the bot's username and the specified inline query in the current chat's input field. Can be empty, in which case only the bot's username will be inserted.
This offers a quick way for the user to open your bot in inline mode in the same chat good for selecting something from multiple options. */
switch_inline_query_current_chat: string;
}
interface SwitchInlineChosenChatButton extends AbstractInlineKeyboardButton {
/** If set, pressing the button will prompt the user to select one of their chats of the specified type, open that chat and insert the bot's username and the specified inline query in the input field */
switch_inline_query_chosen_chat: SwitchInlineQueryChosenChat;
}
interface GameButton extends AbstractInlineKeyboardButton {
/** Description of the game that will be launched when the user presses the button.
NOTE: This type of button must always be the first button in the first row. */
callback_game: CallbackGame;
}
interface PayButton extends AbstractInlineKeyboardButton {
/** Specify True, to send a Pay button.
NOTE: This type of button must always be the first button in the first row and can only be used in invoice messages. */
pay: boolean;
}
}
/** This object represents one button of an inline keyboard. You must use exactly one of the optional fields. */
export type InlineKeyboardButton = InlineKeyboardButton.CallbackButton | InlineKeyboardButton.GameButton | InlineKeyboardButton.LoginButton | InlineKeyboardButton.PayButton | InlineKeyboardButton.SwitchInlineButton | InlineKeyboardButton.SwitchInlineCurrentChatButton | InlineKeyboardButton.SwitchInlineChosenChatButton | InlineKeyboardButton.UrlButton | InlineKeyboardButton.WebAppButton;
/** This object represents a parameter of the inline keyboard button used to automatically authorize a user. Serves as a great replacement for the Telegram Login Widget when the user is coming from Telegram. All the user needs to do is tap/click a button and confirm that they want to log in.
Telegram apps support these buttons as of version 5.7. */
export interface LoginUrl {
/** An HTTPS URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide authorization data, the original URL without information about the user will be opened. The data added is the same as described in Receiving authorization data.
NOTE: You must always check the hash of the received data to verify the authentication and the integrity of the data as described in Checking authorization. */
url: string;
/** New text of the button in forwarded messages. */
forward_text?: string;
/** Username of a bot, which will be used for user authorization. See Setting up a bot for more details. If not specified, the current bot's username will be assumed. The url's domain must be the same as the domain linked with the bot. See Linking your domain to the bot for more details. */
bot_username?: string;
/** Pass True to request the permission for your bot to send messages to the user. */
request_write_access?: boolean;
}
/** This object represents an inline button that switches the current user to inline mode in a chosen chat, with an optional default inline query. */
export interface SwitchInlineQueryChosenChat {
/** The default inline query to be inserted in the input field. If left empty, only the bot's username will be inserted */
query?: string;
/** True, if private chats with users can be chosen */
allow_user_chats?: boolean;
/** True, if private chats with bots can be chosen */
allow_bot_chats?: boolean;
/** True, if group and supergroup chats can be chosen */
allow_group_chats?: boolean;
/** True, if channel chats can be chosen */
allow_channel_chats?: boolean;
}
/** A placeholder, currently holds no information. Use BotFather to set up your game. */
export interface CallbackGame {
}
export declare namespace CallbackQuery {
interface AbstractQuery {
/** Unique identifier for this query */
id: string;
/** Sender */
from: User;
/** Message sent by the bot with the callback button that originated the query */
message?: MaybeInaccessibleMessage;
/** Identifier of the message sent via the bot in inline mode, that originated the query. */
inline_message_id?: string;
/** Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games. */
chat_instance: string;
}
interface DataQuery extends AbstractQuery {
/** Data associated with the callback button. Be aware that the message originated the query can contain no callback buttons with this data. */
data: string;
}
interface GameQuery extends AbstractQuery {
/** Short name of a Game to be returned, serves as the unique identifier for the game */
game_short_name: string;
}
}
/** This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present.
NOTE: After the user presses a callback button, Telegram clients will display a progress bar until you call answerCallbackQuery. It is, therefore, necessary to react by calling answerCallbackQuery even if no notification to the user is needed (e.g., without specifying any of the optional parameters). */
export type CallbackQuery = CallbackQuery.DataQuery | CallbackQuery.GameQuery;
/** This object represents a custom keyboard with reply options (see Introduction to bots for details and examples). */
export interface ReplyKeyboardMarkup {
/** Array of button rows, each represented by an Array of KeyboardButton objects */
keyboard: KeyboardButton[][];
/** Requests clients to always show the keyboard when the regular keyboard is hidden. Defaults to false, in which case the custom keyboard can be hidden and opened with a keyboard icon. */
is_persistent?: boolean;
/** Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. */
resize_keyboard?: boolean;
/** Requests clients to hide the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat the user can press a special button in the input field to see the custom keyboard again. Defaults to false. */
one_time_keyboard?: boolean;
/** The placeholder to be shown in the input field when the keyboard is active; 1-64 characters */
input_field_placeholder?: string;
/** Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
Example: A user requests to change the bot's language, bot replies to the request with a keyboard to select the new language. Other users in the group don't see the keyboard. */
selective?: boolean;
}
export declare namespace KeyboardButton {
interface CommonButton {
/** Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed */
text: string;
}
interface RequestUsersButton extends CommonButton {
/** If specified, pressing the button will open a list of suitable users. Identifiers of selected users will be sent to the bot in a “users_shared” service message. Available in private chats only. */
request_users: KeyboardButtonRequestUsers;
}
interface RequestChatButton extends CommonButton {
/** If specified, pressing the button will open a list of suitable chats. Tapping on a chat will send its identifier to the bot in a “chat_shared” service message. Available in private chats only. */
request_chat: KeyboardButtonRequestChat;
}
interface RequestContactButton extends CommonButton {
/** If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only. */
request_contact: boolean;
}
interface RequestLocationButton extends CommonButton {
/** If True, the user's current location will be sent when the button is pressed. Available in private chats only. */
request_location: boolean;
}
interface RequestPollButton extends CommonButton {
/** If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only. */
request_poll: KeyboardButtonPollType;
}
interface WebAppButton extends CommonButton {
/** If specified, the described Web App will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only. */
web_app: WebAppInfo;
}
}
/** This object represents one button of the reply keyboard. For simple text buttons, String can be used instead of this object to specify the button text. The optional fields web_app, request_user, request_chat, request_contact, request_location, and request_poll are mutually exclusive. */
export type KeyboardButton = KeyboardButton.CommonButton | KeyboardButton.RequestUsersButton | KeyboardButton.RequestChatButton | KeyboardButton.RequestContactButton | KeyboardButton.RequestLocationButton | KeyboardButton.RequestPollButton | KeyboardButton.WebAppButton | string;
/** This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed. */
export interface KeyboardButtonPollType {
/** If quiz is passed, the user will be allowed to create only polls in the quiz mode. If regular is passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type. */
type?: "quiz" | "regular";
}
/** Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup). */
export interface ReplyKeyboardRemove {
/** Requests clients to remove the custom keyboard (user will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep it accessible, use one_time_keyboard in ReplyKeyboardMarkup) */
remove_keyboard: true;
/** Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
Example: A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for that user, while still showing the keyboard with poll options to users who haven't voted yet. */
selective?: boolean;
}
/** Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply'). This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode.
Example: A poll bot for groups runs in privacy mode (only receives commands, replies to its messages and mentions). There could be two ways to create a new poll:
Explain the user how to send a command with parameters (e.g. /newpoll question answer1 answer2). May be appealing for hardcore users but lacks modern day polish.
Guide the user through a step-by-step process. 'Please send me your question', 'Cool, now let's add the first answer option', 'Great. Keep adding answer options, then send /done when you're ready'.
The last option is definitely more attractive. And if you use ForceReply in your bot's questions, it will receive the user's answers even if it only receives replies, commands and mentions - without any extra work for the user. */
export interface ForceReply {
/** Shows reply interface to the user, as if they manually selected the bot's message and tapped 'Reply' */
force_reply: true;
/** The placeholder to be shown in the input field when the reply is active; 1-64 characters */
input_field_placeholder?: string;
/** Use this parameter if you want to force reply from specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message. */
selective?: boolean;
}
/** Describes a Web App. */
export interface WebAppInfo {
/** An HTTPS URL of a Web App to be opened with additional data as specified in Initializing Web Apps */
url: string;
}
/** This object defines the criteria used to request suitable users. The identifiers of the selected users will be shared with the bot when the corresponding button is pressed. */
export interface KeyboardButtonRequestUsers {
/** Signed 32-bit identifier of the request that will be received back in the UsersShared object. Must be unique within the message. */
request_id: number;
/** Pass True to request bots, pass False to request regular users. If not specified, no additional restrictions are applied. */
user_is_bot?: boolean;
/** Pass True to request premium users, pass False to request non-premium users. If not specified, no additional restrictions are applied. */
user_is_premium?: boolean;
/** The maximum number of users to be selected; 1-10. Defaults to 1. */
max_quantity?: number;
}
/** This object defines the criteria used to request a suitable chat. The identifier of the selected chat will be shared with the bot when the corresponding button is pressed. */
export interface KeyboardButtonRequestChat {
/** Signed 32-bit identifier of the request, which will be received back in the ChatShared object. Must be unique within the message */
request_id: number;
/** Pass True to request a channel chat, pass False to request a group or a supergroup chat. */
chat_is_channel: boolean;
/** Pass True to request a forum supergroup, pass False to request a non-forum chat. If not specified, no additional restrictions are applied. */
chat_is_forum?: boolean;
/** Pass True to request a supergroup or a channel with a username, pass False to request a chat without a username. If not specified, no additional restrictions are applied. */
chat_has_username?: boolean;
/** Pass True to request a chat owned by the user. Otherwise, no additional restrictions are applied. */
chat_is_created?: boolean;
/** An object listing the required administrator rights of the user in the chat. The rights must be a superset of bot_administrator_rights. If not specified, no additional restrictions are applied. */
user_administrator_rights?: ChatAdministratorRights;
/** An object listing the required administrator rights of the bot in the chat. The rights must be a subset of user_administrator_rights. If not specified, no additional restrictions are applied. */
bot_administrator_rights?: ChatAdministratorRights;
/** Pass True to request a chat with the bot as a member. Otherwise, no additional restrictions are applied. */
bot_is_member?: boolean;
}

1087
node_modules/@telegraf/types/message.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

1579
node_modules/@telegraf/types/methods.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

36
node_modules/@telegraf/types/package.json generated vendored Normal file
View File

@@ -0,0 +1,36 @@
{
"name": "@telegraf/types",
"private": false,
"version": "7.1.0",
"description": "Type declarations for the Telegram API",
"main": "index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/telegraf/types.git"
},
"keywords": [
"telegram",
"telegraf",
"bot",
"api",
"types",
"typings"
],
"scripts": {
"prepare": "deno task backport"
},
"author": "Telegraf contributors",
"types": "index.d.ts",
"license": "MIT",
"bugs": {
"url": "https://github.com/telegraf/types/issues"
},
"homepage": "https://github.com/telegraf/types#readme",
"files": [
"*.d.ts",
"index.js"
],
"devDependencies": {
"deno-bin": "^1.40.4"
}
}

163
node_modules/@telegraf/types/passport.d.ts generated vendored Normal file
View File

@@ -0,0 +1,163 @@
/** Describes Telegram Passport data shared with the bot by the user. */
export interface PassportData {
/** Array with information about documents and other Telegram Passport elements that was shared with the bot */
data: EncryptedPassportElement[];
/** Encrypted credentials required to decrypt the data */
credentials: EncryptedCredentials;
}
/** This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in JPEG format when decrypted and don't exceed 10MB. */
export interface PassportFile {
/** Identifier for this file, which can be used to download or reuse the file */
file_id: string;
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id: string;
/** File size in bytes */
file_size: number;
/** Unix time when the file was uploaded */
file_date: number;
}
/** Describes documents or other Telegram Passport elements shared with the bot by the user. */
export interface EncryptedPassportElement {
/** Element type. One of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”, “phone_number”, “email”. */
type: "personal_details" | "passport" | "driver_license" | "identity_card" | "internal_passport" | "address" | "utility_bill" | "bank_statement" | "rental_agreement" | "passport_registration" | "temporary_registration" | "phone_number" | "email";
/** Base64-encoded encrypted Telegram Passport element data provided by the user, available for “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport” and “address” types. Can be decrypted and verified using the accompanying EncryptedCredentials. */
data?: string;
/** User's verified phone number, available only for “phone_number” type */
phone_number?: string;
/** User's verified email address, available only for “email” type */
email?: string;
/** Array of encrypted files with documents provided by the user, available for “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials. */
files?: PassportFile[];
/** Encrypted file with the front side of the document, provided by the user. Available for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials. */
front_side?: PassportFile;
/** Encrypted file with the reverse side of the document, provided by the user. Available for “driver_license” and “identity_card”. The file can be decrypted and verified using the accompanying EncryptedCredentials. */
reverse_side?: PassportFile;
/** Encrypted file with the selfie of the user holding a document, provided by the user; available for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials. */
selfie?: PassportFile;
/** Array of encrypted files with translated versions of documents provided by the user. Available if requested for “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials. */
translation?: PassportFile[];
/** Base64-encoded element hash for using in PassportElementErrorUnspecified */
hash: string;
}
/** Describes data required for decrypting and authenticating EncryptedPassportElement. See the Telegram Passport Documentation for a complete description of the data decryption and authentication processes. */
export interface EncryptedCredentials {
/** Base64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets required for EncryptedPassportElement decryption and authentication */
data: string;
/** Base64-encoded data hash for data authentication */
hash: string;
/** Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption */
secret: string;
}
/** This object represents an error in the Telegram Passport element which was submitted that should be resolved by the user. It should be one of:
- PassportElementErrorDataField
- PassportElementErrorFrontSide
- PassportElementErrorReverseSide
- PassportElementErrorSelfie
- PassportElementErrorFile
- PassportElementErrorFiles
- PassportElementErrorTranslationFile
- PassportElementErrorTranslationFiles
- PassportElementErrorUnspecified
*/
export type PassportElementError = PassportElementErrorDataField | PassportElementErrorFrontSide | PassportElementErrorReverseSide | PassportElementErrorSelfie | PassportElementErrorFile | PassportElementErrorFiles | PassportElementErrorTranslationFile | PassportElementErrorTranslationFiles | PassportElementErrorUnspecified;
/** Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field's value changes. */
export interface PassportElementErrorDataField {
/** Error source, must be data */
source: "data";
/** The section of the user's Telegram Passport which has the error, one of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address” */
type: "personal_details" | "passport" | "driver_license" | "identity_card" | "internal_passport" | "address";
/** Name of the data field which has the error */
field_name: string;
/** Base64-encoded data hash */
data_hash: string;
/** Error message */
message: string;
}
/** Represents an issue with the front side of a document. The error is considered resolved when the file with the front side of the document changes. */
export interface PassportElementErrorFrontSide {
/** Error source, must be front_side */
source: "front_side";
/** The section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport” */
type: "passport" | "driver_license" | "identity_card" | "internal_passport";
/** Base64-encoded hash of the file with the front side of the document */
file_hash: string;
/** Error message */
message: string;
}
/** Represents an issue with the reverse side of a document. The error is considered resolved when the file with reverse side of the document changes. */
export interface PassportElementErrorReverseSide {
/** Error source, must be reverse_side */
source: "reverse_side";
/** The section of the user's Telegram Passport which has the issue, one of “driver_license”, “identity_card” */
type: "driver_license" | "identity_card";
/** Base64-encoded hash of the file with the reverse side of the document */
file_hash: string;
/** Error message */
message: string;
}
/** Represents an issue with the selfie with a document. The error is considered resolved when the file with the selfie changes. */
export interface PassportElementErrorSelfie {
/** Error source, must be selfie */
source: "selfie";
/** The section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport” */
type: "passport" | "driver_license" | "identity_card" | "internal_passport";
/** Base64-encoded hash of the file with the selfie */
file_hash: string;
/** Error message */
message: string;
}
/** Represents an issue with a document scan. The error is considered resolved when the file with the document scan changes. */
export interface PassportElementErrorFile {
/** Error source, must be file */
source: "file";
/** The section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” */
type: "utility_bill" | "bank_statement" | "rental_agreement" | "passport_registration" | "temporary_registration";
/** Base64-encoded file hash */
file_hash: string;
/** Error message */
message: string;
}
/** Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes. */
export interface PassportElementErrorFiles {
/** Error source, must be files */
source: "files";
/** The section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” */
type: "utility_bill" | "bank_statement" | "rental_agreement" | "passport_registration" | "temporary_registration";
/** List of base64-encoded file hashes */
file_hashes: string[];
/** Error message */
message: string;
}
/** Represents an issue with one of the files that constitute the translation of a document. The error is considered resolved when the file changes. */
export interface PassportElementErrorTranslationFile {
/** Error source, must be translation_file */
source: "translation_file";
/** Type of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” */
type: "passport" | "driver_license" | "identity_card" | "internal_passport" | "utility_bill" | "bank_statement" | "rental_agreement" | "passport_registration" | "temporary_registration";
/** Base64-encoded file hash */
file_hash: string;
/** Error message */
message: string;
}
/** Represents an issue with the translated version of a document. The error is considered resolved when a file with the document translation change. */
export interface PassportElementErrorTranslationFiles {
/** Error source, must be translation_files */
source: "translation_files";
/** Type of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” */
type: "passport" | "driver_license" | "identity_card" | "internal_passport" | "utility_bill" | "bank_statement" | "rental_agreement" | "passport_registration" | "temporary_registration";
/** List of base64-encoded file hashes */
file_hashes: string[];
/** Error message */
message: string;
}
/** Represents an issue in an unspecified place. The error is considered resolved when new data is added. */
export interface PassportElementErrorUnspecified {
/** Error source, must be unspecified */
source: "unspecified";
/** Type of element of the user's Telegram Passport which has the issue */
type: string;
/** Base64-encoded element hash */
element_hash: string;
/** Error message */
message: string;
}

101
node_modules/@telegraf/types/payment.d.ts generated vendored Normal file
View File

@@ -0,0 +1,101 @@
import type { User } from "./manage.js";
/** This object represents a portion of the price for goods or services. */
export interface LabeledPrice {
/** Portion label */
label: string;
/** Price of the product in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). */
amount: number;
}
/** This object contains basic information about an invoice. */
export interface Invoice {
/** Product name */
title: string;
/** Product description */
description: string;
/** Unique bot deep-linking parameter that can be used to generate this invoice */
start_parameter: string;
/** Three-letter ISO 4217 currency code */
currency: string;
/** Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). */
total_amount: number;
}
/** This object represents a shipping address. */
export interface ShippingAddress {
/** Two-letter ISO 3166-1 alpha-2 country code */
country_code: string;
/** State, if applicable */
state: string;
/** City */
city: string;
/** First line for the address */
street_line1: string;
/** Second line for the address */
street_line2: string;
/** Address post code */
post_code: string;
}
/** This object represents information about an order. */
export interface OrderInfo {
/** User name */
name?: string;
/** User's phone number */
phone_number?: string;
/** User email */
email?: string;
/** User shipping address */
shipping_address?: ShippingAddress;
}
/** This object represents one shipping option. */
export interface ShippingOption {
/** Shipping option identifier */
id: string;
/** Option title */
title: string;
/** List of price portions */
prices: LabeledPrice[];
}
/** This object contains basic information about a successful payment. */
export interface SuccessfulPayment {
/** Three-letter ISO 4217 currency code */
currency: string;
/** Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). */
total_amount: number;
/** Bot specified invoice payload */
invoice_payload: string;
/** Identifier of the shipping option chosen by the user */
shipping_option_id?: string;
/** Order information provided by the user */
order_info?: OrderInfo;
/** Telegram payment identifier */
telegram_payment_charge_id: string;
/** Provider payment identifier */
provider_payment_charge_id: string;
}
/** This object contains information about an incoming shipping query. */
export interface ShippingQuery {
/** Unique query identifier */
id: string;
/** User who sent the query */
from: User;
/** Bot specified invoice payload */
invoice_payload: string;
/** User specified shipping address */
shipping_address: ShippingAddress;
}
/** This object contains information about an incoming pre-checkout query. */
export interface PreCheckoutQuery {
/** Unique query identifier */
id: string;
/** User who sent the query */
from: User;
/** Three-letter ISO 4217 currency code */
currency: string;
/** Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). */
total_amount: number;
/** Bot specified invoice payload */
invoice_payload: string;
/** Identifier of the shipping option chosen by the user */
shipping_option_id?: string;
/** Order information provided by the user */
order_info?: OrderInfo;
}

120
node_modules/@telegraf/types/settings.d.ts generated vendored Normal file
View File

@@ -0,0 +1,120 @@
import type { WebAppInfo } from "./markup.js";
/** This object represents the bot's name. */
export interface BotName {
/** The bot's name */
name: string;
}
/** This object represents the bot's description. */
export interface BotDescription {
/** The bot's description */
description: string;
}
/** This object represents the bot's short description. */
export interface BotShortDescription {
/** The bot's short description */
short_description: string;
}
/** This object describes the bot's menu button in a private chat. It should be one of
- MenuButtonCommands
- MenuButtonWebApp
- MenuButtonDefault
If a menu button other than MenuButtonDefault is set for a private chat, then it is applied in the chat. Otherwise the default menu button is applied. By default, the menu button opens the list of bot commands. */
export type MenuButton = MenuButtonCommands | MenuButtonWebApp | MenuButtonDefault;
/** Represents a menu button, which opens the bot's list of commands. */
export interface MenuButtonCommands {
/** Type of the button, must be commands */
type: "commands";
}
/** Represents a menu button, which launches a Web App. */
export interface MenuButtonWebApp {
/** Button type, must be web_app */
type: "web_app";
/** Text on the button */
text: string;
/** Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. */
web_app: WebAppInfo;
}
/** Describes that no specific value for the menu button was set. */
export interface MenuButtonDefault {
/** Type of the button, must be default */
type: "default";
}
/** This object represents the scope to which bot commands are applied. Currently, the following 7 scopes are supported:
- BotCommandScopeDefault
- BotCommandScopeAllPrivateChats
- BotCommandScopeAllGroupChats
- BotCommandScopeAllChatAdministrators
- BotCommandScopeChat
- BotCommandScopeChatAdministrators
- BotCommandScopeChatMember
## Determining list of commands
The following algorithm is used to determine the list of commands for a particular user viewing the bot menu. The first list of commands which is set is returned:
### Commands in the chat with the bot
- botCommandScopeChat + language_code
- botCommandScopeChat
- botCommandScopeAllPrivateChats + language_code
- botCommandScopeAllPrivateChats
- botCommandScopeDefault + language_code
- botCommandScopeDefault
### Commands in group and supergroup chats
- botCommandScopeChatMember + language_code
- botCommandScopeChatMember
- botCommandScopeChatAdministrators + language_code (administrators only)
- botCommandScopeChatAdministrators (administrators only)
- botCommandScopeChat + language_code
- botCommandScopeChat
- botCommandScopeAllChatAdministrators + language_code (administrators only)
- botCommandScopeAllChatAdministrators (administrators only)
- botCommandScopeAllGroupChats + language_code
- botCommandScopeAllGroupChats
- botCommandScopeDefault + language_code
- botCommandScopeDefault */
export type BotCommandScope = BotCommandScopeDefault | BotCommandScopeAllPrivateChats | BotCommandScopeAllGroupChats | BotCommandScopeAllChatAdministrators | BotCommandScopeChat | BotCommandScopeChatAdministrators | BotCommandScopeChatMember;
/** Represents the default scope of bot commands. Default commands are used if no commands with a narrower scope are specified for the user. */
export interface BotCommandScopeDefault {
/** Scope type, must be default */
type: "default";
}
/** Represents the scope of bot commands, covering all private chats. */
export interface BotCommandScopeAllPrivateChats {
/** Scope type, must be all_private_chats */
type: "all_private_chats";
}
/** Represents the scope of bot commands, covering all group and supergroup chats. */
export interface BotCommandScopeAllGroupChats {
/** Scope type, must be all_group_chats */
type: "all_group_chats";
}
/** Represents the scope of bot commands, covering all group and supergroup chat administrators. */
export interface BotCommandScopeAllChatAdministrators {
/** Scope type, must be all_chat_administrators */
type: "all_chat_administrators";
}
/** Represents the scope of bot commands, covering a specific chat. */
export interface BotCommandScopeChat {
/** Scope type, must be chat */
type: "chat";
/** Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) */
chat_id: number | string;
}
/** Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat. */
export interface BotCommandScopeChatAdministrators {
/** Scope type, must be chat_administrators */
type: "chat_administrators";
/** Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) */
chat_id: number | string;
}
/** Represents the scope of bot commands, covering a specific member of a group or supergroup chat. */
export interface BotCommandScopeChatMember {
/** Scope type, must be chat_member */
type: "chat_member";
/** Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) */
chat_id: number | string;
/** Unique identifier of the target user */
user_id: number;
}

113
node_modules/@telegraf/types/update.d.ts generated vendored Normal file
View File

@@ -0,0 +1,113 @@
import type { ChosenInlineResult, InlineQuery } from "./inline.js";
import type { Chat, ChatBoostRemoved, ChatBoostUpdated, ChatJoinRequest, ChatMemberUpdated, MessageReactionCountUpdated, MessageReactionUpdated, User } from "./manage.js";
import type { CallbackQuery } from "./markup.js";
import type { CommonMessageBundle, Message, Poll, PollAnswer } from "./message.js";
import type { PreCheckoutQuery, ShippingQuery } from "./payment.js";
export declare namespace Update {
/** Internal type holding properties that updates in channels share. */
interface Channel {
chat: Chat.ChannelChat;
author_signature?: string;
from?: never;
}
/** Internal type holding properties that updates outside of channels share. */
interface NonChannel {
chat: Exclude<Chat, Chat.ChannelChat>;
author_signature?: never;
from: User;
}
/** Internal type holding properties that updates about new messages share. */
interface New {
edit_date?: never;
}
/** Internal type holding properties that updates about edited messages share. */
interface Edited {
/** Date the message was last edited in Unix time */
edit_date: number;
forward_from?: never;
forward_from_chat?: never;
forward_from_message_id?: never;
forward_signature?: never;
forward_sender_name?: never;
forward_date?: never;
}
interface AbstractUpdate {
/** The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you're using webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially. */
update_id: number;
}
interface MessageUpdate<M extends Message = Message> extends AbstractUpdate {
/** New incoming message of any kind - text, photo, sticker, etc. */
message: New & NonChannel & M;
}
interface EditedMessageUpdate<M extends CommonMessageBundle = CommonMessageBundle> extends AbstractUpdate {
/** New version of a message that is known to the bot and was edited */
edited_message: Edited & NonChannel & M;
}
interface ChannelPostUpdate<M extends Message = Message> extends AbstractUpdate {
/** New incoming channel post of any kind - text, photo, sticker, etc. */
channel_post: New & Channel & M;
}
interface EditedChannelPostUpdate<M extends CommonMessageBundle = CommonMessageBundle> extends AbstractUpdate {
/** New version of a channel post that is known to the bot and was edited */
edited_channel_post: Edited & Channel & M;
}
interface MessageReactionUpdate extends AbstractUpdate {
/** A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify `"message_reaction"` in the list of allowed_updates to receive these updates. The update isn't received for reactions set by bots. */
message_reaction: MessageReactionUpdated;
}
interface MessageReactionCountUpdate extends AbstractUpdate {
/** Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify `"message_reaction_count"` in the list of allowed_updates to receive these updates. */
message_reaction_count: MessageReactionCountUpdated;
}
interface InlineQueryUpdate extends AbstractUpdate {
/** New incoming inline query */
inline_query: InlineQuery;
}
interface ChosenInlineResultUpdate extends AbstractUpdate {
/** The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot. */
chosen_inline_result: ChosenInlineResult;
}
interface CallbackQueryUpdate<C extends CallbackQuery = CallbackQuery> extends AbstractUpdate {
/** New incoming callback query */
callback_query: C;
}
interface ShippingQueryUpdate extends AbstractUpdate {
/** New incoming shipping query. Only for invoices with flexible price */
shipping_query: ShippingQuery;
}
interface PreCheckoutQueryUpdate extends AbstractUpdate {
/** New incoming pre-checkout query. Contains full information about checkout */
pre_checkout_query: PreCheckoutQuery;
}
interface PollUpdate extends AbstractUpdate {
/** New poll state. Bots receive only updates about stopped polls and polls, which are sent by the bot */
poll: Poll;
}
interface PollAnswerUpdate extends AbstractUpdate {
/** A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself. */
poll_answer: PollAnswer;
}
interface MyChatMemberUpdate extends AbstractUpdate {
/** The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user. */
my_chat_member: ChatMemberUpdated;
}
interface ChatMemberUpdate extends AbstractUpdate {
/** A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates. */
chat_member: ChatMemberUpdated;
}
interface ChatJoinRequestUpdate extends AbstractUpdate {
/** A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates. */
chat_join_request: ChatJoinRequest;
}
interface ChatBoostUpdate extends AbstractUpdate {
/** A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates. */
chat_boost: ChatBoostUpdated;
}
interface RemovedChatBoostUpdate extends AbstractUpdate {
/** A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates. */
removed_chat_boost: ChatBoostRemoved;
}
}
/** This object represents an incoming update.
At most one of the optional parameters can be present in any given update. */
export type Update = Update.CallbackQueryUpdate | Update.ChannelPostUpdate | Update.ChatMemberUpdate | Update.ChosenInlineResultUpdate | Update.EditedChannelPostUpdate | Update.MessageReactionUpdate | Update.MessageReactionCountUpdate | Update.EditedMessageUpdate | Update.InlineQueryUpdate | Update.MessageUpdate | Update.MyChatMemberUpdate | Update.PreCheckoutQueryUpdate | Update.PollAnswerUpdate | Update.PollUpdate | Update.ShippingQueryUpdate | Update.ChatJoinRequestUpdate | Update.ChatBoostUpdate | Update.RemovedChatBoostUpdate;

21
node_modules/abort-controller/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Toru Nagashima
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.

98
node_modules/abort-controller/README.md generated vendored Normal file
View File

@@ -0,0 +1,98 @@
# abort-controller
[![npm version](https://img.shields.io/npm/v/abort-controller.svg)](https://www.npmjs.com/package/abort-controller)
[![Downloads/month](https://img.shields.io/npm/dm/abort-controller.svg)](http://www.npmtrends.com/abort-controller)
[![Build Status](https://travis-ci.org/mysticatea/abort-controller.svg?branch=master)](https://travis-ci.org/mysticatea/abort-controller)
[![Coverage Status](https://codecov.io/gh/mysticatea/abort-controller/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/abort-controller)
[![Dependency Status](https://david-dm.org/mysticatea/abort-controller.svg)](https://david-dm.org/mysticatea/abort-controller)
An implementation of [WHATWG AbortController interface](https://dom.spec.whatwg.org/#interface-abortcontroller).
```js
import AbortController from "abort-controller"
const controller = new AbortController()
const signal = controller.signal
signal.addEventListener("abort", () => {
console.log("aborted!")
})
controller.abort()
```
> https://jsfiddle.net/1r2994qp/1/
## 💿 Installation
Use [npm](https://www.npmjs.com/) to install then use a bundler.
```
npm install abort-controller
```
Or download from [`dist` directory](./dist).
- [dist/abort-controller.mjs](dist/abort-controller.mjs) ... ES modules version.
- [dist/abort-controller.js](dist/abort-controller.js) ... Common JS version.
- [dist/abort-controller.umd.js](dist/abort-controller.umd.js) ... UMD (Universal Module Definition) version. This is transpiled by [Babel](https://babeljs.io/) for IE 11.
## 📖 Usage
### Basic
```js
import AbortController from "abort-controller"
// or
const AbortController = require("abort-controller")
// or UMD version defines a global variable:
const AbortController = window.AbortControllerShim
```
If your bundler recognizes `browser` field of `package.json`, the imported `AbortController` is the native one and it doesn't contain shim (even if the native implementation was nothing).
If you wanted to polyfill `AbortController` for IE, use `abort-controller/polyfill`.
### Polyfilling
Importing `abort-controller/polyfill` assigns the `AbortController` shim to the `AbortController` global variable if the native implementation was nothing.
```js
import "abort-controller/polyfill"
// or
require("abort-controller/polyfill")
```
### API
#### AbortController
> https://dom.spec.whatwg.org/#interface-abortcontroller
##### controller.signal
The [AbortSignal](https://dom.spec.whatwg.org/#interface-AbortSignal) object which is associated to this controller.
##### controller.abort()
Notify `abort` event to listeners that the `signal` has.
## 📰 Changelog
- See [GitHub releases](https://github.com/mysticatea/abort-controller/releases).
## 🍻 Contributing
Contributing is welcome ❤️
Please use GitHub issues/PRs.
### Development tools
- `npm install` installs dependencies for development.
- `npm test` runs tests and measures code coverage.
- `npm run clean` removes temporary files of tests.
- `npm run coverage` opens code coverage of the previous test with your default browser.
- `npm run lint` runs ESLint.
- `npm run build` generates `dist` codes.
- `npm run watch` runs tests on each file change.

13
node_modules/abort-controller/browser.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
/*globals self, window */
"use strict"
/*eslint-disable @mysticatea/prettier */
const { AbortController, AbortSignal } =
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
/* otherwise */ undefined
/*eslint-enable @mysticatea/prettier */
module.exports = AbortController
module.exports.AbortSignal = AbortSignal
module.exports.default = AbortController

11
node_modules/abort-controller/browser.mjs generated vendored Normal file
View File

@@ -0,0 +1,11 @@
/*globals self, window */
/*eslint-disable @mysticatea/prettier */
const { AbortController, AbortSignal } =
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
/* otherwise */ undefined
/*eslint-enable @mysticatea/prettier */
export default AbortController
export { AbortController, AbortSignal }

View File

@@ -0,0 +1,43 @@
import { EventTarget } from "event-target-shim"
type Events = {
abort: any
}
type EventAttributes = {
onabort: any
}
/**
* The signal class.
* @see https://dom.spec.whatwg.org/#abortsignal
*/
declare class AbortSignal extends EventTarget<Events, EventAttributes> {
/**
* AbortSignal cannot be constructed directly.
*/
constructor()
/**
* Returns `true` if this `AbortSignal`"s `AbortController` has signaled to abort, and `false` otherwise.
*/
readonly aborted: boolean
}
/**
* The AbortController.
* @see https://dom.spec.whatwg.org/#abortcontroller
*/
declare class AbortController {
/**
* Initialize this controller.
*/
constructor()
/**
* Returns the `AbortSignal` object associated with this object.
*/
readonly signal: AbortSignal
/**
* Abort and signal to any observers that the associated activity is to be aborted.
*/
abort(): void
}
export default AbortController
export { AbortController, AbortSignal }

127
node_modules/abort-controller/dist/abort-controller.js generated vendored Normal file
View File

@@ -0,0 +1,127 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var eventTargetShim = require('event-target-shim');
/**
* The signal class.
* @see https://dom.spec.whatwg.org/#abortsignal
*/
class AbortSignal extends eventTargetShim.EventTarget {
/**
* AbortSignal cannot be constructed directly.
*/
constructor() {
super();
throw new TypeError("AbortSignal cannot be constructed directly");
}
/**
* Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.
*/
get aborted() {
const aborted = abortedFlags.get(this);
if (typeof aborted !== "boolean") {
throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`);
}
return aborted;
}
}
eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort");
/**
* Create an AbortSignal object.
*/
function createAbortSignal() {
const signal = Object.create(AbortSignal.prototype);
eventTargetShim.EventTarget.call(signal);
abortedFlags.set(signal, false);
return signal;
}
/**
* Abort a given signal.
*/
function abortSignal(signal) {
if (abortedFlags.get(signal) !== false) {
return;
}
abortedFlags.set(signal, true);
signal.dispatchEvent({ type: "abort" });
}
/**
* Aborted flag for each instances.
*/
const abortedFlags = new WeakMap();
// Properties should be enumerable.
Object.defineProperties(AbortSignal.prototype, {
aborted: { enumerable: true },
});
// `toString()` should return `"[object AbortSignal]"`
if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {
configurable: true,
value: "AbortSignal",
});
}
/**
* The AbortController.
* @see https://dom.spec.whatwg.org/#abortcontroller
*/
class AbortController {
/**
* Initialize this controller.
*/
constructor() {
signals.set(this, createAbortSignal());
}
/**
* Returns the `AbortSignal` object associated with this object.
*/
get signal() {
return getSignal(this);
}
/**
* Abort and signal to any observers that the associated activity is to be aborted.
*/
abort() {
abortSignal(getSignal(this));
}
}
/**
* Associated signals.
*/
const signals = new WeakMap();
/**
* Get the associated signal of a given controller.
*/
function getSignal(controller) {
const signal = signals.get(controller);
if (signal == null) {
throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`);
}
return signal;
}
// Properties should be enumerable.
Object.defineProperties(AbortController.prototype, {
signal: { enumerable: true },
abort: { enumerable: true },
});
if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {
configurable: true,
value: "AbortController",
});
}
exports.AbortController = AbortController;
exports.AbortSignal = AbortSignal;
exports.default = AbortController;
module.exports = AbortController
module.exports.AbortController = module.exports["default"] = AbortController
module.exports.AbortSignal = AbortSignal
//# sourceMappingURL=abort-controller.js.map

File diff suppressed because one or more lines are too long

118
node_modules/abort-controller/dist/abort-controller.mjs generated vendored Normal file
View File

@@ -0,0 +1,118 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
import { EventTarget, defineEventAttribute } from 'event-target-shim';
/**
* The signal class.
* @see https://dom.spec.whatwg.org/#abortsignal
*/
class AbortSignal extends EventTarget {
/**
* AbortSignal cannot be constructed directly.
*/
constructor() {
super();
throw new TypeError("AbortSignal cannot be constructed directly");
}
/**
* Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.
*/
get aborted() {
const aborted = abortedFlags.get(this);
if (typeof aborted !== "boolean") {
throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`);
}
return aborted;
}
}
defineEventAttribute(AbortSignal.prototype, "abort");
/**
* Create an AbortSignal object.
*/
function createAbortSignal() {
const signal = Object.create(AbortSignal.prototype);
EventTarget.call(signal);
abortedFlags.set(signal, false);
return signal;
}
/**
* Abort a given signal.
*/
function abortSignal(signal) {
if (abortedFlags.get(signal) !== false) {
return;
}
abortedFlags.set(signal, true);
signal.dispatchEvent({ type: "abort" });
}
/**
* Aborted flag for each instances.
*/
const abortedFlags = new WeakMap();
// Properties should be enumerable.
Object.defineProperties(AbortSignal.prototype, {
aborted: { enumerable: true },
});
// `toString()` should return `"[object AbortSignal]"`
if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {
configurable: true,
value: "AbortSignal",
});
}
/**
* The AbortController.
* @see https://dom.spec.whatwg.org/#abortcontroller
*/
class AbortController {
/**
* Initialize this controller.
*/
constructor() {
signals.set(this, createAbortSignal());
}
/**
* Returns the `AbortSignal` object associated with this object.
*/
get signal() {
return getSignal(this);
}
/**
* Abort and signal to any observers that the associated activity is to be aborted.
*/
abort() {
abortSignal(getSignal(this));
}
}
/**
* Associated signals.
*/
const signals = new WeakMap();
/**
* Get the associated signal of a given controller.
*/
function getSignal(controller) {
const signal = signals.get(controller);
if (signal == null) {
throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`);
}
return signal;
}
// Properties should be enumerable.
Object.defineProperties(AbortController.prototype, {
signal: { enumerable: true },
abort: { enumerable: true },
});
if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {
configurable: true,
value: "AbortController",
});
}
export default AbortController;
export { AbortController, AbortSignal };
//# sourceMappingURL=abort-controller.mjs.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

97
node_modules/abort-controller/package.json generated vendored Normal file
View File

@@ -0,0 +1,97 @@
{
"name": "abort-controller",
"version": "3.0.0",
"description": "An implementation of WHATWG AbortController interface.",
"main": "dist/abort-controller",
"files": [
"dist",
"polyfill.*",
"browser.*"
],
"engines": {
"node": ">=6.5"
},
"dependencies": {
"event-target-shim": "^5.0.0"
},
"browser": "./browser.js",
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/plugin-transform-modules-commonjs": "^7.2.0",
"@babel/preset-env": "^7.3.0",
"@babel/register": "^7.0.0",
"@mysticatea/eslint-plugin": "^8.0.1",
"@mysticatea/spy": "^0.1.2",
"@types/mocha": "^5.2.5",
"@types/node": "^10.12.18",
"assert": "^1.4.1",
"codecov": "^3.1.0",
"dts-bundle-generator": "^2.0.0",
"eslint": "^5.12.1",
"karma": "^3.1.4",
"karma-chrome-launcher": "^2.2.0",
"karma-coverage": "^1.1.2",
"karma-firefox-launcher": "^1.1.0",
"karma-growl-reporter": "^1.0.0",
"karma-ie-launcher": "^1.0.0",
"karma-mocha": "^1.3.0",
"karma-rollup-preprocessor": "^7.0.0-rc.2",
"mocha": "^5.2.0",
"npm-run-all": "^4.1.5",
"nyc": "^13.1.0",
"opener": "^1.5.1",
"rimraf": "^2.6.3",
"rollup": "^1.1.2",
"rollup-plugin-babel": "^4.3.2",
"rollup-plugin-babel-minify": "^7.0.0",
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-node-resolve": "^4.0.0",
"rollup-plugin-sourcemaps": "^0.4.2",
"rollup-plugin-typescript": "^1.0.0",
"rollup-watch": "^4.3.1",
"ts-node": "^8.0.1",
"type-tester": "^1.0.0",
"typescript": "^3.2.4"
},
"scripts": {
"preversion": "npm test",
"version": "npm run -s build && git add dist/*",
"postversion": "git push && git push --tags",
"clean": "rimraf .nyc_output coverage",
"coverage": "opener coverage/lcov-report/index.html",
"lint": "eslint . --ext .ts",
"build": "run-s -s build:*",
"build:rollup": "rollup -c",
"build:dts": "dts-bundle-generator -o dist/abort-controller.d.ts src/abort-controller.ts && ts-node scripts/fix-dts",
"test": "run-s -s lint test:*",
"test:mocha": "nyc mocha test/*.ts",
"test:karma": "karma start --single-run",
"watch": "run-p -s watch:*",
"watch:mocha": "mocha test/*.ts --require ts-node/register --watch-extensions ts --watch --growl",
"watch:karma": "karma start --watch",
"codecov": "codecov"
},
"repository": {
"type": "git",
"url": "git+https://github.com/mysticatea/abort-controller.git"
},
"keywords": [
"w3c",
"whatwg",
"event",
"events",
"abort",
"cancel",
"abortcontroller",
"abortsignal",
"controller",
"signal",
"shim"
],
"author": "Toru Nagashima (https://github.com/mysticatea)",
"license": "MIT",
"bugs": {
"url": "https://github.com/mysticatea/abort-controller/issues"
},
"homepage": "https://github.com/mysticatea/abort-controller#readme"
}

21
node_modules/abort-controller/polyfill.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
/*globals require, self, window */
"use strict"
const ac = require("./dist/abort-controller")
/*eslint-disable @mysticatea/prettier */
const g =
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
typeof global !== "undefined" ? global :
/* otherwise */ undefined
/*eslint-enable @mysticatea/prettier */
if (g) {
if (typeof g.AbortController === "undefined") {
g.AbortController = ac.AbortController
}
if (typeof g.AbortSignal === "undefined") {
g.AbortSignal = ac.AbortSignal
}
}

19
node_modules/abort-controller/polyfill.mjs generated vendored Normal file
View File

@@ -0,0 +1,19 @@
/*globals self, window */
import * as ac from "./dist/abort-controller"
/*eslint-disable @mysticatea/prettier */
const g =
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
typeof global !== "undefined" ? global :
/* otherwise */ undefined
/*eslint-enable @mysticatea/prettier */
if (g) {
if (typeof g.AbortController === "undefined") {
g.AbortController = ac.AbortController
}
if (typeof g.AbortSignal === "undefined") {
g.AbortSignal = ac.AbortSignal
}
}

17
node_modules/buffer-alloc-unsafe/index.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
function allocUnsafe (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
}
if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
if (Buffer.allocUnsafe) {
return Buffer.allocUnsafe(size)
} else {
return new Buffer(size)
}
}
module.exports = allocUnsafe

24
node_modules/buffer-alloc-unsafe/package.json generated vendored Normal file
View File

@@ -0,0 +1,24 @@
{
"name": "buffer-alloc-unsafe",
"version": "1.1.0",
"license": "MIT",
"repository": "LinusU/buffer-alloc-unsafe",
"files": [
"index.js"
],
"scripts": {
"test": "standard && node test"
},
"devDependencies": {
"standard": "^7.1.2"
},
"keywords": [
"allocUnsafe",
"allocate",
"buffer allocUnsafe",
"buffer unsafe allocate",
"buffer",
"ponyfill",
"unsafe allocate"
]
}

46
node_modules/buffer-alloc-unsafe/readme.md generated vendored Normal file
View File

@@ -0,0 +1,46 @@
# Buffer Alloc Unsafe
A [ponyfill](https://ponyfill.com) for `Buffer.allocUnsafe`.
Works as Node.js: `v7.0.0` <br>
Works on Node.js: `v0.10.0`
## Installation
```sh
npm install --save buffer-alloc-unsafe
```
## Usage
```js
const allocUnsafe = require('buffer-alloc-unsafe')
console.log(allocUnsafe(10))
//=> <Buffer 78 0c 80 03 01 00 00 00 05 00>
console.log(allocUnsafe(10))
//=> <Buffer 58 ed bf 5f ff 7f 00 00 01 00>
console.log(allocUnsafe(10))
//=> <Buffer 50 0c 80 03 01 00 00 00 0a 00>
allocUnsafe(-10)
//=> RangeError: "size" argument must not be negative
```
## API
### allocUnsafe(size)
- `size` &lt;Integer&gt; The desired length of the new `Buffer`
Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be
less than or equal to the value of `buffer.kMaxLength` and greater than or equal
to zero. Otherwise, a `RangeError` is thrown.
## See also
- [buffer-alloc](https://github.com/LinusU/buffer-alloc) A ponyfill for `Buffer.alloc`
- [buffer-fill](https://github.com/LinusU/buffer-fill) A ponyfill for `Buffer.fill`
- [buffer-from](https://github.com/LinusU/buffer-from) A ponyfill for `Buffer.from`

32
node_modules/buffer-alloc/index.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
var bufferFill = require('buffer-fill')
var allocUnsafe = require('buffer-alloc-unsafe')
module.exports = function alloc (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
}
if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
if (Buffer.alloc) {
return Buffer.alloc(size, fill, encoding)
}
var buffer = allocUnsafe(size)
if (size === 0) {
return buffer
}
if (fill === undefined) {
return bufferFill(buffer, 0)
}
if (typeof encoding !== 'string') {
encoding = undefined
}
return bufferFill(buffer, fill, encoding)
}

26
node_modules/buffer-alloc/package.json generated vendored Normal file
View File

@@ -0,0 +1,26 @@
{
"name": "buffer-alloc",
"version": "1.2.0",
"license": "MIT",
"repository": "LinusU/buffer-alloc",
"files": [
"index.js"
],
"scripts": {
"test": "standard && node test"
},
"dependencies": {
"buffer-alloc-unsafe": "^1.1.0",
"buffer-fill": "^1.0.0"
},
"devDependencies": {
"standard": "^7.1.2"
},
"keywords": [
"alloc",
"allocate",
"buffer alloc",
"buffer allocate",
"buffer"
]
}

43
node_modules/buffer-alloc/readme.md generated vendored Normal file
View File

@@ -0,0 +1,43 @@
# Buffer Alloc
A [ponyfill](https://ponyfill.com) for `Buffer.alloc`.
Works as Node.js: `v7.0.0` <br>
Works on Node.js: `v0.10.0`
## Installation
```sh
npm install --save buffer-alloc
```
## Usage
```js
const alloc = require('buffer-alloc')
console.log(alloc(4))
//=> <Buffer 00 00 00 00>
console.log(alloc(6, 0x41))
//=> <Buffer 41 41 41 41 41 41>
console.log(alloc(10, 'linus', 'utf8'))
//=> <Buffer 6c 69 6e 75 73 6c 69 6e 75 73>
```
## API
### alloc(size[, fill[, encoding]])
- `size` &lt;Integer&gt; The desired length of the new `Buffer`
- `fill` &lt;String&gt; | &lt;Buffer&gt; | &lt;Integer&gt; A value to pre-fill the new `Buffer` with. **Default:** `0`
- `encoding` &lt;String&gt; If `fill` is a string, this is its encoding. **Default:** `'utf8'`
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be zero-filled.
## See also
- [buffer-alloc-unsafe](https://github.com/LinusU/buffer-alloc-unsafe) A ponyfill for `Buffer.allocUnsafe`
- [buffer-fill](https://github.com/LinusU/buffer-fill) A ponyfill for `Buffer.fill`
- [buffer-from](https://github.com/LinusU/buffer-from) A ponyfill for `Buffer.from`

113
node_modules/buffer-fill/index.js generated vendored Normal file
View File

@@ -0,0 +1,113 @@
/* Node.js 6.4.0 and up has full support */
var hasFullSupport = (function () {
try {
if (!Buffer.isEncoding('latin1')) {
return false
}
var buf = Buffer.alloc ? Buffer.alloc(4) : new Buffer(4)
buf.fill('ab', 'ucs2')
return (buf.toString('hex') === '61006200')
} catch (_) {
return false
}
}())
function isSingleByte (val) {
return (val.length === 1 && val.charCodeAt(0) < 256)
}
function fillWithNumber (buffer, val, start, end) {
if (start < 0 || end > buffer.length) {
throw new RangeError('Out of range index')
}
start = start >>> 0
end = end === undefined ? buffer.length : end >>> 0
if (end > start) {
buffer.fill(val, start, end)
}
return buffer
}
function fillWithBuffer (buffer, val, start, end) {
if (start < 0 || end > buffer.length) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return buffer
}
start = start >>> 0
end = end === undefined ? buffer.length : end >>> 0
var pos = start
var len = val.length
while (pos <= (end - len)) {
val.copy(buffer, pos)
pos += len
}
if (pos !== end) {
val.copy(buffer, pos, 0, end - pos)
}
return buffer
}
function fill (buffer, val, start, end, encoding) {
if (hasFullSupport) {
return buffer.fill(val, start, end, encoding)
}
if (typeof val === 'number') {
return fillWithNumber(buffer, val, start, end)
}
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = buffer.length
} else if (typeof end === 'string') {
encoding = end
end = buffer.length
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (encoding === 'latin1') {
encoding = 'binary'
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
if (val === '') {
return fillWithNumber(buffer, 0, start, end)
}
if (isSingleByte(val)) {
return fillWithNumber(buffer, val.charCodeAt(0), start, end)
}
val = new Buffer(val, encoding)
}
if (Buffer.isBuffer(val)) {
return fillWithBuffer(buffer, val, start, end)
}
// Other values (e.g. undefined, boolean, object) results in zero-fill
return fillWithNumber(buffer, 0, start, end)
}
module.exports = fill

16
node_modules/buffer-fill/package.json generated vendored Normal file
View File

@@ -0,0 +1,16 @@
{
"name": "buffer-fill",
"version": "1.0.0",
"license": "MIT",
"repository": "LinusU/buffer-fill",
"files": [
"index.js"
],
"scripts": {
"test": "standard && node test"
},
"devDependencies": {
"buffer-alloc-unsafe": "^1.1.0",
"standard": "^7.1.2"
}
}

54
node_modules/buffer-fill/readme.md generated vendored Normal file
View File

@@ -0,0 +1,54 @@
# Buffer Fill
A [ponyfill](https://ponyfill.com) for `Buffer.fill`.
Works as Node.js: `v6.4.0` <br>
Works on Node.js: `v0.10.0`
## Installation
```sh
npm install --save buffer-fill
```
## Usage
```js
const fill = require('buffer-fill')
const buf = Buffer.allocUnsafe(5)
console.log(buf.fill(8))
//=> <Buffer 08 08 08 08 08>
console.log(buf.fill(9, 2, 4))
//=> <Buffer 08 08 09 09 08>
console.log(buf.fill('linus', 'latin1'))
//=> <Buffer 6c 69 6e 75 73>
console.log(buf.fill('\u0222'))
//=> <Buffer c8 a2 c8 a2 c8>
```
## API
### fill(buf, value[, offset[, end]][, encoding])
- `value` &lt;String&gt; | &lt;Buffer&gt; | &lt;Integer&gt; The value to fill `buf` with
- `offset` &lt;Integer&gt; Where to start filling `buf`. **Default:** `0`
- `end` &lt;Integer&gt; Where to stop filling `buf` (not inclusive). **Default:** `buf.length`
- `encoding` &lt;String&gt; If `value` is a string, this is its encoding. **Default:** `'utf8'`
- Return: &lt;Buffer&gt; A reference to `buf`
Fills `buf` with the specified `value`. If the `offset` and `end` are not given,
the entire `buf` will be filled. This is meant to be a small simplification to
allow the creation and filling of a `Buffer` to be done on a single line.
If the final write of a `fill()` operation falls on a multi-byte character, then
only the first bytes of that character that fit into `buf` are written.
## See also
- [buffer-alloc-unsafe](https://github.com/LinusU/buffer-alloc-unsafe) A ponyfill for `Buffer.allocUnsafe`
- [buffer-alloc](https://github.com/LinusU/buffer-alloc) A ponyfill for `Buffer.alloc`
- [buffer-from](https://github.com/LinusU/buffer-from) A ponyfill for `Buffer.from`

20
node_modules/debug/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,20 @@
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>
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.

481
node_modules/debug/README.md generated vendored Normal file
View File

@@ -0,0 +1,481 @@
# debug
[![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors)
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
A tiny JavaScript debugging utility modelled after Node.js core's debugging
technique. Works in Node.js and web browsers.
## Installation
```bash
$ npm install debug
```
## Usage
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
Example [_app.js_](./examples/node/app.js):
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %o', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example [_worker.js_](./examples/node/worker.js):
```js
var a = require('debug')('worker:a')
, b = require('debug')('worker:b');
function work() {
a('doing lots of uninteresting work');
setTimeout(work, Math.random() * 1000);
}
work();
function workb() {
b('doing some work');
setTimeout(workb, Math.random() * 2000);
}
workb();
```
The `DEBUG` environment variable is then used to enable these based on space or
comma-delimited names.
Here are some examples:
<img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png">
#### Windows command prompt notes
##### CMD
On Windows the environment variable is set using the `set` command.
```cmd
set DEBUG=*,-not_this
```
Example:
```cmd
set DEBUG=* & node app.js
```
##### PowerShell (VS Code default)
PowerShell uses different syntax to set environment variables.
```cmd
$env:DEBUG = "*,-not_this"
```
Example:
```cmd
$env:DEBUG='app';node app.js
```
Then, run the program to be debugged as usual.
npm script example:
```js
"windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",
```
## Namespace Colors
Every debug instance has a color generated for it based on its namespace name.
This helps when visually parsing the debug output to identify which debug instance
a debug line belongs to.
#### Node.js
In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
the [`supports-color`](https://npmjs.org/supports-color) module alongside debug,
otherwise debug will only use a small handful of basic colors.
<img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png">
#### Web Browser
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).
<img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png">
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below:
<img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png">
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output.
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has
debuggers named "connect:bodyParser", "connect:compress", "connect:session",
instead of listing all three with
`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do
`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character.
For example, `DEBUG=*,-connect:*` would include all debuggers except those
starting with "connect:".
## Environment Variables
When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:
| Name | Purpose |
|-----------|-------------------------------------------------|
| `DEBUG` | Enables/disables specific debugging namespaces. |
| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
__Note:__ The environment variables beginning with `DEBUG_` end up being
converted into an Options object that gets used with `%o`/`%O` formatters.
See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.
## Formatters
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting.
Below are the officially supported formatters:
| Formatter | Representation |
|-----------|----------------|
| `%O` | Pretty-print an Object on multiple lines. |
| `%o` | Pretty-print an Object all on a single line. |
| `%s` | String. |
| `%d` | Number (both integer and float). |
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%` | Single percent sign ('%'). This does not consume an argument. |
### Custom formatters
You can add custom formatters by extending the `debug.formatters` object.
For example, if you wanted to add support for rendering a Buffer as hex with
`%h`, you could do something like:
```js
const createDebug = require('debug')
createDebug.formatters.h = (v) => {
return v.toString('hex')
}
// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
```
## Browser Support
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
if you don't want to build it yourself.
Debug's enable state is currently persisted by `localStorage`.
Consider the situation shown below where you have `worker:a` and `worker:b`,
and wish to debug both. You can enable this using `localStorage.debug`:
```js
localStorage.debug = 'worker:*'
```
And then refresh the page.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
b('doing some work');
}, 1200);
```
In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_.
<img width="647" src="https://user-images.githubusercontent.com/7143133/152083257-29034707-c42c-4959-8add-3cee850e6fcf.png">
## Output streams
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
Example [_stdout.js_](./examples/node/stdout.js):
```js
var debug = require('debug');
var error = debug('app:error');
// by default stderr is used
error('goes to stderr!');
var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');
// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```
## Extend
You can simply extend debugger
```js
const log = require('debug')('auth');
//creates new debug instance with extended namespace
const logSign = log.extend('sign');
const logLogin = log.extend('login');
log('hello'); // auth hello
logSign('hello'); //auth:sign hello
logLogin('hello'); //auth:login hello
```
## Set dynamically
You can also enable debug dynamically by calling the `enable()` method :
```js
let debug = require('debug');
console.log(1, debug.enabled('test'));
debug.enable('test');
console.log(2, debug.enabled('test'));
debug.disable();
console.log(3, debug.enabled('test'));
```
print :
```
1 false
2 true
3 false
```
Usage :
`enable(namespaces)`
`namespaces` can include modes separated by a colon and wildcards.
Note that calling `enable()` completely overrides previously set DEBUG variable :
```
$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
=> false
```
`disable()`
Will disable all namespaces. The functions returns the namespaces currently
enabled (and skipped). This can be useful if you want to disable debugging
temporarily without knowing what was enabled to begin with.
For example:
```js
let debug = require('debug');
debug.enable('foo:*,-foo:bar');
let namespaces = debug.disable();
debug.enable(namespaces);
```
Note: There is no guarantee that the string will be identical to the initial
enable string, but semantically they will be identical.
## Checking whether a debug target is enabled
After you've created a debug instance, you can determine whether or not it is
enabled by checking the `enabled` property:
```javascript
const debug = require('debug')('http');
if (debug.enabled) {
// do stuff...
}
```
You can also manually toggle this property to force the debug instance to be
enabled or disabled.
## Usage in child processes
Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process.
For example:
```javascript
worker = fork(WORKER_WRAP_PATH, [workerPath], {
stdio: [
/* stdin: */ 0,
/* stdout: */ 'pipe',
/* stderr: */ 'pipe',
'ipc',
],
env: Object.assign({}, process.env, {
DEBUG_COLORS: 1 // without this settings, colors won't be shown
}),
});
worker.stderr.pipe(process.stderr, { end: false });
```
## Authors
- TJ Holowaychuk
- Nathan Rajlich
- Andrew Rhyne
- Josh Junon
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
## License
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
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.

64
node_modules/debug/package.json generated vendored Normal file
View File

@@ -0,0 +1,64 @@
{
"name": "debug",
"version": "4.4.3",
"repository": {
"type": "git",
"url": "git://github.com/debug-js/debug.git"
},
"description": "Lightweight debugging utility for Node.js and the browser",
"keywords": [
"debug",
"log",
"debugger"
],
"files": [
"src",
"LICENSE",
"README.md"
],
"author": "Josh Junon (https://github.com/qix-)",
"contributors": [
"TJ Holowaychuk <tj@vision-media.ca>",
"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)",
"Andrew Rhyne <rhyneandrew@gmail.com>"
],
"license": "MIT",
"scripts": {
"lint": "xo",
"test": "npm run test:node && npm run test:browser && npm run lint",
"test:node": "mocha test.js test.node.js",
"test:browser": "karma start --single-run",
"test:coverage": "cat ./coverage/lcov.info | coveralls"
},
"dependencies": {
"ms": "^2.1.3"
},
"devDependencies": {
"brfs": "^2.0.1",
"browserify": "^16.2.3",
"coveralls": "^3.0.2",
"karma": "^3.1.4",
"karma-browserify": "^6.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.3.0",
"mocha": "^5.2.0",
"mocha-lcov-reporter": "^1.2.0",
"sinon": "^14.0.0",
"xo": "^0.23.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
},
"main": "./src/index.js",
"browser": "./src/browser.js",
"engines": {
"node": ">=6.0"
},
"xo": {
"rules": {
"import/extensions": "off"
}
}
}

272
node_modules/debug/src/browser.js generated vendored Normal file
View File

@@ -0,0 +1,272 @@
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
};
})();
/**
* Colors.
*/
exports.colors = [
'#0000CC',
'#0000FF',
'#0033CC',
'#0033FF',
'#0066CC',
'#0066FF',
'#0099CC',
'#0099FF',
'#00CC00',
'#00CC33',
'#00CC66',
'#00CC99',
'#00CCCC',
'#00CCFF',
'#3300CC',
'#3300FF',
'#3333CC',
'#3333FF',
'#3366CC',
'#3366FF',
'#3399CC',
'#3399FF',
'#33CC00',
'#33CC33',
'#33CC66',
'#33CC99',
'#33CCCC',
'#33CCFF',
'#6600CC',
'#6600FF',
'#6633CC',
'#6633FF',
'#66CC00',
'#66CC33',
'#9900CC',
'#9900FF',
'#9933CC',
'#9933FF',
'#99CC00',
'#99CC33',
'#CC0000',
'#CC0033',
'#CC0066',
'#CC0099',
'#CC00CC',
'#CC00FF',
'#CC3300',
'#CC3333',
'#CC3366',
'#CC3399',
'#CC33CC',
'#CC33FF',
'#CC6600',
'#CC6633',
'#CC9900',
'#CC9933',
'#CCCC00',
'#CCCC33',
'#FF0000',
'#FF0033',
'#FF0066',
'#FF0099',
'#FF00CC',
'#FF00FF',
'#FF3300',
'#FF3333',
'#FF3366',
'#FF3399',
'#FF33CC',
'#FF33FF',
'#FF6600',
'#FF6633',
'#FF9900',
'#FF9933',
'#FFCC00',
'#FFCC33'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
let m;
// Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
// eslint-disable-next-line no-return-assign
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// Is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
// Double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') +
this.namespace +
(this.useColors ? ' %c' : ' ') +
args[0] +
(this.useColors ? '%c ' : ' ') +
'+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
exports.log = console.debug || console.log || (() => {});
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
let r;
try {
r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};

292
node_modules/debug/src/common.js generated vendored Normal file
View File

@@ -0,0 +1,292 @@
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
createDebug.destroy = destroy;
Object.keys(env).forEach(key => {
createDebug[key] = env[key];
});
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
// Disabled?
if (!debug.enabled) {
return;
}
const self = debug;
// Set `diff` timestamp
const curr = Number(new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return '%';
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
const val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
Object.defineProperty(debug, 'enabled', {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: v => {
enableOverride = v;
}
});
// Env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
const split = (typeof namespaces === 'string' ? namespaces : '')
.trim()
.replace(/\s+/g, ',')
.split(',')
.filter(Boolean);
for (const ns of split) {
if (ns[0] === '-') {
createDebug.skips.push(ns.slice(1));
} else {
createDebug.names.push(ns);
}
}
}
/**
* Checks if the given string matches a namespace template, honoring
* asterisks as wildcards.
*
* @param {String} search
* @param {String} template
* @return {Boolean}
*/
function matchesTemplate(search, template) {
let searchIndex = 0;
let templateIndex = 0;
let starIndex = -1;
let matchIndex = 0;
while (searchIndex < search.length) {
if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
// Match character or proceed with wildcard
if (template[templateIndex] === '*') {
starIndex = templateIndex;
matchIndex = searchIndex;
templateIndex++; // Skip the '*'
} else {
searchIndex++;
templateIndex++;
}
} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition
// Backtrack to the last '*' and try to match more characters
templateIndex = starIndex + 1;
matchIndex++;
searchIndex = matchIndex;
} else {
return false; // No match
}
}
// Handle trailing '*' in template
while (templateIndex < template.length && template[templateIndex] === '*') {
templateIndex++;
}
return templateIndex === template.length;
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [
...createDebug.names,
...createDebug.skips.map(namespace => '-' + namespace)
].join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
for (const skip of createDebug.skips) {
if (matchesTemplate(name, skip)) {
return false;
}
}
for (const ns of createDebug.names) {
if (matchesTemplate(name, ns)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;

10
node_modules/debug/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,10 @@
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}

263
node_modules/debug/src/node.js generated vendored Normal file
View File

@@ -0,0 +1,263 @@
/**
* Module dependencies.
*/
const tty = require('tty');
const util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util.deprecate(
() => {},
'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
);
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
try {
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
// eslint-disable-next-line import/no-extraneous-dependencies
const supportsColor = require('supports-color');
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {
// Swallow - we only care if `supports-color` is available; it doesn't have to be.
}
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(key => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
// Camel-case
const prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
// Coerce string value into JS value
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts ?
Boolean(exports.inspectOpts.colors) :
tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
const {namespace: name, useColors} = this;
if (useColors) {
const c = this.color;
const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return '';
}
return new Date().toISOString() + ' ';
}
/**
* Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.
*/
function log(...args) {
return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.split('\n')
.map(str => str.trim())
.join(' ');
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};

520
node_modules/dotenv/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,520 @@
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [Unreleased](https://github.com/motdotla/dotenv/compare/v16.6.1...master)
## [16.6.1](https://github.com/motdotla/dotenv/compare/v16.6.0...v16.6.1) (2025-06-27)
### Changed
- Default `quiet` to true hiding the runtime log message ([#874](https://github.com/motdotla/dotenv/pull/874))
- NOTICE: 17.0.0 will be released with quiet defaulting to false. Use `config({ quiet: true })` to suppress.
- And check out the new [dotenvx](https://github.com/dotenvx/dotenvx). As coding workflows evolve and agents increasingly handle secrets, encrypted .env files offer a much safer way to deploy both agents and code together with secure secrets. Simply switch `require('dotenv').config()` for `require('@dotenvx/dotenvx').config()`.
## [16.6.0](https://github.com/motdotla/dotenv/compare/v16.5.0...v16.6.0) (2025-06-26)
### Added
- Default log helpful message `[dotenv@16.6.0] injecting env (1) from .env` ([#870](https://github.com/motdotla/dotenv/pull/870))
- Use `{ quiet: true }` to suppress
- Aligns dotenv more closely with [dotenvx](https://github.com/dotenvx/dotenvx).
## [16.5.0](https://github.com/motdotla/dotenv/compare/v16.4.7...v16.5.0) (2025-04-07)
### Added
- 🎉 Added new sponsor [Graphite](https://graphite.dev/?utm_source=github&utm_medium=repo&utm_campaign=dotenv) - *the AI developer productivity platform helping teams on GitHub ship higher quality software, faster*.
> [!TIP]
> **[Become a sponsor](https://github.com/sponsors/motdotla)**
>
> The dotenvx README is viewed thousands of times DAILY on GitHub and NPM.
> Sponsoring dotenv is a great way to get in front of developers and give back to the developer community at the same time.
### Changed
- Remove `_log` method. Use `_debug` [#862](https://github.com/motdotla/dotenv/pull/862)
## [16.4.7](https://github.com/motdotla/dotenv/compare/v16.4.6...v16.4.7) (2024-12-03)
### Changed
- Ignore `.tap` folder when publishing. (oops, sorry about that everyone. - @motdotla) [#848](https://github.com/motdotla/dotenv/pull/848)
## [16.4.6](https://github.com/motdotla/dotenv/compare/v16.4.5...v16.4.6) (2024-12-02)
### Changed
- Clean up stale dev dependencies [#847](https://github.com/motdotla/dotenv/pull/847)
- Various README updates clarifying usage and alternative solutions using [dotenvx](https://github.com/dotenvx/dotenvx)
## [16.4.5](https://github.com/motdotla/dotenv/compare/v16.4.4...v16.4.5) (2024-02-19)
### Changed
- 🐞 Fix recent regression when using `path` option. return to historical behavior: do not attempt to auto find `.env` if `path` set. (regression was introduced in `16.4.3`) [#814](https://github.com/motdotla/dotenv/pull/814)
## [16.4.4](https://github.com/motdotla/dotenv/compare/v16.4.3...v16.4.4) (2024-02-13)
### Changed
- 🐞 Replaced chaining operator `?.` with old school `&&` (fixing node 12 failures) [#812](https://github.com/motdotla/dotenv/pull/812)
## [16.4.3](https://github.com/motdotla/dotenv/compare/v16.4.2...v16.4.3) (2024-02-12)
### Changed
- Fixed processing of multiple files in `options.path` [#805](https://github.com/motdotla/dotenv/pull/805)
## [16.4.2](https://github.com/motdotla/dotenv/compare/v16.4.1...v16.4.2) (2024-02-10)
### Changed
- Changed funding link in package.json to [`dotenvx.com`](https://dotenvx.com)
## [16.4.1](https://github.com/motdotla/dotenv/compare/v16.4.0...v16.4.1) (2024-01-24)
- Patch support for array as `path` option [#797](https://github.com/motdotla/dotenv/pull/797)
## [16.4.0](https://github.com/motdotla/dotenv/compare/v16.3.2...v16.4.0) (2024-01-23)
- Add `error.code` to error messages around `.env.vault` decryption handling [#795](https://github.com/motdotla/dotenv/pull/795)
- Add ability to find `.env.vault` file when filename(s) passed as an array [#784](https://github.com/motdotla/dotenv/pull/784)
## [16.3.2](https://github.com/motdotla/dotenv/compare/v16.3.1...v16.3.2) (2024-01-18)
### Added
- Add debug message when no encoding set [#735](https://github.com/motdotla/dotenv/pull/735)
### Changed
- Fix output typing for `populate` [#792](https://github.com/motdotla/dotenv/pull/792)
- Use subarray instead of slice [#793](https://github.com/motdotla/dotenv/pull/793)
## [16.3.1](https://github.com/motdotla/dotenv/compare/v16.3.0...v16.3.1) (2023-06-17)
### Added
- Add missing type definitions for `processEnv` and `DOTENV_KEY` options. [#756](https://github.com/motdotla/dotenv/pull/756)
## [16.3.0](https://github.com/motdotla/dotenv/compare/v16.2.0...v16.3.0) (2023-06-16)
### Added
- Optionally pass `DOTENV_KEY` to options rather than relying on `process.env.DOTENV_KEY`. Defaults to `process.env.DOTENV_KEY` [#754](https://github.com/motdotla/dotenv/pull/754)
## [16.2.0](https://github.com/motdotla/dotenv/compare/v16.1.4...v16.2.0) (2023-06-15)
### Added
- Optionally write to your own target object rather than `process.env`. Defaults to `process.env`. [#753](https://github.com/motdotla/dotenv/pull/753)
- Add import type URL to types file [#751](https://github.com/motdotla/dotenv/pull/751)
## [16.1.4](https://github.com/motdotla/dotenv/compare/v16.1.3...v16.1.4) (2023-06-04)
### Added
- Added `.github/` to `.npmignore` [#747](https://github.com/motdotla/dotenv/pull/747)
## [16.1.3](https://github.com/motdotla/dotenv/compare/v16.1.2...v16.1.3) (2023-05-31)
### Removed
- Removed `browser` keys for `path`, `os`, and `crypto` in package.json. These were set to false incorrectly as of 16.1. Instead, if using dotenv on the front-end make sure to include polyfills for `path`, `os`, and `crypto`. [node-polyfill-webpack-plugin](https://github.com/Richienb/node-polyfill-webpack-plugin) provides these.
## [16.1.2](https://github.com/motdotla/dotenv/compare/v16.1.1...v16.1.2) (2023-05-31)
### Changed
- Exposed private function `_configDotenv` as `configDotenv`. [#744](https://github.com/motdotla/dotenv/pull/744)
## [16.1.1](https://github.com/motdotla/dotenv/compare/v16.1.0...v16.1.1) (2023-05-30)
### Added
- Added type definition for `decrypt` function
### Changed
- Fixed `{crypto: false}` in `packageJson.browser`
## [16.1.0](https://github.com/motdotla/dotenv/compare/v16.0.3...v16.1.0) (2023-05-30)
### Added
- Add `populate` convenience method [#733](https://github.com/motdotla/dotenv/pull/733)
- Accept URL as path option [#720](https://github.com/motdotla/dotenv/pull/720)
- Add dotenv to `npm fund` command
- Spanish language README [#698](https://github.com/motdotla/dotenv/pull/698)
- Add `.env.vault` support. 🎉 ([#730](https://github.com/motdotla/dotenv/pull/730))
`.env.vault` extends the `.env` file format standard with a localized encrypted vault file. Package it securely with your production code deploys. It's cloud agnostic so that you can deploy your secrets anywhere  without [risky third-party integrations](https://techcrunch.com/2023/01/05/circleci-breach/). [read more](https://github.com/motdotla/dotenv#-deploying)
### Changed
- Fixed "cannot resolve 'fs'" error on tools like Replit [#693](https://github.com/motdotla/dotenv/pull/693)
## [16.0.3](https://github.com/motdotla/dotenv/compare/v16.0.2...v16.0.3) (2022-09-29)
### Changed
- Added library version to debug logs ([#682](https://github.com/motdotla/dotenv/pull/682))
## [16.0.2](https://github.com/motdotla/dotenv/compare/v16.0.1...v16.0.2) (2022-08-30)
### Added
- Export `env-options.js` and `cli-options.js` in package.json for use with downstream [dotenv-expand](https://github.com/motdotla/dotenv-expand) module
## [16.0.1](https://github.com/motdotla/dotenv/compare/v16.0.0...v16.0.1) (2022-05-10)
### Changed
- Minor README clarifications
- Development ONLY: updated devDependencies as recommended for development only security risks ([#658](https://github.com/motdotla/dotenv/pull/658))
## [16.0.0](https://github.com/motdotla/dotenv/compare/v15.0.1...v16.0.0) (2022-02-02)
### Added
- _Breaking:_ Backtick support 🎉 ([#615](https://github.com/motdotla/dotenv/pull/615))
If you had values containing the backtick character, please quote those values with either single or double quotes.
## [15.0.1](https://github.com/motdotla/dotenv/compare/v15.0.0...v15.0.1) (2022-02-02)
### Changed
- Properly parse empty single or double quoted values 🐞 ([#614](https://github.com/motdotla/dotenv/pull/614))
## [15.0.0](https://github.com/motdotla/dotenv/compare/v14.3.2...v15.0.0) (2022-01-31)
`v15.0.0` is a major new release with some important breaking changes.
### Added
- _Breaking:_ Multiline parsing support (just works. no need for the flag.)
### Changed
- _Breaking:_ `#` marks the beginning of a comment (UNLESS the value is wrapped in quotes. Please update your `.env` files to wrap in quotes any values containing `#`. For example: `SECRET_HASH="something-with-a-#-hash"`).
..Understandably, (as some teams have noted) this is tedious to do across the entire team. To make it less tedious, we recommend using [dotenv cli](https://github.com/dotenv-org/cli) going forward. It's an optional plugin that will keep your `.env` files in sync between machines, environments, or team members.
### Removed
- _Breaking:_ Remove multiline option (just works out of the box now. no need for the flag.)
## [14.3.2](https://github.com/motdotla/dotenv/compare/v14.3.1...v14.3.2) (2022-01-25)
### Changed
- Preserve backwards compatibility on values containing `#` 🐞 ([#603](https://github.com/motdotla/dotenv/pull/603))
## [14.3.1](https://github.com/motdotla/dotenv/compare/v14.3.0...v14.3.1) (2022-01-25)
### Changed
- Preserve backwards compatibility on exports by re-introducing the prior in-place exports 🐞 ([#606](https://github.com/motdotla/dotenv/pull/606))
## [14.3.0](https://github.com/motdotla/dotenv/compare/v14.2.0...v14.3.0) (2022-01-24)
### Added
- Add `multiline` option 🎉 ([#486](https://github.com/motdotla/dotenv/pull/486))
## [14.2.0](https://github.com/motdotla/dotenv/compare/v14.1.1...v14.2.0) (2022-01-17)
### Added
- Add `dotenv_config_override` cli option
- Add `DOTENV_CONFIG_OVERRIDE` command line env option
## [14.1.1](https://github.com/motdotla/dotenv/compare/v14.1.0...v14.1.1) (2022-01-17)
### Added
- Add React gotcha to FAQ on README
## [14.1.0](https://github.com/motdotla/dotenv/compare/v14.0.1...v14.1.0) (2022-01-17)
### Added
- Add `override` option 🎉 ([#595](https://github.com/motdotla/dotenv/pull/595))
## [14.0.1](https://github.com/motdotla/dotenv/compare/v14.0.0...v14.0.1) (2022-01-16)
### Added
- Log error on failure to load `.env` file ([#594](https://github.com/motdotla/dotenv/pull/594))
## [14.0.0](https://github.com/motdotla/dotenv/compare/v13.0.1...v14.0.0) (2022-01-16)
### Added
- _Breaking:_ Support inline comments for the parser 🎉 ([#568](https://github.com/motdotla/dotenv/pull/568))
## [13.0.1](https://github.com/motdotla/dotenv/compare/v13.0.0...v13.0.1) (2022-01-16)
### Changed
* Hide comments and newlines from debug output ([#404](https://github.com/motdotla/dotenv/pull/404))
## [13.0.0](https://github.com/motdotla/dotenv/compare/v12.0.4...v13.0.0) (2022-01-16)
### Added
* _Breaking:_ Add type file for `config.js` ([#539](https://github.com/motdotla/dotenv/pull/539))
## [12.0.4](https://github.com/motdotla/dotenv/compare/v12.0.3...v12.0.4) (2022-01-16)
### Changed
* README updates
* Minor order adjustment to package json format
## [12.0.3](https://github.com/motdotla/dotenv/compare/v12.0.2...v12.0.3) (2022-01-15)
### Changed
* Simplified jsdoc for consistency across editors
## [12.0.2](https://github.com/motdotla/dotenv/compare/v12.0.1...v12.0.2) (2022-01-15)
### Changed
* Improve embedded jsdoc type documentation
## [12.0.1](https://github.com/motdotla/dotenv/compare/v12.0.0...v12.0.1) (2022-01-15)
### Changed
* README updates and clarifications
## [12.0.0](https://github.com/motdotla/dotenv/compare/v11.0.0...v12.0.0) (2022-01-15)
### Removed
- _Breaking:_ drop support for Flow static type checker ([#584](https://github.com/motdotla/dotenv/pull/584))
### Changed
- Move types/index.d.ts to lib/main.d.ts ([#585](https://github.com/motdotla/dotenv/pull/585))
- Typescript cleanup ([#587](https://github.com/motdotla/dotenv/pull/587))
- Explicit typescript inclusion in package.json ([#566](https://github.com/motdotla/dotenv/pull/566))
## [11.0.0](https://github.com/motdotla/dotenv/compare/v10.0.0...v11.0.0) (2022-01-11)
### Changed
- _Breaking:_ drop support for Node v10 ([#558](https://github.com/motdotla/dotenv/pull/558))
- Patch debug option ([#550](https://github.com/motdotla/dotenv/pull/550))
## [10.0.0](https://github.com/motdotla/dotenv/compare/v9.0.2...v10.0.0) (2021-05-20)
### Added
- Add generic support to parse function
- Allow for import "dotenv/config.js"
- Add support to resolve home directory in path via ~
## [9.0.2](https://github.com/motdotla/dotenv/compare/v9.0.1...v9.0.2) (2021-05-10)
### Changed
- Support windows newlines with debug mode
## [9.0.1](https://github.com/motdotla/dotenv/compare/v9.0.0...v9.0.1) (2021-05-08)
### Changed
- Updates to README
## [9.0.0](https://github.com/motdotla/dotenv/compare/v8.6.0...v9.0.0) (2021-05-05)
### Changed
- _Breaking:_ drop support for Node v8
## [8.6.0](https://github.com/motdotla/dotenv/compare/v8.5.1...v8.6.0) (2021-05-05)
### Added
- define package.json in exports
## [8.5.1](https://github.com/motdotla/dotenv/compare/v8.5.0...v8.5.1) (2021-05-05)
### Changed
- updated dev dependencies via npm audit
## [8.5.0](https://github.com/motdotla/dotenv/compare/v8.4.0...v8.5.0) (2021-05-05)
### Added
- allow for `import "dotenv/config"`
## [8.4.0](https://github.com/motdotla/dotenv/compare/v8.3.0...v8.4.0) (2021-05-05)
### Changed
- point to exact types file to work with VS Code
## [8.3.0](https://github.com/motdotla/dotenv/compare/v8.2.0...v8.3.0) (2021-05-05)
### Changed
- _Breaking:_ drop support for Node v8 (mistake to be released as minor bump. later bumped to 9.0.0. see above.)
## [8.2.0](https://github.com/motdotla/dotenv/compare/v8.1.0...v8.2.0) (2019-10-16)
### Added
- TypeScript types
## [8.1.0](https://github.com/motdotla/dotenv/compare/v8.0.0...v8.1.0) (2019-08-18)
### Changed
- _Breaking:_ drop support for Node v6 ([#392](https://github.com/motdotla/dotenv/issues/392))
# [8.0.0](https://github.com/motdotla/dotenv/compare/v7.0.0...v8.0.0) (2019-05-02)
### Changed
- _Breaking:_ drop support for Node v6 ([#302](https://github.com/motdotla/dotenv/issues/392))
## [7.0.0] - 2019-03-12
### Fixed
- Fix removing unbalanced quotes ([#376](https://github.com/motdotla/dotenv/pull/376))
### Removed
- Removed `load` alias for `config` for consistency throughout code and documentation.
## [6.2.0] - 2018-12-03
### Added
- Support preload configuration via environment variables ([#351](https://github.com/motdotla/dotenv/issues/351))
## [6.1.0] - 2018-10-08
### Added
- `debug` option for `config` and `parse` methods will turn on logging
## [6.0.0] - 2018-06-02
### Changed
- _Breaking:_ drop support for Node v4 ([#304](https://github.com/motdotla/dotenv/pull/304))
## [5.0.0] - 2018-01-29
### Added
- Testing against Node v8 and v9
- Documentation on trim behavior of values
- Documentation on how to use with `import`
### Changed
- _Breaking_: default `path` is now `path.resolve(process.cwd(), '.env')`
- _Breaking_: does not write over keys already in `process.env` if the key has a falsy value
- using `const` and `let` instead of `var`
### Removed
- Testing against Node v7
## [4.0.0] - 2016-12-23
### Changed
- Return Object with parsed content or error instead of false ([#165](https://github.com/motdotla/dotenv/pull/165)).
### Removed
- `verbose` option removed in favor of returning result.
## [3.0.0] - 2016-12-20
### Added
- `verbose` option will log any error messages. Off by default.
- parses email addresses correctly
- allow importing config method directly in ES6
### Changed
- Suppress error messages by default ([#154](https://github.com/motdotla/dotenv/pull/154))
- Ignoring more files for NPM to make package download smaller
### Fixed
- False positive test due to case-sensitive variable ([#124](https://github.com/motdotla/dotenv/pull/124))
### Removed
- `silent` option removed in favor of `verbose`
## [2.0.0] - 2016-01-20
### Added
- CHANGELOG to ["make it easier for users and contributors to see precisely what notable changes have been made between each release"](http://keepachangelog.com/). Linked to from README
- LICENSE to be more explicit about what was defined in `package.json`. Linked to from README
- Testing nodejs v4 on travis-ci
- added examples of how to use dotenv in different ways
- return parsed object on success rather than boolean true
### Changed
- README has shorter description not referencing ruby gem since we don't have or want feature parity
### Removed
- Variable expansion and escaping so environment variables are encouraged to be fully orthogonal
## [1.2.0] - 2015-06-20
### Added
- Preload hook to require dotenv without including it in your code
### Changed
- clarified license to be "BSD-2-Clause" in `package.json`
### Fixed
- retain spaces in string vars
## [1.1.0] - 2015-03-31
### Added
- Silent option to silence `console.log` when `.env` missing
## [1.0.0] - 2015-03-13
### Removed
- support for multiple `.env` files. should always use one `.env` file for the current environment
[7.0.0]: https://github.com/motdotla/dotenv/compare/v6.2.0...v7.0.0
[6.2.0]: https://github.com/motdotla/dotenv/compare/v6.1.0...v6.2.0
[6.1.0]: https://github.com/motdotla/dotenv/compare/v6.0.0...v6.1.0
[6.0.0]: https://github.com/motdotla/dotenv/compare/v5.0.0...v6.0.0
[5.0.0]: https://github.com/motdotla/dotenv/compare/v4.0.0...v5.0.0
[4.0.0]: https://github.com/motdotla/dotenv/compare/v3.0.0...v4.0.0
[3.0.0]: https://github.com/motdotla/dotenv/compare/v2.0.0...v3.0.0
[2.0.0]: https://github.com/motdotla/dotenv/compare/v1.2.0...v2.0.0
[1.2.0]: https://github.com/motdotla/dotenv/compare/v1.1.0...v1.2.0
[1.1.0]: https://github.com/motdotla/dotenv/compare/v1.0.0...v1.1.0
[1.0.0]: https://github.com/motdotla/dotenv/compare/v0.4.0...v1.0.0

23
node_modules/dotenv/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,23 @@
Copyright (c) 2015, Scott Motte
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

411
node_modules/dotenv/README-es.md generated vendored Normal file
View File

@@ -0,0 +1,411 @@
<div align="center">
🎉 announcing <a href="https://github.com/dotenvx/dotenvx">dotenvx</a>. <em>run anywhere, multi-environment, encrypted envs</em>.
</div>
&nbsp;
<div align="center">
<p>
<sup>
<a href="https://github.com/sponsors/motdotla">Dotenv es apoyado por la comunidad.</a>
</sup>
</p>
<sup>Gracias espaciales a:</sup>
<br>
<br>
<a href="https://graphite.dev/?utm_source=github&utm_medium=repo&utm_campaign=dotenv"><img src="https://res.cloudinary.com/dotenv-org/image/upload/v1744035073/graphite_lgsrl8.gif" width="240" alt="Graphite" /></a>
<a href="https://graphite.dev/?utm_source=github&utm_medium=repo&utm_campaign=dotenv">
<b>Graphite is the AI developer productivity platform helping teams on GitHub ship higher quality software, faster.</b>
</a>
<hr>
</div>
# dotenv [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv)
<img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.svg" alt="dotenv" align="right" width="200" />
Dotenv es un módulo de dependencia cero que carga las variables de entorno desde un archivo `.env` en [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). El almacenamiento de la configuración del entorno separado del código está basado en la metodología [The Twelve-Factor App](http://12factor.net/config).
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard)
[![LICENSE](https://img.shields.io/github/license/motdotla/dotenv.svg)](LICENSE)
## Instalación
```bash
# instalación local (recomendado)
npm install dotenv --save
```
O installación con yarn? `yarn add dotenv`
## Uso
Cree un archivo `.env` en la raíz de su proyecto:
```dosini
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
```
Tan prónto como sea posible en su aplicación, importe y configure dotenv:
```javascript
require('dotenv').config()
console.log(process.env) // elimine esto después que haya confirmado que esta funcionando
```
.. o usa ES6?
```javascript
import * as dotenv from 'dotenv' // vea en https://github.com/motdotla/dotenv#como-uso-dotenv-con-import
// REVISAR LINK DE REFERENCIA DE IMPORTACIÓN
dotenv.config()
import express from 'express'
```
Eso es todo. `process.env` ahora tiene las claves y los valores que definiste en tu archivo `.env`:
```javascript
require('dotenv').config()
...
s3.getBucketCors({Bucket: process.env.S3_BUCKET}, function(err, data) {})
```
### Valores multilínea
Si necesita variables de varias líneas, por ejemplo, claves privadas, ahora se admiten en la versión (`>= v15.0.0`) con saltos de línea:
```dosini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
...
Kh9NV...
...
-----END RSA PRIVATE KEY-----"
```
Alternativamente, puede usar comillas dobles y usar el carácter `\n`:
```dosini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"
```
### Comentarios
Los comentarios pueden ser agregados en tu archivo o en la misma línea:
```dosini
# This is a comment
SECRET_KEY=YOURSECRETKEYGOESHERE # comment
SECRET_HASH="something-with-a-#-hash"
```
Los comentarios comienzan donde existe un `#`, entonces, si su valor contiene un `#`, enciérrelo entre comillas. Este es un cambio importante desde la versión `>= v15.0.0` en adelante.
### Análisis
El motor que analiza el contenido de su archivo que contiene variables de entorno está disponible para su uso. Este Acepta una Cadena o un Búfer y devolverá un Objeto con las claves y los valores analizados.
```javascript
const dotenv = require('dotenv')
const buf = Buffer.from('BASICO=basico')
const config = dotenv.parse(buf) // devolverá un objeto
console.log(typeof config, config) // objeto { BASICO : 'basico' }
```
### Precarga
Puede usar el `--require` (`-r`) [opción de línea de comando](https://nodejs.org/api/cli.html#-r---require-module) para precargar dotenv. Al hacer esto, no necesita requerir ni cargar dotnev en el código de su aplicación.
```bash
$ node -r dotenv/config tu_script.js
```
Las opciones de configuración a continuación se admiten como argumentos de línea de comandos en el formato `dotenv_config_<option>=value`
```bash
$ node -r dotenv/config tu_script.js dotenv_config_path=/custom/path/to/.env dotenv_config_debug=true
```
Además, puede usar variables de entorno para establecer opciones de configuración. Los argumentos de línea de comandos precederán a estos.
```bash
$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config tu_script.js
```
```bash
$ DOTENV_CONFIG_ENCODING=latin1 DOTENV_CONFIG_DEBUG=true node -r dotenv/config tu_script.js dotenv_config_path=/custom/path/to/.env
```
### Expansión Variable
Necesitaras agregar el valor de otro variable en una de sus variables? Usa [dotenv-expand](https://github.com/motdotla/dotenv-expand).
## Ejemplos
Vea [ejemplos](https://github.com/dotenv-org/examples) sobre el uso de dotenv con varios frameworks, lenguajes y configuraciones.
* [nodejs](https://github.com/dotenv-org/examples/tree/master/dotenv-nodejs)
* [nodejs (depurar en)](https://github.com/dotenv-org/examples/tree/master/dotenv-nodejs-debug)
* [nodejs (anular en)](https://github.com/dotenv-org/examples/tree/master/dotenv-nodejs-override)
* [esm](https://github.com/dotenv-org/examples/tree/master/dotenv-esm)
* [esm (precarga)](https://github.com/dotenv-org/examples/tree/master/dotenv-esm-preload)
* [typescript](https://github.com/dotenv-org/examples/tree/master/dotenv-typescript)
* [typescript parse](https://github.com/dotenv-org/examples/tree/master/dotenv-typescript-parse)
* [typescript config](https://github.com/dotenv-org/examples/tree/master/dotenv-typescript-config)
* [webpack](https://github.com/dotenv-org/examples/tree/master/dotenv-webpack)
* [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/dotenv-webpack2)
* [react](https://github.com/dotenv-org/examples/tree/master/dotenv-react)
* [react (typescript)](https://github.com/dotenv-org/examples/tree/master/dotenv-react-typescript)
* [express](https://github.com/dotenv-org/examples/tree/master/dotenv-express)
* [nestjs](https://github.com/dotenv-org/examples/tree/master/dotenv-nestjs)
## Documentación
Dotenv expone dos funciones:
* `configuración`
* `analizar`
### Configuración
`Configuración` leerá su archivo `.env`, analizará el contenido, lo asignará a [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
y devolverá un Objeto con una clave `parsed` que contiene el contenido cargado o una clave `error` si falla.
```js
const result = dotenv.config()
if (result.error) {
throw result.error
}
console.log(result.parsed)
```
Adicionalmente, puede pasar opciones a `configuracion`.
#### Opciones
##### Ruta
Por defecto: `path.resolve(process.cwd(), '.env')`
Especifique una ruta personalizada si el archivo que contiene las variables de entorno se encuentra localizado en otro lugar.
```js
require('dotenv').config({ path: '/personalizado/ruta/a/.env' })
```
##### Codificación
Por defecto: `utf8`
Especifique la codificación del archivo que contiene las variables de entorno.
```js
require('dotenv').config({ encoding: 'latin1' })
```
##### Depurar
Por defecto: `false`
Active el registro de ayuda para depurar por qué ciertas claves o valores no se inician como lo esperabas.
```js
require('dotenv').config({ debug: process.env.DEBUG })
```
##### Anular
Por defecto: `false`
Anule cualquier variable de entorno que ya se haya configurada en su maquina con los valores de su archivo .env.
```js
require('dotenv').config({ override: true })
```
### Analizar
El motor que analiza el contenido del archivo que contiene las variables de entorno está disponible para su uso. Acepta una Cadena o un Búfer y retornará un objecto con los valores analizados.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('BASICO=basico')
const config = dotenv.parse(buf) // devolverá un objeto
console.log(typeof config, config) // objeto { BASICO : 'basico' }
```
#### Opciones
##### Depurar
Por defecto: `false`
Active el registro de ayuda para depurar por qué ciertas claves o valores no se inician como lo esperabas.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('hola mundo')
const opt = { debug: true }
const config = dotenv.parse(buf, opt)
// espere por un mensaje de depuración porque el búfer no esta listo KEY=VAL
```
## FAQ
### ¿Por qué el archivo `.env` no carga mis variables de entorno correctamente?
Lo más probable es que su archivo `.env` no esté en el lugar correcto. [Vea este stack overflow](https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables).
Active el modo de depuración y vuelva a intentarlo...
```js
require('dotenv').config({ debug: true })
```
Recibirá un error apropiado en su consola.
### ¿Debo confirmar mi archivo `.env`?
No. Recomendamos **enfáticamente** no enviar su archivo `.env` a la versión de control. Solo debe incluir los valores especificos del entorno, como la base de datos, contraseñas o claves API.
### ¿Debería tener multiples archivos `.env`?
No. Recomendamos **enfáticamente** no tener un archivo `.env` "principal" y un archivo `.env` de "entorno" como `.env.test`. Su configuración debe variar entre implementaciones y no debe compartir valores entre entornos.
> En una Aplicación de Doce Factores, las variables de entorno son controles diferenciados, cada uno totalmente independiente a otras variables de entorno. Nunca se agrupan como "entornos", sino que se gestionan de manera independiente para cada despliegue. Este es un modelo que se escala sin problemas a medida que la aplicación se expande de forma natural en más despliegues a lo largo de su vida.
>
> [La Apliación de los Doce Factores](https://12factor.net/es/)
### ¿Qué reglas sigue el motor de análisis?
El motor de análisis actualmente admite las siguientes reglas:
- `BASICO=basico` se convierte en `{BASICO: 'basico'}`
- las líneas vacías se saltan
- las líneas que comienzan con `#` se tratan como comentarios
- `#` marca el comienzo de un comentario (a menos que el valor esté entre comillas)
- valores vacíos se convierten en cadenas vacías (`VACIO=` se convierte en `{VACIO: ''}`)
- las comillas internas se mantienen (piensa en JSON) (`JSON={"foo": "bar"}` se convierte en `{JSON:"{\"foo\": \"bar\"}"`)
- los espacios en blanco se eliminan de ambos extremos de los valores no citanos (aprende más en [`trim`](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO= algo ` se convierte en `{FOO: 'algo'}`)
- los valores entre comillas simples y dobles se escapan (`CITA_SIMPLE='citado'` se convierte en `{CITA_SIMPLE: "citado"}`)
- los valores entre comillas simples y dobles mantienen los espacios en blanco en ambos extremos (`FOO=" algo "` se convierte en `{FOO: ' algo '}`)
- los valores entre comillas dobles expanden nuevas líneas (`MULTILINEA="nueva\nlínea"` se convierte en
```
{MULTILINEA: 'nueva
línea'}
```
- se admite la comilla simple invertida (`` SIGNO_ACENTO=`Esto tiene comillas 'simples' y "dobles" en su interior.` ``)
### ¿Qué sucede con las variables de entorno que ya estaban configuradas?
Por defecto, nunca modificaremos ninguna variable de entorno que ya haya sido establecida. En particular, si hay una variable en su archivo `.env` que colisiona con una que ya existe en su entorno, entonces esa variable se omitirá.
Si por el contrario, quieres anular `process.env` utiliza la opción `override`.
```javascript
require('dotenv').config({ override: true })
```
### ¿Por qué mis variables de entorno no aparecen para React?
Su código React se ejecuta en Webpack, donde el módulo `fs` o incluso el propio `process` global no son accesibles fuera-de-la-caja. El módulo `process.env` sólo puede ser inyectado a través de la configuración de Webpack.
Si estás usando [`react-scripts`](https://www.npmjs.com/package/react-scripts), el cual se distribuye a través de [`create-react-app`](https://create-react-app.dev/), tiene dotenv incorporado pero con una singularidad. Escriba sus variables de entorno con `REACT_APP_`. Vea [este stack overflow](https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project) para más detalles.
Si estás utilizando otros frameworks (por ejemplo, Next.js, Gatsby...), debes consultar su documentación para saber cómo injectar variables de entorno en el cliente.
### ¿Puedo personalizar/escribir plugins para dotenv?
Sí! `dotenv.config()` devuelve un objeto que representa el archivo `.env` analizado. Esto te da todo lo que necesitas para poder establecer valores en `process.env`. Por ejemplo:
```js
const dotenv = require('dotenv')
const variableExpansion = require('dotenv-expand')
const miEnv = dotenv.config()
variableExpansion(miEnv)
```
### Cómo uso dotnev con `import`?
Simplemente..
```javascript
// index.mjs (ESM)
import * as dotenv from 'dotenv' // vea https://github.com/motdotla/dotenv#como-uso-dotenv-con-import
dotenv.config()
import express from 'express'
```
Un poco de historia...
> Cuando se ejecuta un módulo que contiene una sentencia `import`, los módulos que importa serán cargados primero, y luego se ejecuta cada bloque del módulo en un recorrido en profundidad del gráfico de dependencias, evitando los ciclos al saltarse todo lo que ya se ha ejecutado.
>
> [ES6 en Profundidad: Módulos](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
¿Qué significa esto en lenguaje sencillo? Significa que se podrías pensar que lo siguiente funcionaría pero no lo hará.
```js
// notificarError.mjs
import { Cliente } from 'mejor-servicio-para-notificar-error'
export default new Client(process.env.CLAVE_API)
// index.mjs
import dotenv from 'dotenv'
dotenv.config()
import notificarError from './notificarError.mjs'
notificarError.report(new Error('ejemplo documentado'))
```
`process.env.CLAVE_API` será vacio.
En su lugar, el código anterior debe ser escrito como...
```js
// notificarError.mjs
import { Cliente } from 'mejor-servicio-para-notificar-errores'
export default new Client(process.env.CLAVE_API)
// index.mjs
import * as dotenv from 'dotenv'
dotenv.config()
import notificarError from './notificarError.mjs'
notificarError.report(new Error('ejemplo documentado'))
```
¿Esto tiene algo de sentido? Esto es poco poco intuitivo, pero es como funciona la importación de módulos en ES6. Aquí hay un ejemplo [ejemplo práctico de esta trampa](https://github.com/dotenv-org/examples/tree/master/dotenv-es6-import-pitfall).
Existen dos arternativas a este planteamiento:
1. Precarga dotenv: `node --require dotenv/config index.js` (_Nota: no es necesario usar `import` dotenv con este método_)
2. Cree un archivo separado que ejecutará `config` primero como se describe en [este comentario #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822)
### ¿Qué pasa con la expansión de variable?
Prueba [dotenv-expand](https://github.com/motdotla/dotenv-expand)
## Guía de contribución
Vea [CONTRIBUTING.md](CONTRIBUTING.md)
## REGISTRO DE CAMBIOS
Vea [CHANGELOG.md](CHANGELOG.md)
## ¿Quiénes utilizan dotenv?
[Estos módulos npm dependen de él.](https://www.npmjs.com/browse/depended/dotenv)
Los proyectos que lo amplían suelen utilizar la [palabra clave "dotenv" en npm](https://www.npmjs.com/search?q=keywords:dotenv).

645
node_modules/dotenv/README.md generated vendored Normal file
View File

@@ -0,0 +1,645 @@
<div align="center">
🎉 announcing <a href="https://github.com/dotenvx/dotenvx">dotenvx</a>. <em>run anywhere, multi-environment, encrypted envs</em>.
</div>
&nbsp;
<div align="center">
**Special thanks to [our sponsors](https://github.com/sponsors/motdotla)**
<br>
<a href="https://graphite.dev/?utm_source=github&utm_medium=repo&utm_campaign=dotenv"><img src="https://res.cloudinary.com/dotenv-org/image/upload/v1744035073/graphite_lgsrl8.gif" width="240" alt="Graphite" /></a>
<br>
<a href="https://graphite.dev/?utm_source=github&utm_medium=repo&utm_campaign=dotenv">
<b>Graphite is the AI developer productivity platform helping teams on GitHub ship higher quality software, faster.</b>
</a>
<hr>
</div>
# dotenv [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv)
<img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.svg" alt="dotenv" align="right" width="200" />
Dotenv is a zero-dependency module that loads environment variables from a `.env` file into [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). Storing configuration in the environment separate from code is based on [The Twelve-Factor App](https://12factor.net/config) methodology.
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard)
[![LICENSE](https://img.shields.io/github/license/motdotla/dotenv.svg)](LICENSE)
[![codecov](https://codecov.io/gh/motdotla/dotenv-expand/graph/badge.svg?token=pawWEyaMfg)](https://codecov.io/gh/motdotla/dotenv-expand)
* [🌱 Install](#-install)
* [🏗️ Usage (.env)](#%EF%B8%8F-usage)
* [🌴 Multiple Environments 🆕](#-manage-multiple-environments)
* [🚀 Deploying (encryption) 🆕](#-deploying)
* [📚 Examples](#-examples)
* [📖 Docs](#-documentation)
* [❓ FAQ](#-faq)
* [⏱️ Changelog](./CHANGELOG.md)
## 🌱 Install
```bash
npm install dotenv --save
```
You can also use an npm-compatible package manager like yarn, bun or pnpm:
```bash
yarn add dotenv
```
```bash
bun add dotenv
```
```bash
pnpm add dotenv
```
## 🏗️ Usage
<a href="https://www.youtube.com/watch?v=YtkZR0NFd1g">
<div align="right">
<img src="https://img.youtube.com/vi/YtkZR0NFd1g/hqdefault.jpg" alt="how to use dotenv video tutorial" align="right" width="330" />
<img src="https://simpleicons.vercel.app/youtube/ff0000" alt="youtube/@dotenvorg" align="right" width="24" />
</div>
</a>
Create a `.env` file in the root of your project (if using a monorepo structure like `apps/backend/app.js`, put it in the root of the folder where your `app.js` process runs):
```dosini
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
```
As early as possible in your application, import and configure dotenv:
```javascript
require('dotenv').config()
console.log(process.env) // remove this after you've confirmed it is working
```
.. [or using ES6?](#how-do-i-use-dotenv-with-import)
```javascript
import 'dotenv/config'
```
That's it. `process.env` now has the keys and values you defined in your `.env` file:
```javascript
require('dotenv').config()
// or import 'dotenv/config' if you're using ES6
...
s3.getBucketCors({Bucket: process.env.S3_BUCKET}, function(err, data) {})
```
### Multiline values
If you need multiline variables, for example private keys, those are now supported (`>= v15.0.0`) with line breaks:
```dosini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
...
Kh9NV...
...
-----END RSA PRIVATE KEY-----"
```
Alternatively, you can double quote strings and use the `\n` character:
```dosini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"
```
### Comments
Comments may be added to your file on their own line or inline:
```dosini
# This is a comment
SECRET_KEY=YOURSECRETKEYGOESHERE # comment
SECRET_HASH="something-with-a-#-hash"
```
Comments begin where a `#` exists, so if your value contains a `#` please wrap it in quotes. This is a breaking change from `>= v15.0.0` and on.
### Parsing
The engine which parses the contents of your file containing environment variables is available to use. It accepts a String or Buffer and will return an Object with the parsed keys and values.
```javascript
const dotenv = require('dotenv')
const buf = Buffer.from('BASIC=basic')
const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }
```
### Preload
> Note: Consider using [`dotenvx`](https://github.com/dotenvx/dotenvx) instead of preloading. I am now doing (and recommending) so.
>
> It serves the same purpose (you do not need to require and load dotenv), adds better debugging, and works with ANY language, framework, or platform. [motdotla](https://github.com/motdotla)
You can use the `--require` (`-r`) [command line option](https://nodejs.org/api/cli.html#-r---require-module) to preload dotenv. By doing this, you do not need to require and load dotenv in your application code.
```bash
$ node -r dotenv/config your_script.js
```
The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value`
```bash
$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env dotenv_config_debug=true
```
Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.
```bash
$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
```
```bash
$ DOTENV_CONFIG_ENCODING=latin1 DOTENV_CONFIG_DEBUG=true node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
```
### Variable Expansion
You need to add the value of another variable in one of your variables? Use [dotenv-expand](https://github.com/motdotla/dotenv-expand).
### Command Substitution
Use [dotenvx](https://github.com/dotenvx/dotenvx) to use command substitution.
Add the output of a command to one of your variables in your .env file.
```ini
# .env
DATABASE_URL="postgres://$(whoami)@localhost/my_database"
```
```js
// index.js
console.log('DATABASE_URL', process.env.DATABASE_URL)
```
```sh
$ dotenvx run --debug -- node index.js
[dotenvx@0.14.1] injecting env (1) from .env
DATABASE_URL postgres://yourusername@localhost/my_database
```
### Syncing
You need to keep `.env` files in sync between machines, environments, or team members? Use [dotenvx](https://github.com/dotenvx/dotenvx) to encrypt your `.env` files and safely include them in source control. This still subscribes to the twelve-factor app rules by generating a decryption key separate from code.
### Multiple Environments
Use [dotenvx](https://github.com/dotenvx/dotenvx) to generate `.env.ci`, `.env.production` files, and more.
### Deploying
You need to deploy your secrets in a cloud-agnostic manner? Use [dotenvx](https://github.com/dotenvx/dotenvx) to generate a private decryption key that is set on your production server.
## 🌴 Manage Multiple Environments
Use [dotenvx](https://github.com/dotenvx/dotenvx)
Run any environment locally. Create a `.env.ENVIRONMENT` file and use `--env-file` to load it. It's straightforward, yet flexible.
```bash
$ echo "HELLO=production" > .env.production
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
$ dotenvx run --env-file=.env.production -- node index.js
Hello production
> ^^
```
or with multiple .env files
```bash
$ echo "HELLO=local" > .env.local
$ echo "HELLO=World" > .env
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
$ dotenvx run --env-file=.env.local --env-file=.env -- node index.js
Hello local
```
[more environment examples](https://dotenvx.com/docs/quickstart/environments)
## 🚀 Deploying
Use [dotenvx](https://github.com/dotenvx/dotenvx).
Add encryption to your `.env` files with a single command. Pass the `--encrypt` flag.
```
$ dotenvx set HELLO Production --encrypt -f .env.production
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
$ DOTENV_PRIVATE_KEY_PRODUCTION="<.env.production private key>" dotenvx run -- node index.js
[dotenvx] injecting env (2) from .env.production
Hello Production
```
[learn more](https://github.com/dotenvx/dotenvx?tab=readme-ov-file#encryption)
## 📚 Examples
See [examples](https://github.com/dotenv-org/examples) of using dotenv with various frameworks, languages, and configurations.
* [nodejs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs)
* [nodejs (debug on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-debug)
* [nodejs (override on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-override)
* [nodejs (processEnv override)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-custom-target)
* [esm](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm)
* [esm (preload)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm-preload)
* [typescript](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript)
* [typescript parse](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-parse)
* [typescript config](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-config)
* [webpack](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack)
* [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack2)
* [react](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react)
* [react (typescript)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react-typescript)
* [express](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-express)
* [nestjs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nestjs)
* [fastify](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-fastify)
## 📖 Documentation
Dotenv exposes four functions:
* `config`
* `parse`
* `populate`
* `decrypt`
### Config
`config` will read your `.env` file, parse the contents, assign it to
[`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
```js
const result = dotenv.config()
if (result.error) {
throw result.error
}
console.log(result.parsed)
```
You can additionally, pass options to `config`.
#### Options
##### path
Default: `path.resolve(process.cwd(), '.env')`
Specify a custom path if your file containing environment variables is located elsewhere.
```js
require('dotenv').config({ path: '/custom/path/to/.env' })
```
By default, `config` will look for a file called .env in the current working directory.
Pass in multiple files as an array, and they will be parsed in order and combined with `process.env` (or `option.processEnv`, if set). The first value set for a variable will win, unless the `options.override` flag is set, in which case the last value set will win. If a value already exists in `process.env` and the `options.override` flag is NOT set, no changes will be made to that value.
```js
require('dotenv').config({ path: ['.env.local', '.env'] })
```
##### encoding
Default: `utf8`
Specify the encoding of your file containing environment variables.
```js
require('dotenv').config({ encoding: 'latin1' })
```
##### debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being set as you expect.
```js
require('dotenv').config({ debug: process.env.DEBUG })
```
##### override
Default: `false`
Override any environment variables that have already been set on your machine with values from your .env file(s). If multiple files have been provided in `option.path` the override will also be used as each file is combined with the next. Without `override` being set, the first value wins. With `override` set the last value wins.
```js
require('dotenv').config({ override: true })
```
##### processEnv
Default: `process.env`
Specify an object to write your environment variables to. Defaults to `process.env` environment variables.
```js
const myObject = {}
require('dotenv').config({ processEnv: myObject })
console.log(myObject) // values from .env
console.log(process.env) // this was not changed or written to
```
### Parse
The engine which parses the contents of your file containing environment
variables is available to use. It accepts a String or Buffer and will return
an Object with the parsed keys and values.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('BASIC=basic')
const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }
```
#### Options
##### debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being set as you expect.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('hello world')
const opt = { debug: true }
const config = dotenv.parse(buf, opt)
// expect a debug message because the buffer is not in KEY=VAL form
```
### Populate
The engine which populates the contents of your .env file to `process.env` is available for use. It accepts a target, a source, and options. This is useful for power users who want to supply their own objects.
For example, customizing the source:
```js
const dotenv = require('dotenv')
const parsed = { HELLO: 'world' }
dotenv.populate(process.env, parsed)
console.log(process.env.HELLO) // world
```
For example, customizing the source AND target:
```js
const dotenv = require('dotenv')
const parsed = { HELLO: 'universe' }
const target = { HELLO: 'world' } // empty object
dotenv.populate(target, parsed, { override: true, debug: true })
console.log(target) // { HELLO: 'universe' }
```
#### options
##### Debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being populated as you expect.
##### override
Default: `false`
Override any environment variables that have already been set.
## ❓ FAQ
### Why is the `.env` file not loading my environment variables successfully?
Most likely your `.env` file is not in the correct place. [See this stack overflow](https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables).
Turn on debug mode and try again..
```js
require('dotenv').config({ debug: true })
```
You will receive a helpful error outputted to your console.
### Should I commit my `.env` file?
No. We **strongly** recommend against committing your `.env` file to version
control. It should only include environment-specific values such as database
passwords or API keys. Your production database should have a different
password than your development database.
### Should I have multiple `.env` files?
We recommend creating one `.env` file per environment. Use `.env` for local/development, `.env.production` for production and so on. This still follows the twelve factor principles as each is attributed individually to its own environment. Avoid custom set ups that work in inheritance somehow (`.env.production` inherits values form `.env` for example). It is better to duplicate values if necessary across each `.env.environment` file.
> In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as “environments”, but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime.
>
> [The Twelve-Factor App](http://12factor.net/config)
### What rules does the parsing engine follow?
The parsing engine currently supports the following rules:
- `BASIC=basic` becomes `{BASIC: 'basic'}`
- empty lines are skipped
- lines beginning with `#` are treated as comments
- `#` marks the beginning of a comment (unless when the value is wrapped in quotes)
- empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
- inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
- whitespace is removed from both ends of unquoted values (see more on [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO= some value ` becomes `{FOO: 'some value'}`)
- single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
- single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`)
- double quoted values expand new lines (`MULTILINE="new\nline"` becomes
```
{MULTILINE: 'new
line'}
```
- backticks are supported (`` BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.` ``)
### What happens to environment variables that were already set?
By default, we will never modify any environment variables that have already been set. In particular, if there is a variable in your `.env` file which collides with one that already exists in your environment, then that variable will be skipped.
If instead, you want to override `process.env` use the `override` option.
```javascript
require('dotenv').config({ override: true })
```
### How come my environment variables are not showing up for React?
Your React code is run in Webpack, where the `fs` module or even the `process` global itself are not accessible out-of-the-box. `process.env` can only be injected through Webpack configuration.
If you are using [`react-scripts`](https://www.npmjs.com/package/react-scripts), which is distributed through [`create-react-app`](https://create-react-app.dev/), it has dotenv built in but with a quirk. Preface your environment variables with `REACT_APP_`. See [this stack overflow](https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project) for more details.
If you are using other frameworks (e.g. Next.js, Gatsby...), you need to consult their documentation for how to inject environment variables into the client.
### Can I customize/write plugins for dotenv?
Yes! `dotenv.config()` returns an object representing the parsed `.env` file. This gives you everything you need to continue setting values on `process.env`. For example:
```js
const dotenv = require('dotenv')
const variableExpansion = require('dotenv-expand')
const myEnv = dotenv.config()
variableExpansion(myEnv)
```
### How do I use dotenv with `import`?
Simply..
```javascript
// index.mjs (ESM)
import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import express from 'express'
```
A little background..
> When you run a module containing an `import` declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.
>
> [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
What does this mean in plain language? It means you would think the following would work but it won't.
`errorReporter.mjs`:
```js
class Client {
constructor (apiKey) {
console.log('apiKey', apiKey)
this.apiKey = apiKey
}
}
export default new Client(process.env.API_KEY)
```
`index.mjs`:
```js
// Note: this is INCORRECT and will not work
import * as dotenv from 'dotenv'
dotenv.config()
import errorReporter from './errorReporter.mjs' // process.env.API_KEY will be blank!
```
`process.env.API_KEY` will be blank.
Instead, `index.mjs` should be written as..
```js
import 'dotenv/config'
import errorReporter from './errorReporter.mjs'
```
Does that make sense? It's a bit unintuitive, but it is how importing of ES6 modules work. Here is a [working example of this pitfall](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-es6-import-pitfall).
There are two alternatives to this approach:
1. Preload dotenv: `node --require dotenv/config index.js` (_Note: you do not need to `import` dotenv with this approach_)
2. Create a separate file that will execute `config` first as outlined in [this comment on #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822)
### Why am I getting the error `Module not found: Error: Can't resolve 'crypto|os|path'`?
You are using dotenv on the front-end and have not included a polyfill. Webpack < 5 used to include these for you. Do the following:
```bash
npm install node-polyfill-webpack-plugin
```
Configure your `webpack.config.js` to something like the following.
```js
require('dotenv').config()
const path = require('path');
const webpack = require('webpack')
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
module.exports = {
mode: 'development',
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new NodePolyfillPlugin(),
new webpack.DefinePlugin({
'process.env': {
HELLO: JSON.stringify(process.env.HELLO)
}
}),
]
};
```
Alternatively, just use [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack) which does this and more behind the scenes for you.
### What about variable expansion?
Try [dotenv-expand](https://github.com/motdotla/dotenv-expand)
### What about syncing and securing .env files?
Use [dotenvx](https://github.com/dotenvx/dotenvx)
### What if I accidentally commit my `.env` file to code?
Remove it, [remove git history](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository) and then install the [git pre-commit hook](https://github.com/dotenvx/dotenvx#pre-commit) to prevent this from ever happening again.
```
brew install dotenvx/brew/dotenvx
dotenvx precommit --install
```
### How can I prevent committing my `.env` file to a Docker build?
Use the [docker prebuild hook](https://dotenvx.com/docs/features/prebuild).
```bash
# Dockerfile
...
RUN curl -fsS https://dotenvx.sh/ | sh
...
RUN dotenvx prebuild
CMD ["dotenvx", "run", "--", "node", "index.js"]
```
## Contributing Guide
See [CONTRIBUTING.md](CONTRIBUTING.md)
## CHANGELOG
See [CHANGELOG.md](CHANGELOG.md)
## Who's using dotenv?
[These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv)
Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv).

1
node_modules/dotenv/SECURITY.md generated vendored Normal file
View File

@@ -0,0 +1 @@
Please report any security vulnerabilities to security@dotenvx.com.

1
node_modules/dotenv/config.d.ts generated vendored Normal file
View File

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

9
node_modules/dotenv/config.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
(function () {
require('./lib/main').config(
Object.assign(
{},
require('./lib/env-options'),
require('./lib/cli-options')(process.argv)
)
)
})()

17
node_modules/dotenv/lib/cli-options.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
const re = /^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/
module.exports = function optionMatcher (args) {
const options = args.reduce(function (acc, cur) {
const matches = cur.match(re)
if (matches) {
acc[matches[1]] = matches[2]
}
return acc
}, {})
if (!('quiet' in options)) {
options.quiet = 'true'
}
return options
}

28
node_modules/dotenv/lib/env-options.js generated vendored Normal file
View File

@@ -0,0 +1,28 @@
// ../config.js accepts options via environment variables
const options = {}
if (process.env.DOTENV_CONFIG_ENCODING != null) {
options.encoding = process.env.DOTENV_CONFIG_ENCODING
}
if (process.env.DOTENV_CONFIG_PATH != null) {
options.path = process.env.DOTENV_CONFIG_PATH
}
if (process.env.DOTENV_CONFIG_QUIET != null) {
options.quiet = process.env.DOTENV_CONFIG_QUIET
}
if (process.env.DOTENV_CONFIG_DEBUG != null) {
options.debug = process.env.DOTENV_CONFIG_DEBUG
}
if (process.env.DOTENV_CONFIG_OVERRIDE != null) {
options.override = process.env.DOTENV_CONFIG_OVERRIDE
}
if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) {
options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY
}
module.exports = options

162
node_modules/dotenv/lib/main.d.ts generated vendored Normal file
View File

@@ -0,0 +1,162 @@
// TypeScript Version: 3.0
/// <reference types="node" />
import type { URL } from 'url';
export interface DotenvParseOutput {
[name: string]: string;
}
/**
* Parses a string or buffer in the .env file format into an object.
*
* See https://dotenvx.com/docs
*
* @param src - contents to be parsed. example: `'DB_HOST=localhost'`
* @returns an object with keys and values based on `src`. example: `{ DB_HOST : 'localhost' }`
*/
export function parse<T extends DotenvParseOutput = DotenvParseOutput>(
src: string | Buffer
): T;
export interface DotenvConfigOptions {
/**
* Default: `path.resolve(process.cwd(), '.env')`
*
* Specify a custom path if your file containing environment variables is located elsewhere.
* Can also be an array of strings, specifying multiple paths.
*
* example: `require('dotenv').config({ path: '/custom/path/to/.env' })`
* example: `require('dotenv').config({ path: ['/path/to/first.env', '/path/to/second.env'] })`
*/
path?: string | string[] | URL;
/**
* Default: `utf8`
*
* Specify the encoding of your file containing environment variables.
*
* example: `require('dotenv').config({ encoding: 'latin1' })`
*/
encoding?: string;
/**
* Default: `false`
*
* Suppress all output (except errors).
*
* example: `require('dotenv').config({ quiet: true })`
*/
quiet?: boolean;
/**
* Default: `false`
*
* Turn on logging to help debug why certain keys or values are not being set as you expect.
*
* example: `require('dotenv').config({ debug: process.env.DEBUG })`
*/
debug?: boolean;
/**
* Default: `false`
*
* Override any environment variables that have already been set on your machine with values from your .env file.
*
* example: `require('dotenv').config({ override: true })`
*/
override?: boolean;
/**
* Default: `process.env`
*
* Specify an object to write your secrets to. Defaults to process.env environment variables.
*
* example: `const processEnv = {}; require('dotenv').config({ processEnv: processEnv })`
*/
processEnv?: DotenvPopulateInput;
/**
* Default: `undefined`
*
* Pass the DOTENV_KEY directly to config options. Defaults to looking for process.env.DOTENV_KEY environment variable. Note this only applies to decrypting .env.vault files. If passed as null or undefined, or not passed at all, dotenv falls back to its traditional job of parsing a .env file.
*
* example: `require('dotenv').config({ DOTENV_KEY: 'dotenv://:key_1234…@dotenvx.com/vault/.env.vault?environment=production' })`
*/
DOTENV_KEY?: string;
}
export interface DotenvConfigOutput {
error?: Error;
parsed?: DotenvParseOutput;
}
export interface DotenvPopulateOptions {
/**
* Default: `false`
*
* Turn on logging to help debug why certain keys or values are not being set as you expect.
*
* example: `require('dotenv').config({ debug: process.env.DEBUG })`
*/
debug?: boolean;
/**
* Default: `false`
*
* Override any environment variables that have already been set on your machine with values from your .env file.
*
* example: `require('dotenv').config({ override: true })`
*/
override?: boolean;
}
export interface DotenvPopulateInput {
[name: string]: string;
}
/**
* Loads `.env` file contents into process.env by default. If `DOTENV_KEY` is present, it smartly attempts to load encrypted `.env.vault` file contents into process.env.
*
* See https://dotenvx.com/docs
*
* @param options - additional options. example: `{ path: './custom/path', encoding: 'latin1', quiet: false, debug: true, override: false }`
* @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
*
*/
export function config(options?: DotenvConfigOptions): DotenvConfigOutput;
/**
* Loads `.env` file contents into process.env.
*
* See https://dotenvx.com/docs
*
* @param options - additional options. example: `{ path: './custom/path', encoding: 'latin1', quiet: false, debug: true, override: false }`
* @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
*
*/
export function configDotenv(options?: DotenvConfigOptions): DotenvConfigOutput;
/**
* Loads `source` json contents into `target` like process.env.
*
* See https://dotenvx.com/docs
*
* @param processEnv - the target JSON object. in most cases use process.env but you can also pass your own JSON object
* @param parsed - the source JSON object
* @param options - additional options. example: `{ quiet: false, debug: true, override: false }`
* @returns {void}
*
*/
export function populate(processEnv: DotenvPopulateInput, parsed: DotenvPopulateInput, options?: DotenvConfigOptions): void;
/**
* Decrypt ciphertext
*
* See https://dotenvx.com/docs
*
* @param encrypted - the encrypted ciphertext string
* @param keyStr - the decryption key string
* @returns {string}
*
*/
export function decrypt(encrypted: string, keyStr: string): string;

386
node_modules/dotenv/lib/main.js generated vendored Normal file
View File

@@ -0,0 +1,386 @@
const fs = require('fs')
const path = require('path')
const os = require('os')
const crypto = require('crypto')
const packageJson = require('../package.json')
const version = packageJson.version
const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg
// Parse src into an Object
function parse (src) {
const obj = {}
// Convert buffer to string
let lines = src.toString()
// Convert line breaks to same format
lines = lines.replace(/\r\n?/mg, '\n')
let match
while ((match = LINE.exec(lines)) != null) {
const key = match[1]
// Default undefined or null to empty string
let value = (match[2] || '')
// Remove whitespace
value = value.trim()
// Check if double quoted
const maybeQuote = value[0]
// Remove surrounding quotes
value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2')
// Expand newlines if double quoted
if (maybeQuote === '"') {
value = value.replace(/\\n/g, '\n')
value = value.replace(/\\r/g, '\r')
}
// Add to object
obj[key] = value
}
return obj
}
function _parseVault (options) {
options = options || {}
const vaultPath = _vaultPath(options)
options.path = vaultPath // parse .env.vault
const result = DotenvModule.configDotenv(options)
if (!result.parsed) {
const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)
err.code = 'MISSING_DATA'
throw err
}
// handle scenario for comma separated keys - for use with key rotation
// example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod"
const keys = _dotenvKey(options).split(',')
const length = keys.length
let decrypted
for (let i = 0; i < length; i++) {
try {
// Get full key
const key = keys[i].trim()
// Get instructions for decrypt
const attrs = _instructions(result, key)
// Decrypt
decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key)
break
} catch (error) {
// last key
if (i + 1 >= length) {
throw error
}
// try next key
}
}
// Parse decrypted .env string
return DotenvModule.parse(decrypted)
}
function _warn (message) {
console.log(`[dotenv@${version}][WARN] ${message}`)
}
function _debug (message) {
console.log(`[dotenv@${version}][DEBUG] ${message}`)
}
function _log (message) {
console.log(`[dotenv@${version}] ${message}`)
}
function _dotenvKey (options) {
// prioritize developer directly setting options.DOTENV_KEY
if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
return options.DOTENV_KEY
}
// secondary infra already contains a DOTENV_KEY environment variable
if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
return process.env.DOTENV_KEY
}
// fallback to empty string
return ''
}
function _instructions (result, dotenvKey) {
// Parse DOTENV_KEY. Format is a URI
let uri
try {
uri = new URL(dotenvKey)
} catch (error) {
if (error.code === 'ERR_INVALID_URL') {
const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development')
err.code = 'INVALID_DOTENV_KEY'
throw err
}
throw error
}
// Get decrypt key
const key = uri.password
if (!key) {
const err = new Error('INVALID_DOTENV_KEY: Missing key part')
err.code = 'INVALID_DOTENV_KEY'
throw err
}
// Get environment
const environment = uri.searchParams.get('environment')
if (!environment) {
const err = new Error('INVALID_DOTENV_KEY: Missing environment part')
err.code = 'INVALID_DOTENV_KEY'
throw err
}
// Get ciphertext payload
const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`
const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION
if (!ciphertext) {
const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)
err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'
throw err
}
return { ciphertext, key }
}
function _vaultPath (options) {
let possibleVaultPath = null
if (options && options.path && options.path.length > 0) {
if (Array.isArray(options.path)) {
for (const filepath of options.path) {
if (fs.existsSync(filepath)) {
possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`
}
}
} else {
possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`
}
} else {
possibleVaultPath = path.resolve(process.cwd(), '.env.vault')
}
if (fs.existsSync(possibleVaultPath)) {
return possibleVaultPath
}
return null
}
function _resolveHome (envPath) {
return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
}
function _configVault (options) {
const debug = Boolean(options && options.debug)
const quiet = options && 'quiet' in options ? options.quiet : true
if (debug || !quiet) {
_log('Loading env from encrypted .env.vault')
}
const parsed = DotenvModule._parseVault(options)
let processEnv = process.env
if (options && options.processEnv != null) {
processEnv = options.processEnv
}
DotenvModule.populate(processEnv, parsed, options)
return { parsed }
}
function configDotenv (options) {
const dotenvPath = path.resolve(process.cwd(), '.env')
let encoding = 'utf8'
const debug = Boolean(options && options.debug)
const quiet = options && 'quiet' in options ? options.quiet : true
if (options && options.encoding) {
encoding = options.encoding
} else {
if (debug) {
_debug('No encoding is specified. UTF-8 is used by default')
}
}
let optionPaths = [dotenvPath] // default, look for .env
if (options && options.path) {
if (!Array.isArray(options.path)) {
optionPaths = [_resolveHome(options.path)]
} else {
optionPaths = [] // reset default
for (const filepath of options.path) {
optionPaths.push(_resolveHome(filepath))
}
}
}
// Build the parsed data in a temporary object (because we need to return it). Once we have the final
// parsed data, we will combine it with process.env (or options.processEnv if provided).
let lastError
const parsedAll = {}
for (const path of optionPaths) {
try {
// Specifying an encoding returns a string instead of a buffer
const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }))
DotenvModule.populate(parsedAll, parsed, options)
} catch (e) {
if (debug) {
_debug(`Failed to load ${path} ${e.message}`)
}
lastError = e
}
}
let processEnv = process.env
if (options && options.processEnv != null) {
processEnv = options.processEnv
}
DotenvModule.populate(processEnv, parsedAll, options)
if (debug || !quiet) {
const keysCount = Object.keys(parsedAll).length
const shortPaths = []
for (const filePath of optionPaths) {
try {
const relative = path.relative(process.cwd(), filePath)
shortPaths.push(relative)
} catch (e) {
if (debug) {
_debug(`Failed to load ${filePath} ${e.message}`)
}
lastError = e
}
}
_log(`injecting env (${keysCount}) from ${shortPaths.join(',')}`)
}
if (lastError) {
return { parsed: parsedAll, error: lastError }
} else {
return { parsed: parsedAll }
}
}
// Populates process.env from .env file
function config (options) {
// fallback to original dotenv if DOTENV_KEY is not set
if (_dotenvKey(options).length === 0) {
return DotenvModule.configDotenv(options)
}
const vaultPath = _vaultPath(options)
// dotenvKey exists but .env.vault file does not exist
if (!vaultPath) {
_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`)
return DotenvModule.configDotenv(options)
}
return DotenvModule._configVault(options)
}
function decrypt (encrypted, keyStr) {
const key = Buffer.from(keyStr.slice(-64), 'hex')
let ciphertext = Buffer.from(encrypted, 'base64')
const nonce = ciphertext.subarray(0, 12)
const authTag = ciphertext.subarray(-16)
ciphertext = ciphertext.subarray(12, -16)
try {
const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce)
aesgcm.setAuthTag(authTag)
return `${aesgcm.update(ciphertext)}${aesgcm.final()}`
} catch (error) {
const isRange = error instanceof RangeError
const invalidKeyLength = error.message === 'Invalid key length'
const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'
if (isRange || invalidKeyLength) {
const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)')
err.code = 'INVALID_DOTENV_KEY'
throw err
} else if (decryptionFailed) {
const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY')
err.code = 'DECRYPTION_FAILED'
throw err
} else {
throw error
}
}
}
// Populate process.env with parsed values
function populate (processEnv, parsed, options = {}) {
const debug = Boolean(options && options.debug)
const override = Boolean(options && options.override)
if (typeof parsed !== 'object') {
const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')
err.code = 'OBJECT_REQUIRED'
throw err
}
// Set process.env
for (const key of Object.keys(parsed)) {
if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
if (override === true) {
processEnv[key] = parsed[key]
}
if (debug) {
if (override === true) {
_debug(`"${key}" is already defined and WAS overwritten`)
} else {
_debug(`"${key}" is already defined and was NOT overwritten`)
}
}
} else {
processEnv[key] = parsed[key]
}
}
}
const DotenvModule = {
configDotenv,
_configVault,
_parseVault,
config,
decrypt,
parse,
populate
}
module.exports.configDotenv = DotenvModule.configDotenv
module.exports._configVault = DotenvModule._configVault
module.exports._parseVault = DotenvModule._parseVault
module.exports.config = DotenvModule.config
module.exports.decrypt = DotenvModule.decrypt
module.exports.parse = DotenvModule.parse
module.exports.populate = DotenvModule.populate
module.exports = DotenvModule

62
node_modules/dotenv/package.json generated vendored Normal file
View File

@@ -0,0 +1,62 @@
{
"name": "dotenv",
"version": "16.6.1",
"description": "Loads environment variables from .env file",
"main": "lib/main.js",
"types": "lib/main.d.ts",
"exports": {
".": {
"types": "./lib/main.d.ts",
"require": "./lib/main.js",
"default": "./lib/main.js"
},
"./config": "./config.js",
"./config.js": "./config.js",
"./lib/env-options": "./lib/env-options.js",
"./lib/env-options.js": "./lib/env-options.js",
"./lib/cli-options": "./lib/cli-options.js",
"./lib/cli-options.js": "./lib/cli-options.js",
"./package.json": "./package.json"
},
"scripts": {
"dts-check": "tsc --project tests/types/tsconfig.json",
"lint": "standard",
"pretest": "npm run lint && npm run dts-check",
"test": "tap run --allow-empty-coverage --disable-coverage --timeout=60000",
"test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",
"prerelease": "npm test",
"release": "standard-version"
},
"repository": {
"type": "git",
"url": "git://github.com/motdotla/dotenv.git"
},
"homepage": "https://github.com/motdotla/dotenv#readme",
"funding": "https://dotenvx.com",
"keywords": [
"dotenv",
"env",
".env",
"environment",
"variables",
"config",
"settings"
],
"readmeFilename": "README.md",
"license": "BSD-2-Clause",
"devDependencies": {
"@types/node": "^18.11.3",
"decache": "^4.6.2",
"sinon": "^14.0.1",
"standard": "^17.0.0",
"standard-version": "^9.5.0",
"tap": "^19.2.0",
"typescript": "^4.8.4"
},
"engines": {
"node": ">=12"
},
"browser": {
"fs": false
}
}

22
node_modules/event-target-shim/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Toru Nagashima
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.

293
node_modules/event-target-shim/README.md generated vendored Normal file
View File

@@ -0,0 +1,293 @@
# event-target-shim
[![npm version](https://img.shields.io/npm/v/event-target-shim.svg)](https://www.npmjs.com/package/event-target-shim)
[![Downloads/month](https://img.shields.io/npm/dm/event-target-shim.svg)](http://www.npmtrends.com/event-target-shim)
[![Build Status](https://travis-ci.org/mysticatea/event-target-shim.svg?branch=master)](https://travis-ci.org/mysticatea/event-target-shim)
[![Coverage Status](https://codecov.io/gh/mysticatea/event-target-shim/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/event-target-shim)
[![Dependency Status](https://david-dm.org/mysticatea/event-target-shim.svg)](https://david-dm.org/mysticatea/event-target-shim)
An implementation of [WHATWG EventTarget interface](https://dom.spec.whatwg.org/#interface-eventtarget), plus few extensions.
- This provides `EventTarget` constructor that can inherit for your custom object.
- This provides an utility that defines properties of attribute listeners (e.g. `obj.onclick`).
```js
import {EventTarget, defineEventAttribute} from "event-target-shim"
class Foo extends EventTarget {
// ...
}
// Define `foo.onhello` property.
defineEventAttribute(Foo.prototype, "hello")
// Use
const foo = new Foo()
foo.addEventListener("hello", e => console.log("hello", e))
foo.onhello = e => console.log("onhello:", e)
foo.dispatchEvent(new CustomEvent("hello"))
```
## 💿 Installation
Use [npm](https://www.npmjs.com/) to install then use a bundler.
```
npm install event-target-shim
```
Or download from [`dist` directory](./dist).
- [dist/event-target-shim.mjs](dist/event-target-shim.mjs) ... ES modules version.
- [dist/event-target-shim.js](dist/event-target-shim.js) ... Common JS version.
- [dist/event-target-shim.umd.js](dist/event-target-shim.umd.js) ... UMD (Universal Module Definition) version. This is transpiled by [Babel](https://babeljs.io/) for IE 11.
## 📖 Usage
```js
import {EventTarget, defineEventAttribute} from "event-target-shim"
// or
const {EventTarget, defineEventAttribute} = require("event-target-shim")
// or UMD version defines a global variable:
const {EventTarget, defineEventAttribute} = window.EventTargetShim
```
### EventTarget
> https://dom.spec.whatwg.org/#interface-eventtarget
#### eventTarget.addEventListener(type, callback, options)
Register an event listener.
- `type` is a string. This is the event name to register.
- `callback` is a function. This is the event listener to register.
- `options` is a boolean or an object `{ capture?: boolean, passive?: boolean, once?: boolean }`. If this is a boolean, it's same meaning as `{ capture: options }`.
- `capture` is the flag to register the event listener for capture phase.
- `passive` is the flag to ignore `event.preventDefault()` method in the event listener.
- `once` is the flag to remove the event listener automatically after the first call.
#### eventTarget.removeEventListener(type, callback, options)
Unregister an event listener.
- `type` is a string. This is the event name to unregister.
- `callback` is a function. This is the event listener to unregister.
- `options` is a boolean or an object `{ capture?: boolean }`. If this is a boolean, it's same meaning as `{ capture: options }`.
- `capture` is the flag to register the event listener for capture phase.
#### eventTarget.dispatchEvent(event)
Dispatch an event.
- `event` is a [Event](https://dom.spec.whatwg.org/#event) object or an object `{ type: string, [key: string]: any }`. The latter is non-standard but useful. In both cases, listeners receive the event as implementing [Event](https://dom.spec.whatwg.org/#event) interface.
### defineEventAttribute(proto, type)
Define an event attribute (e.g. `onclick`) to `proto`. This is non-standard.
- `proto` is an object (assuming it's a prototype object). This function defines a getter/setter pair for the event attribute.
- `type` is a string. This is the event name to define.
For example:
```js
class AbortSignal extends EventTarget {
constructor() {
this.aborted = false
}
}
// Define `onabort` property.
defineEventAttribute(AbortSignal.prototype, "abort")
```
### EventTarget(types)
Define a custom `EventTarget` class with event attributes. This is non-standard.
- `types` is a string or an array of strings. This is the event name to define.
For example:
```js
// This has `onabort` property.
class AbortSignal extends EventTarget("abort") {
constructor() {
this.aborted = false
}
}
```
## 📚 Examples
### ES2015 and later
> https://jsfiddle.net/636vea92/
```js
const {EventTarget, defineEventAttribute} = EventTargetShim
// Define a derived class.
class Foo extends EventTarget {
// ...
}
// Define `foo.onhello` property.
defineEventAttribute(Foo.prototype, "hello")
// Register event listeners.
const foo = new Foo()
foo.addEventListener("hello", (e) => {
console.log("hello", e)
})
foo.onhello = (e) => {
console.log("onhello", e)
}
// Dispatching events
foo.dispatchEvent(new CustomEvent("hello", { detail: "detail" }))
```
### Typescript
```ts
import { EventTarget, defineEventAttribute } from "event-target-shim";
// Define events
type FooEvents = {
hello: CustomEvent
}
type FooEventAttributes = {
onhello: CustomEvent
}
// Define a derived class.
class Foo extends EventTarget<FooEvents, FooEventAttributes> {
// ...
}
// Define `foo.onhello` property's implementation.
defineEventAttribute(Foo.prototype, "hello")
// Register event listeners.
const foo = new Foo()
foo.addEventListener("hello", (e) => {
console.log("hello", e.detail)
})
foo.onhello = (e) => {
console.log("onhello", e.detail)
}
// Dispatching events
foo.dispatchEvent(new CustomEvent("hello", { detail: "detail" }))
```
Unfortunately, both `FooEvents` and `FooEventAttributes` are needed because TypeScript doesn't allow the mutation of string literal types. If TypeScript allowed us to compute `"onhello"` from `"hello"` in types, `FooEventAttributes` will be optional.
This `EventTarget` type is compatible with `EventTarget` interface of `lib.dom.d.ts`.
#### To disallow unknown events
By default, methods such as `addEventListener` accept unknown events. You can disallow unknown events by the third type parameter `"strict"`.
```ts
type FooEvents = {
hello: CustomEvent
}
class Foo extends EventTarget<FooEvents, {}, "strict"> {
// ...
}
// OK because `hello` is defined in FooEvents.
foo.addEventListener("hello", (e) => {
})
// Error because `unknown` is not defined in FooEvents.
foo.addEventListener("unknown", (e) => {
})
```
However, if you use `"strict"` parameter, it loses compatibility with `EventTarget` interface of `lib.dom.d.ts`.
#### To infer the type of `dispatchEvent()` method
TypeScript cannot infer the event type of `dispatchEvent()` method properly from the argument in most cases. You can improve this behavior with the following steps:
1. Use the third type parameter `"strict"`. This prevents inferring to `dispatchEvent<string>()`.
2. Make the `type` property of event definitions stricter.
```ts
type FooEvents = {
hello: CustomEvent & { type: "hello" }
hey: Event & { type: "hey" }
}
class Foo extends EventTarget<FooEvents, {}, "strict"> {
// ...
}
// Error because `detail` property is lacking.
foo.dispatchEvent({ type: "hello" })
```
### ES5
> https://jsfiddle.net/522zc9de/
```js
// Define a derived class.
function Foo() {
EventTarget.call(this)
}
Foo.prototype = Object.create(EventTarget.prototype, {
constructor: { value: Foo, configurable: true, writable: true }
// ...
})
// Define `foo.onhello` property.
defineEventAttribute(Foo.prototype, "hello")
// Register event listeners.
var foo = new Foo()
foo.addEventListener("hello", function(e) {
console.log("hello", e)
})
foo.onhello = function(e) {
console.log("onhello", e)
}
// Dispatching events
function isSupportEventConstrucor() { // IE does not support.
try {
new CusomEvent("hello")
return true
} catch (_err) {
return false
}
}
if (isSupportEventConstrucor()) {
foo.dispatchEvent(new CustomEvent("hello", { detail: "detail" }))
} else {
var e = document.createEvent("CustomEvent")
e.initCustomEvent("hello", false, false, "detail")
foo.dispatchEvent(e)
}
```
## 📰 Changelog
- See [GitHub releases](https://github.com/mysticatea/event-target-shim/releases).
## 🍻 Contributing
Contributing is welcome ❤️
Please use GitHub issues/PRs.
### Development tools
- `npm install` installs dependencies for development.
- `npm test` runs tests and measures code coverage.
- `npm run clean` removes temporary files of tests.
- `npm run coverage` opens code coverage of the previous test with your default browser.
- `npm run lint` runs ESLint.
- `npm run build` generates `dist` codes.
- `npm run watch` runs tests on each file change.

View File

@@ -0,0 +1,871 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* @copyright 2015 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/**
* @typedef {object} PrivateData
* @property {EventTarget} eventTarget The event target.
* @property {{type:string}} event The original event object.
* @property {number} eventPhase The current event phase.
* @property {EventTarget|null} currentTarget The current event target.
* @property {boolean} canceled The flag to prevent default.
* @property {boolean} stopped The flag to stop propagation.
* @property {boolean} immediateStopped The flag to stop propagation immediately.
* @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.
* @property {number} timeStamp The unix time.
* @private
*/
/**
* Private data for event wrappers.
* @type {WeakMap<Event, PrivateData>}
* @private
*/
const privateData = new WeakMap();
/**
* Cache for wrapper classes.
* @type {WeakMap<Object, Function>}
* @private
*/
const wrappers = new WeakMap();
/**
* Get private data.
* @param {Event} event The event object to get private data.
* @returns {PrivateData} The private data of the event.
* @private
*/
function pd(event) {
const retv = privateData.get(event);
console.assert(
retv != null,
"'this' is expected an Event object, but got",
event
);
return retv
}
/**
* https://dom.spec.whatwg.org/#set-the-canceled-flag
* @param data {PrivateData} private data.
*/
function setCancelFlag(data) {
if (data.passiveListener != null) {
if (
typeof console !== "undefined" &&
typeof console.error === "function"
) {
console.error(
"Unable to preventDefault inside passive event listener invocation.",
data.passiveListener
);
}
return
}
if (!data.event.cancelable) {
return
}
data.canceled = true;
if (typeof data.event.preventDefault === "function") {
data.event.preventDefault();
}
}
/**
* @see https://dom.spec.whatwg.org/#interface-event
* @private
*/
/**
* The event wrapper.
* @constructor
* @param {EventTarget} eventTarget The event target of this dispatching.
* @param {Event|{type:string}} event The original event to wrap.
*/
function Event(eventTarget, event) {
privateData.set(this, {
eventTarget,
event,
eventPhase: 2,
currentTarget: eventTarget,
canceled: false,
stopped: false,
immediateStopped: false,
passiveListener: null,
timeStamp: event.timeStamp || Date.now(),
});
// https://heycam.github.io/webidl/#Unforgeable
Object.defineProperty(this, "isTrusted", { value: false, enumerable: true });
// Define accessors
const keys = Object.keys(event);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
if (!(key in this)) {
Object.defineProperty(this, key, defineRedirectDescriptor(key));
}
}
}
// Should be enumerable, but class methods are not enumerable.
Event.prototype = {
/**
* The type of this event.
* @type {string}
*/
get type() {
return pd(this).event.type
},
/**
* The target of this event.
* @type {EventTarget}
*/
get target() {
return pd(this).eventTarget
},
/**
* The target of this event.
* @type {EventTarget}
*/
get currentTarget() {
return pd(this).currentTarget
},
/**
* @returns {EventTarget[]} The composed path of this event.
*/
composedPath() {
const currentTarget = pd(this).currentTarget;
if (currentTarget == null) {
return []
}
return [currentTarget]
},
/**
* Constant of NONE.
* @type {number}
*/
get NONE() {
return 0
},
/**
* Constant of CAPTURING_PHASE.
* @type {number}
*/
get CAPTURING_PHASE() {
return 1
},
/**
* Constant of AT_TARGET.
* @type {number}
*/
get AT_TARGET() {
return 2
},
/**
* Constant of BUBBLING_PHASE.
* @type {number}
*/
get BUBBLING_PHASE() {
return 3
},
/**
* The target of this event.
* @type {number}
*/
get eventPhase() {
return pd(this).eventPhase
},
/**
* Stop event bubbling.
* @returns {void}
*/
stopPropagation() {
const data = pd(this);
data.stopped = true;
if (typeof data.event.stopPropagation === "function") {
data.event.stopPropagation();
}
},
/**
* Stop event bubbling.
* @returns {void}
*/
stopImmediatePropagation() {
const data = pd(this);
data.stopped = true;
data.immediateStopped = true;
if (typeof data.event.stopImmediatePropagation === "function") {
data.event.stopImmediatePropagation();
}
},
/**
* The flag to be bubbling.
* @type {boolean}
*/
get bubbles() {
return Boolean(pd(this).event.bubbles)
},
/**
* The flag to be cancelable.
* @type {boolean}
*/
get cancelable() {
return Boolean(pd(this).event.cancelable)
},
/**
* Cancel this event.
* @returns {void}
*/
preventDefault() {
setCancelFlag(pd(this));
},
/**
* The flag to indicate cancellation state.
* @type {boolean}
*/
get defaultPrevented() {
return pd(this).canceled
},
/**
* The flag to be composed.
* @type {boolean}
*/
get composed() {
return Boolean(pd(this).event.composed)
},
/**
* The unix time of this event.
* @type {number}
*/
get timeStamp() {
return pd(this).timeStamp
},
/**
* The target of this event.
* @type {EventTarget}
* @deprecated
*/
get srcElement() {
return pd(this).eventTarget
},
/**
* The flag to stop event bubbling.
* @type {boolean}
* @deprecated
*/
get cancelBubble() {
return pd(this).stopped
},
set cancelBubble(value) {
if (!value) {
return
}
const data = pd(this);
data.stopped = true;
if (typeof data.event.cancelBubble === "boolean") {
data.event.cancelBubble = true;
}
},
/**
* The flag to indicate cancellation state.
* @type {boolean}
* @deprecated
*/
get returnValue() {
return !pd(this).canceled
},
set returnValue(value) {
if (!value) {
setCancelFlag(pd(this));
}
},
/**
* Initialize this event object. But do nothing under event dispatching.
* @param {string} type The event type.
* @param {boolean} [bubbles=false] The flag to be possible to bubble up.
* @param {boolean} [cancelable=false] The flag to be possible to cancel.
* @deprecated
*/
initEvent() {
// Do nothing.
},
};
// `constructor` is not enumerable.
Object.defineProperty(Event.prototype, "constructor", {
value: Event,
configurable: true,
writable: true,
});
// Ensure `event instanceof window.Event` is `true`.
if (typeof window !== "undefined" && typeof window.Event !== "undefined") {
Object.setPrototypeOf(Event.prototype, window.Event.prototype);
// Make association for wrappers.
wrappers.set(window.Event.prototype, Event);
}
/**
* Get the property descriptor to redirect a given property.
* @param {string} key Property name to define property descriptor.
* @returns {PropertyDescriptor} The property descriptor to redirect the property.
* @private
*/
function defineRedirectDescriptor(key) {
return {
get() {
return pd(this).event[key]
},
set(value) {
pd(this).event[key] = value;
},
configurable: true,
enumerable: true,
}
}
/**
* Get the property descriptor to call a given method property.
* @param {string} key Property name to define property descriptor.
* @returns {PropertyDescriptor} The property descriptor to call the method property.
* @private
*/
function defineCallDescriptor(key) {
return {
value() {
const event = pd(this).event;
return event[key].apply(event, arguments)
},
configurable: true,
enumerable: true,
}
}
/**
* Define new wrapper class.
* @param {Function} BaseEvent The base wrapper class.
* @param {Object} proto The prototype of the original event.
* @returns {Function} The defined wrapper class.
* @private
*/
function defineWrapper(BaseEvent, proto) {
const keys = Object.keys(proto);
if (keys.length === 0) {
return BaseEvent
}
/** CustomEvent */
function CustomEvent(eventTarget, event) {
BaseEvent.call(this, eventTarget, event);
}
CustomEvent.prototype = Object.create(BaseEvent.prototype, {
constructor: { value: CustomEvent, configurable: true, writable: true },
});
// Define accessors.
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
if (!(key in BaseEvent.prototype)) {
const descriptor = Object.getOwnPropertyDescriptor(proto, key);
const isFunc = typeof descriptor.value === "function";
Object.defineProperty(
CustomEvent.prototype,
key,
isFunc
? defineCallDescriptor(key)
: defineRedirectDescriptor(key)
);
}
}
return CustomEvent
}
/**
* Get the wrapper class of a given prototype.
* @param {Object} proto The prototype of the original event to get its wrapper.
* @returns {Function} The wrapper class.
* @private
*/
function getWrapper(proto) {
if (proto == null || proto === Object.prototype) {
return Event
}
let wrapper = wrappers.get(proto);
if (wrapper == null) {
wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);
wrappers.set(proto, wrapper);
}
return wrapper
}
/**
* Wrap a given event to management a dispatching.
* @param {EventTarget} eventTarget The event target of this dispatching.
* @param {Object} event The event to wrap.
* @returns {Event} The wrapper instance.
* @private
*/
function wrapEvent(eventTarget, event) {
const Wrapper = getWrapper(Object.getPrototypeOf(event));
return new Wrapper(eventTarget, event)
}
/**
* Get the immediateStopped flag of a given event.
* @param {Event} event The event to get.
* @returns {boolean} The flag to stop propagation immediately.
* @private
*/
function isStopped(event) {
return pd(event).immediateStopped
}
/**
* Set the current event phase of a given event.
* @param {Event} event The event to set current target.
* @param {number} eventPhase New event phase.
* @returns {void}
* @private
*/
function setEventPhase(event, eventPhase) {
pd(event).eventPhase = eventPhase;
}
/**
* Set the current target of a given event.
* @param {Event} event The event to set current target.
* @param {EventTarget|null} currentTarget New current target.
* @returns {void}
* @private
*/
function setCurrentTarget(event, currentTarget) {
pd(event).currentTarget = currentTarget;
}
/**
* Set a passive listener of a given event.
* @param {Event} event The event to set current target.
* @param {Function|null} passiveListener New passive listener.
* @returns {void}
* @private
*/
function setPassiveListener(event, passiveListener) {
pd(event).passiveListener = passiveListener;
}
/**
* @typedef {object} ListenerNode
* @property {Function} listener
* @property {1|2|3} listenerType
* @property {boolean} passive
* @property {boolean} once
* @property {ListenerNode|null} next
* @private
*/
/**
* @type {WeakMap<object, Map<string, ListenerNode>>}
* @private
*/
const listenersMap = new WeakMap();
// Listener types
const CAPTURE = 1;
const BUBBLE = 2;
const ATTRIBUTE = 3;
/**
* Check whether a given value is an object or not.
* @param {any} x The value to check.
* @returns {boolean} `true` if the value is an object.
*/
function isObject(x) {
return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax
}
/**
* Get listeners.
* @param {EventTarget} eventTarget The event target to get.
* @returns {Map<string, ListenerNode>} The listeners.
* @private
*/
function getListeners(eventTarget) {
const listeners = listenersMap.get(eventTarget);
if (listeners == null) {
throw new TypeError(
"'this' is expected an EventTarget object, but got another value."
)
}
return listeners
}
/**
* Get the property descriptor for the event attribute of a given event.
* @param {string} eventName The event name to get property descriptor.
* @returns {PropertyDescriptor} The property descriptor.
* @private
*/
function defineEventAttributeDescriptor(eventName) {
return {
get() {
const listeners = getListeners(this);
let node = listeners.get(eventName);
while (node != null) {
if (node.listenerType === ATTRIBUTE) {
return node.listener
}
node = node.next;
}
return null
},
set(listener) {
if (typeof listener !== "function" && !isObject(listener)) {
listener = null; // eslint-disable-line no-param-reassign
}
const listeners = getListeners(this);
// Traverse to the tail while removing old value.
let prev = null;
let node = listeners.get(eventName);
while (node != null) {
if (node.listenerType === ATTRIBUTE) {
// Remove old value.
if (prev !== null) {
prev.next = node.next;
} else if (node.next !== null) {
listeners.set(eventName, node.next);
} else {
listeners.delete(eventName);
}
} else {
prev = node;
}
node = node.next;
}
// Add new value.
if (listener !== null) {
const newNode = {
listener,
listenerType: ATTRIBUTE,
passive: false,
once: false,
next: null,
};
if (prev === null) {
listeners.set(eventName, newNode);
} else {
prev.next = newNode;
}
}
},
configurable: true,
enumerable: true,
}
}
/**
* Define an event attribute (e.g. `eventTarget.onclick`).
* @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.
* @param {string} eventName The event name to define.
* @returns {void}
*/
function defineEventAttribute(eventTargetPrototype, eventName) {
Object.defineProperty(
eventTargetPrototype,
`on${eventName}`,
defineEventAttributeDescriptor(eventName)
);
}
/**
* Define a custom EventTarget with event attributes.
* @param {string[]} eventNames Event names for event attributes.
* @returns {EventTarget} The custom EventTarget.
* @private
*/
function defineCustomEventTarget(eventNames) {
/** CustomEventTarget */
function CustomEventTarget() {
EventTarget.call(this);
}
CustomEventTarget.prototype = Object.create(EventTarget.prototype, {
constructor: {
value: CustomEventTarget,
configurable: true,
writable: true,
},
});
for (let i = 0; i < eventNames.length; ++i) {
defineEventAttribute(CustomEventTarget.prototype, eventNames[i]);
}
return CustomEventTarget
}
/**
* EventTarget.
*
* - This is constructor if no arguments.
* - This is a function which returns a CustomEventTarget constructor if there are arguments.
*
* For example:
*
* class A extends EventTarget {}
* class B extends EventTarget("message") {}
* class C extends EventTarget("message", "error") {}
* class D extends EventTarget(["message", "error"]) {}
*/
function EventTarget() {
/*eslint-disable consistent-return */
if (this instanceof EventTarget) {
listenersMap.set(this, new Map());
return
}
if (arguments.length === 1 && Array.isArray(arguments[0])) {
return defineCustomEventTarget(arguments[0])
}
if (arguments.length > 0) {
const types = new Array(arguments.length);
for (let i = 0; i < arguments.length; ++i) {
types[i] = arguments[i];
}
return defineCustomEventTarget(types)
}
throw new TypeError("Cannot call a class as a function")
/*eslint-enable consistent-return */
}
// Should be enumerable, but class methods are not enumerable.
EventTarget.prototype = {
/**
* Add a given listener to this event target.
* @param {string} eventName The event name to add.
* @param {Function} listener The listener to add.
* @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
* @returns {void}
*/
addEventListener(eventName, listener, options) {
if (listener == null) {
return
}
if (typeof listener !== "function" && !isObject(listener)) {
throw new TypeError("'listener' should be a function or an object.")
}
const listeners = getListeners(this);
const optionsIsObj = isObject(options);
const capture = optionsIsObj
? Boolean(options.capture)
: Boolean(options);
const listenerType = capture ? CAPTURE : BUBBLE;
const newNode = {
listener,
listenerType,
passive: optionsIsObj && Boolean(options.passive),
once: optionsIsObj && Boolean(options.once),
next: null,
};
// Set it as the first node if the first node is null.
let node = listeners.get(eventName);
if (node === undefined) {
listeners.set(eventName, newNode);
return
}
// Traverse to the tail while checking duplication..
let prev = null;
while (node != null) {
if (
node.listener === listener &&
node.listenerType === listenerType
) {
// Should ignore duplication.
return
}
prev = node;
node = node.next;
}
// Add it.
prev.next = newNode;
},
/**
* Remove a given listener from this event target.
* @param {string} eventName The event name to remove.
* @param {Function} listener The listener to remove.
* @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
* @returns {void}
*/
removeEventListener(eventName, listener, options) {
if (listener == null) {
return
}
const listeners = getListeners(this);
const capture = isObject(options)
? Boolean(options.capture)
: Boolean(options);
const listenerType = capture ? CAPTURE : BUBBLE;
let prev = null;
let node = listeners.get(eventName);
while (node != null) {
if (
node.listener === listener &&
node.listenerType === listenerType
) {
if (prev !== null) {
prev.next = node.next;
} else if (node.next !== null) {
listeners.set(eventName, node.next);
} else {
listeners.delete(eventName);
}
return
}
prev = node;
node = node.next;
}
},
/**
* Dispatch a given event.
* @param {Event|{type:string}} event The event to dispatch.
* @returns {boolean} `false` if canceled.
*/
dispatchEvent(event) {
if (event == null || typeof event.type !== "string") {
throw new TypeError('"event.type" should be a string.')
}
// If listeners aren't registered, terminate.
const listeners = getListeners(this);
const eventName = event.type;
let node = listeners.get(eventName);
if (node == null) {
return true
}
// Since we cannot rewrite several properties, so wrap object.
const wrappedEvent = wrapEvent(this, event);
// This doesn't process capturing phase and bubbling phase.
// This isn't participating in a tree.
let prev = null;
while (node != null) {
// Remove this listener if it's once
if (node.once) {
if (prev !== null) {
prev.next = node.next;
} else if (node.next !== null) {
listeners.set(eventName, node.next);
} else {
listeners.delete(eventName);
}
} else {
prev = node;
}
// Call this listener
setPassiveListener(
wrappedEvent,
node.passive ? node.listener : null
);
if (typeof node.listener === "function") {
try {
node.listener.call(this, wrappedEvent);
} catch (err) {
if (
typeof console !== "undefined" &&
typeof console.error === "function"
) {
console.error(err);
}
}
} else if (
node.listenerType !== ATTRIBUTE &&
typeof node.listener.handleEvent === "function"
) {
node.listener.handleEvent(wrappedEvent);
}
// Break if `event.stopImmediatePropagation` was called.
if (isStopped(wrappedEvent)) {
break
}
node = node.next;
}
setPassiveListener(wrappedEvent, null);
setEventPhase(wrappedEvent, 0);
setCurrentTarget(wrappedEvent, null);
return !wrappedEvent.defaultPrevented
},
};
// `constructor` is not enumerable.
Object.defineProperty(EventTarget.prototype, "constructor", {
value: EventTarget,
configurable: true,
writable: true,
});
// Ensure `eventTarget instanceof window.EventTarget` is `true`.
if (
typeof window !== "undefined" &&
typeof window.EventTarget !== "undefined"
) {
Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);
}
exports.defineEventAttribute = defineEventAttribute;
exports.EventTarget = EventTarget;
exports.default = EventTarget;
module.exports = EventTarget
module.exports.EventTarget = module.exports["default"] = EventTarget
module.exports.defineEventAttribute = defineEventAttribute
//# sourceMappingURL=event-target-shim.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,862 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* @copyright 2015 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
/**
* @typedef {object} PrivateData
* @property {EventTarget} eventTarget The event target.
* @property {{type:string}} event The original event object.
* @property {number} eventPhase The current event phase.
* @property {EventTarget|null} currentTarget The current event target.
* @property {boolean} canceled The flag to prevent default.
* @property {boolean} stopped The flag to stop propagation.
* @property {boolean} immediateStopped The flag to stop propagation immediately.
* @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.
* @property {number} timeStamp The unix time.
* @private
*/
/**
* Private data for event wrappers.
* @type {WeakMap<Event, PrivateData>}
* @private
*/
const privateData = new WeakMap();
/**
* Cache for wrapper classes.
* @type {WeakMap<Object, Function>}
* @private
*/
const wrappers = new WeakMap();
/**
* Get private data.
* @param {Event} event The event object to get private data.
* @returns {PrivateData} The private data of the event.
* @private
*/
function pd(event) {
const retv = privateData.get(event);
console.assert(
retv != null,
"'this' is expected an Event object, but got",
event
);
return retv
}
/**
* https://dom.spec.whatwg.org/#set-the-canceled-flag
* @param data {PrivateData} private data.
*/
function setCancelFlag(data) {
if (data.passiveListener != null) {
if (
typeof console !== "undefined" &&
typeof console.error === "function"
) {
console.error(
"Unable to preventDefault inside passive event listener invocation.",
data.passiveListener
);
}
return
}
if (!data.event.cancelable) {
return
}
data.canceled = true;
if (typeof data.event.preventDefault === "function") {
data.event.preventDefault();
}
}
/**
* @see https://dom.spec.whatwg.org/#interface-event
* @private
*/
/**
* The event wrapper.
* @constructor
* @param {EventTarget} eventTarget The event target of this dispatching.
* @param {Event|{type:string}} event The original event to wrap.
*/
function Event(eventTarget, event) {
privateData.set(this, {
eventTarget,
event,
eventPhase: 2,
currentTarget: eventTarget,
canceled: false,
stopped: false,
immediateStopped: false,
passiveListener: null,
timeStamp: event.timeStamp || Date.now(),
});
// https://heycam.github.io/webidl/#Unforgeable
Object.defineProperty(this, "isTrusted", { value: false, enumerable: true });
// Define accessors
const keys = Object.keys(event);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
if (!(key in this)) {
Object.defineProperty(this, key, defineRedirectDescriptor(key));
}
}
}
// Should be enumerable, but class methods are not enumerable.
Event.prototype = {
/**
* The type of this event.
* @type {string}
*/
get type() {
return pd(this).event.type
},
/**
* The target of this event.
* @type {EventTarget}
*/
get target() {
return pd(this).eventTarget
},
/**
* The target of this event.
* @type {EventTarget}
*/
get currentTarget() {
return pd(this).currentTarget
},
/**
* @returns {EventTarget[]} The composed path of this event.
*/
composedPath() {
const currentTarget = pd(this).currentTarget;
if (currentTarget == null) {
return []
}
return [currentTarget]
},
/**
* Constant of NONE.
* @type {number}
*/
get NONE() {
return 0
},
/**
* Constant of CAPTURING_PHASE.
* @type {number}
*/
get CAPTURING_PHASE() {
return 1
},
/**
* Constant of AT_TARGET.
* @type {number}
*/
get AT_TARGET() {
return 2
},
/**
* Constant of BUBBLING_PHASE.
* @type {number}
*/
get BUBBLING_PHASE() {
return 3
},
/**
* The target of this event.
* @type {number}
*/
get eventPhase() {
return pd(this).eventPhase
},
/**
* Stop event bubbling.
* @returns {void}
*/
stopPropagation() {
const data = pd(this);
data.stopped = true;
if (typeof data.event.stopPropagation === "function") {
data.event.stopPropagation();
}
},
/**
* Stop event bubbling.
* @returns {void}
*/
stopImmediatePropagation() {
const data = pd(this);
data.stopped = true;
data.immediateStopped = true;
if (typeof data.event.stopImmediatePropagation === "function") {
data.event.stopImmediatePropagation();
}
},
/**
* The flag to be bubbling.
* @type {boolean}
*/
get bubbles() {
return Boolean(pd(this).event.bubbles)
},
/**
* The flag to be cancelable.
* @type {boolean}
*/
get cancelable() {
return Boolean(pd(this).event.cancelable)
},
/**
* Cancel this event.
* @returns {void}
*/
preventDefault() {
setCancelFlag(pd(this));
},
/**
* The flag to indicate cancellation state.
* @type {boolean}
*/
get defaultPrevented() {
return pd(this).canceled
},
/**
* The flag to be composed.
* @type {boolean}
*/
get composed() {
return Boolean(pd(this).event.composed)
},
/**
* The unix time of this event.
* @type {number}
*/
get timeStamp() {
return pd(this).timeStamp
},
/**
* The target of this event.
* @type {EventTarget}
* @deprecated
*/
get srcElement() {
return pd(this).eventTarget
},
/**
* The flag to stop event bubbling.
* @type {boolean}
* @deprecated
*/
get cancelBubble() {
return pd(this).stopped
},
set cancelBubble(value) {
if (!value) {
return
}
const data = pd(this);
data.stopped = true;
if (typeof data.event.cancelBubble === "boolean") {
data.event.cancelBubble = true;
}
},
/**
* The flag to indicate cancellation state.
* @type {boolean}
* @deprecated
*/
get returnValue() {
return !pd(this).canceled
},
set returnValue(value) {
if (!value) {
setCancelFlag(pd(this));
}
},
/**
* Initialize this event object. But do nothing under event dispatching.
* @param {string} type The event type.
* @param {boolean} [bubbles=false] The flag to be possible to bubble up.
* @param {boolean} [cancelable=false] The flag to be possible to cancel.
* @deprecated
*/
initEvent() {
// Do nothing.
},
};
// `constructor` is not enumerable.
Object.defineProperty(Event.prototype, "constructor", {
value: Event,
configurable: true,
writable: true,
});
// Ensure `event instanceof window.Event` is `true`.
if (typeof window !== "undefined" && typeof window.Event !== "undefined") {
Object.setPrototypeOf(Event.prototype, window.Event.prototype);
// Make association for wrappers.
wrappers.set(window.Event.prototype, Event);
}
/**
* Get the property descriptor to redirect a given property.
* @param {string} key Property name to define property descriptor.
* @returns {PropertyDescriptor} The property descriptor to redirect the property.
* @private
*/
function defineRedirectDescriptor(key) {
return {
get() {
return pd(this).event[key]
},
set(value) {
pd(this).event[key] = value;
},
configurable: true,
enumerable: true,
}
}
/**
* Get the property descriptor to call a given method property.
* @param {string} key Property name to define property descriptor.
* @returns {PropertyDescriptor} The property descriptor to call the method property.
* @private
*/
function defineCallDescriptor(key) {
return {
value() {
const event = pd(this).event;
return event[key].apply(event, arguments)
},
configurable: true,
enumerable: true,
}
}
/**
* Define new wrapper class.
* @param {Function} BaseEvent The base wrapper class.
* @param {Object} proto The prototype of the original event.
* @returns {Function} The defined wrapper class.
* @private
*/
function defineWrapper(BaseEvent, proto) {
const keys = Object.keys(proto);
if (keys.length === 0) {
return BaseEvent
}
/** CustomEvent */
function CustomEvent(eventTarget, event) {
BaseEvent.call(this, eventTarget, event);
}
CustomEvent.prototype = Object.create(BaseEvent.prototype, {
constructor: { value: CustomEvent, configurable: true, writable: true },
});
// Define accessors.
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
if (!(key in BaseEvent.prototype)) {
const descriptor = Object.getOwnPropertyDescriptor(proto, key);
const isFunc = typeof descriptor.value === "function";
Object.defineProperty(
CustomEvent.prototype,
key,
isFunc
? defineCallDescriptor(key)
: defineRedirectDescriptor(key)
);
}
}
return CustomEvent
}
/**
* Get the wrapper class of a given prototype.
* @param {Object} proto The prototype of the original event to get its wrapper.
* @returns {Function} The wrapper class.
* @private
*/
function getWrapper(proto) {
if (proto == null || proto === Object.prototype) {
return Event
}
let wrapper = wrappers.get(proto);
if (wrapper == null) {
wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);
wrappers.set(proto, wrapper);
}
return wrapper
}
/**
* Wrap a given event to management a dispatching.
* @param {EventTarget} eventTarget The event target of this dispatching.
* @param {Object} event The event to wrap.
* @returns {Event} The wrapper instance.
* @private
*/
function wrapEvent(eventTarget, event) {
const Wrapper = getWrapper(Object.getPrototypeOf(event));
return new Wrapper(eventTarget, event)
}
/**
* Get the immediateStopped flag of a given event.
* @param {Event} event The event to get.
* @returns {boolean} The flag to stop propagation immediately.
* @private
*/
function isStopped(event) {
return pd(event).immediateStopped
}
/**
* Set the current event phase of a given event.
* @param {Event} event The event to set current target.
* @param {number} eventPhase New event phase.
* @returns {void}
* @private
*/
function setEventPhase(event, eventPhase) {
pd(event).eventPhase = eventPhase;
}
/**
* Set the current target of a given event.
* @param {Event} event The event to set current target.
* @param {EventTarget|null} currentTarget New current target.
* @returns {void}
* @private
*/
function setCurrentTarget(event, currentTarget) {
pd(event).currentTarget = currentTarget;
}
/**
* Set a passive listener of a given event.
* @param {Event} event The event to set current target.
* @param {Function|null} passiveListener New passive listener.
* @returns {void}
* @private
*/
function setPassiveListener(event, passiveListener) {
pd(event).passiveListener = passiveListener;
}
/**
* @typedef {object} ListenerNode
* @property {Function} listener
* @property {1|2|3} listenerType
* @property {boolean} passive
* @property {boolean} once
* @property {ListenerNode|null} next
* @private
*/
/**
* @type {WeakMap<object, Map<string, ListenerNode>>}
* @private
*/
const listenersMap = new WeakMap();
// Listener types
const CAPTURE = 1;
const BUBBLE = 2;
const ATTRIBUTE = 3;
/**
* Check whether a given value is an object or not.
* @param {any} x The value to check.
* @returns {boolean} `true` if the value is an object.
*/
function isObject(x) {
return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax
}
/**
* Get listeners.
* @param {EventTarget} eventTarget The event target to get.
* @returns {Map<string, ListenerNode>} The listeners.
* @private
*/
function getListeners(eventTarget) {
const listeners = listenersMap.get(eventTarget);
if (listeners == null) {
throw new TypeError(
"'this' is expected an EventTarget object, but got another value."
)
}
return listeners
}
/**
* Get the property descriptor for the event attribute of a given event.
* @param {string} eventName The event name to get property descriptor.
* @returns {PropertyDescriptor} The property descriptor.
* @private
*/
function defineEventAttributeDescriptor(eventName) {
return {
get() {
const listeners = getListeners(this);
let node = listeners.get(eventName);
while (node != null) {
if (node.listenerType === ATTRIBUTE) {
return node.listener
}
node = node.next;
}
return null
},
set(listener) {
if (typeof listener !== "function" && !isObject(listener)) {
listener = null; // eslint-disable-line no-param-reassign
}
const listeners = getListeners(this);
// Traverse to the tail while removing old value.
let prev = null;
let node = listeners.get(eventName);
while (node != null) {
if (node.listenerType === ATTRIBUTE) {
// Remove old value.
if (prev !== null) {
prev.next = node.next;
} else if (node.next !== null) {
listeners.set(eventName, node.next);
} else {
listeners.delete(eventName);
}
} else {
prev = node;
}
node = node.next;
}
// Add new value.
if (listener !== null) {
const newNode = {
listener,
listenerType: ATTRIBUTE,
passive: false,
once: false,
next: null,
};
if (prev === null) {
listeners.set(eventName, newNode);
} else {
prev.next = newNode;
}
}
},
configurable: true,
enumerable: true,
}
}
/**
* Define an event attribute (e.g. `eventTarget.onclick`).
* @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.
* @param {string} eventName The event name to define.
* @returns {void}
*/
function defineEventAttribute(eventTargetPrototype, eventName) {
Object.defineProperty(
eventTargetPrototype,
`on${eventName}`,
defineEventAttributeDescriptor(eventName)
);
}
/**
* Define a custom EventTarget with event attributes.
* @param {string[]} eventNames Event names for event attributes.
* @returns {EventTarget} The custom EventTarget.
* @private
*/
function defineCustomEventTarget(eventNames) {
/** CustomEventTarget */
function CustomEventTarget() {
EventTarget.call(this);
}
CustomEventTarget.prototype = Object.create(EventTarget.prototype, {
constructor: {
value: CustomEventTarget,
configurable: true,
writable: true,
},
});
for (let i = 0; i < eventNames.length; ++i) {
defineEventAttribute(CustomEventTarget.prototype, eventNames[i]);
}
return CustomEventTarget
}
/**
* EventTarget.
*
* - This is constructor if no arguments.
* - This is a function which returns a CustomEventTarget constructor if there are arguments.
*
* For example:
*
* class A extends EventTarget {}
* class B extends EventTarget("message") {}
* class C extends EventTarget("message", "error") {}
* class D extends EventTarget(["message", "error"]) {}
*/
function EventTarget() {
/*eslint-disable consistent-return */
if (this instanceof EventTarget) {
listenersMap.set(this, new Map());
return
}
if (arguments.length === 1 && Array.isArray(arguments[0])) {
return defineCustomEventTarget(arguments[0])
}
if (arguments.length > 0) {
const types = new Array(arguments.length);
for (let i = 0; i < arguments.length; ++i) {
types[i] = arguments[i];
}
return defineCustomEventTarget(types)
}
throw new TypeError("Cannot call a class as a function")
/*eslint-enable consistent-return */
}
// Should be enumerable, but class methods are not enumerable.
EventTarget.prototype = {
/**
* Add a given listener to this event target.
* @param {string} eventName The event name to add.
* @param {Function} listener The listener to add.
* @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
* @returns {void}
*/
addEventListener(eventName, listener, options) {
if (listener == null) {
return
}
if (typeof listener !== "function" && !isObject(listener)) {
throw new TypeError("'listener' should be a function or an object.")
}
const listeners = getListeners(this);
const optionsIsObj = isObject(options);
const capture = optionsIsObj
? Boolean(options.capture)
: Boolean(options);
const listenerType = capture ? CAPTURE : BUBBLE;
const newNode = {
listener,
listenerType,
passive: optionsIsObj && Boolean(options.passive),
once: optionsIsObj && Boolean(options.once),
next: null,
};
// Set it as the first node if the first node is null.
let node = listeners.get(eventName);
if (node === undefined) {
listeners.set(eventName, newNode);
return
}
// Traverse to the tail while checking duplication..
let prev = null;
while (node != null) {
if (
node.listener === listener &&
node.listenerType === listenerType
) {
// Should ignore duplication.
return
}
prev = node;
node = node.next;
}
// Add it.
prev.next = newNode;
},
/**
* Remove a given listener from this event target.
* @param {string} eventName The event name to remove.
* @param {Function} listener The listener to remove.
* @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
* @returns {void}
*/
removeEventListener(eventName, listener, options) {
if (listener == null) {
return
}
const listeners = getListeners(this);
const capture = isObject(options)
? Boolean(options.capture)
: Boolean(options);
const listenerType = capture ? CAPTURE : BUBBLE;
let prev = null;
let node = listeners.get(eventName);
while (node != null) {
if (
node.listener === listener &&
node.listenerType === listenerType
) {
if (prev !== null) {
prev.next = node.next;
} else if (node.next !== null) {
listeners.set(eventName, node.next);
} else {
listeners.delete(eventName);
}
return
}
prev = node;
node = node.next;
}
},
/**
* Dispatch a given event.
* @param {Event|{type:string}} event The event to dispatch.
* @returns {boolean} `false` if canceled.
*/
dispatchEvent(event) {
if (event == null || typeof event.type !== "string") {
throw new TypeError('"event.type" should be a string.')
}
// If listeners aren't registered, terminate.
const listeners = getListeners(this);
const eventName = event.type;
let node = listeners.get(eventName);
if (node == null) {
return true
}
// Since we cannot rewrite several properties, so wrap object.
const wrappedEvent = wrapEvent(this, event);
// This doesn't process capturing phase and bubbling phase.
// This isn't participating in a tree.
let prev = null;
while (node != null) {
// Remove this listener if it's once
if (node.once) {
if (prev !== null) {
prev.next = node.next;
} else if (node.next !== null) {
listeners.set(eventName, node.next);
} else {
listeners.delete(eventName);
}
} else {
prev = node;
}
// Call this listener
setPassiveListener(
wrappedEvent,
node.passive ? node.listener : null
);
if (typeof node.listener === "function") {
try {
node.listener.call(this, wrappedEvent);
} catch (err) {
if (
typeof console !== "undefined" &&
typeof console.error === "function"
) {
console.error(err);
}
}
} else if (
node.listenerType !== ATTRIBUTE &&
typeof node.listener.handleEvent === "function"
) {
node.listener.handleEvent(wrappedEvent);
}
// Break if `event.stopImmediatePropagation` was called.
if (isStopped(wrappedEvent)) {
break
}
node = node.next;
}
setPassiveListener(wrappedEvent, null);
setEventPhase(wrappedEvent, 0);
setCurrentTarget(wrappedEvent, null);
return !wrappedEvent.defaultPrevented
},
};
// `constructor` is not enumerable.
Object.defineProperty(EventTarget.prototype, "constructor", {
value: EventTarget,
configurable: true,
writable: true,
});
// Ensure `eventTarget instanceof window.EventTarget` is `true`.
if (
typeof window !== "undefined" &&
typeof window.EventTarget !== "undefined"
) {
Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);
}
export default EventTarget;
export { defineEventAttribute, EventTarget };
//# sourceMappingURL=event-target-shim.mjs.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

399
node_modules/event-target-shim/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,399 @@
export as namespace EventTargetShim
/**
* `Event` interface.
* @see https://dom.spec.whatwg.org/#event
*/
export interface Event {
/**
* The type of this event.
*/
readonly type: string
/**
* The target of this event.
*/
readonly target: EventTarget<{}, {}, "standard"> | null
/**
* The current target of this event.
*/
readonly currentTarget: EventTarget<{}, {}, "standard"> | null
/**
* The target of this event.
* @deprecated
*/
readonly srcElement: any | null
/**
* The composed path of this event.
*/
composedPath(): EventTarget<{}, {}, "standard">[]
/**
* Constant of NONE.
*/
readonly NONE: number
/**
* Constant of CAPTURING_PHASE.
*/
readonly CAPTURING_PHASE: number
/**
* Constant of BUBBLING_PHASE.
*/
readonly BUBBLING_PHASE: number
/**
* Constant of AT_TARGET.
*/
readonly AT_TARGET: number
/**
* Indicates which phase of the event flow is currently being evaluated.
*/
readonly eventPhase: number
/**
* Stop event bubbling.
*/
stopPropagation(): void
/**
* Stop event bubbling.
*/
stopImmediatePropagation(): void
/**
* Initialize event.
* @deprecated
*/
initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void
/**
* The flag indicating bubbling.
*/
readonly bubbles: boolean
/**
* Stop event bubbling.
* @deprecated
*/
cancelBubble: boolean
/**
* Set or get cancellation flag.
* @deprecated
*/
returnValue: boolean
/**
* The flag indicating whether the event can be canceled.
*/
readonly cancelable: boolean
/**
* Cancel this event.
*/
preventDefault(): void
/**
* The flag to indicating whether the event was canceled.
*/
readonly defaultPrevented: boolean
/**
* The flag to indicating if event is composed.
*/
readonly composed: boolean
/**
* Indicates whether the event was dispatched by the user agent.
*/
readonly isTrusted: boolean
/**
* The unix time of this event.
*/
readonly timeStamp: number
}
/**
* The constructor of `EventTarget` interface.
*/
export type EventTargetConstructor<
TEvents extends EventTarget.EventDefinition = {},
TEventAttributes extends EventTarget.EventDefinition = {},
TMode extends EventTarget.Mode = "loose"
> = {
prototype: EventTarget<TEvents, TEventAttributes, TMode>
new(): EventTarget<TEvents, TEventAttributes, TMode>
}
/**
* `EventTarget` interface.
* @see https://dom.spec.whatwg.org/#interface-eventtarget
*/
export type EventTarget<
TEvents extends EventTarget.EventDefinition = {},
TEventAttributes extends EventTarget.EventDefinition = {},
TMode extends EventTarget.Mode = "loose"
> = EventTarget.EventAttributes<TEventAttributes> & {
/**
* Add a given listener to this event target.
* @param eventName The event name to add.
* @param listener The listener to add.
* @param options The options for this listener.
*/
addEventListener<TEventType extends EventTarget.EventType<TEvents, TMode>>(
type: TEventType,
listener:
| EventTarget.Listener<EventTarget.PickEvent<TEvents, TEventType>>
| null,
options?: boolean | EventTarget.AddOptions
): void
/**
* Remove a given listener from this event target.
* @param eventName The event name to remove.
* @param listener The listener to remove.
* @param options The options for this listener.
*/
removeEventListener<TEventType extends EventTarget.EventType<TEvents, TMode>>(
type: TEventType,
listener:
| EventTarget.Listener<EventTarget.PickEvent<TEvents, TEventType>>
| null,
options?: boolean | EventTarget.RemoveOptions
): void
/**
* Dispatch a given event.
* @param event The event to dispatch.
* @returns `false` if canceled.
*/
dispatchEvent<TEventType extends EventTarget.EventType<TEvents, TMode>>(
event: EventTarget.EventData<TEvents, TEventType, TMode>
): boolean
}
export const EventTarget: EventTargetConstructor & {
/**
* Create an `EventTarget` instance with detailed event definition.
*
* The detailed event definition requires to use `defineEventAttribute()`
* function later.
*
* Unfortunately, the second type parameter `TEventAttributes` was needed
* because we cannot compute string literal types.
*
* @example
* const signal = new EventTarget<{ abort: Event }, { onabort: Event }>()
* defineEventAttribute(signal, "abort")
*/
new <
TEvents extends EventTarget.EventDefinition,
TEventAttributes extends EventTarget.EventDefinition,
TMode extends EventTarget.Mode = "loose"
>(): EventTarget<TEvents, TEventAttributes, TMode>
/**
* Define an `EventTarget` constructor with attribute events and detailed event definition.
*
* Unfortunately, the second type parameter `TEventAttributes` was needed
* because we cannot compute string literal types.
*
* @example
* class AbortSignal extends EventTarget<{ abort: Event }, { onabort: Event }>("abort") {
* abort(): void {}
* }
*
* @param events Optional event attributes (e.g. passing in `"click"` adds `onclick` to prototype).
*/
<
TEvents extends EventTarget.EventDefinition = {},
TEventAttributes extends EventTarget.EventDefinition = {},
TMode extends EventTarget.Mode = "loose"
>(events: string[]): EventTargetConstructor<
TEvents,
TEventAttributes,
TMode
>
/**
* Define an `EventTarget` constructor with attribute events and detailed event definition.
*
* Unfortunately, the second type parameter `TEventAttributes` was needed
* because we cannot compute string literal types.
*
* @example
* class AbortSignal extends EventTarget<{ abort: Event }, { onabort: Event }>("abort") {
* abort(): void {}
* }
*
* @param events Optional event attributes (e.g. passing in `"click"` adds `onclick` to prototype).
*/
<
TEvents extends EventTarget.EventDefinition = {},
TEventAttributes extends EventTarget.EventDefinition = {},
TMode extends EventTarget.Mode = "loose"
>(event0: string, ...events: string[]): EventTargetConstructor<
TEvents,
TEventAttributes,
TMode
>
}
export namespace EventTarget {
/**
* Options of `removeEventListener()` method.
*/
export interface RemoveOptions {
/**
* The flag to indicate that the listener is for the capturing phase.
*/
capture?: boolean
}
/**
* Options of `addEventListener()` method.
*/
export interface AddOptions extends RemoveOptions {
/**
* The flag to indicate that the listener doesn't support
* `event.preventDefault()` operation.
*/
passive?: boolean
/**
* The flag to indicate that the listener will be removed on the first
* event.
*/
once?: boolean
}
/**
* The type of regular listeners.
*/
export interface FunctionListener<TEvent> {
(event: TEvent): void
}
/**
* The type of object listeners.
*/
export interface ObjectListener<TEvent> {
handleEvent(event: TEvent): void
}
/**
* The type of listeners.
*/
export type Listener<TEvent> =
| FunctionListener<TEvent>
| ObjectListener<TEvent>
/**
* Event definition.
*/
export type EventDefinition = {
readonly [key: string]: Event
}
/**
* Mapped type for event attributes.
*/
export type EventAttributes<TEventAttributes extends EventDefinition> = {
[P in keyof TEventAttributes]:
| FunctionListener<TEventAttributes[P]>
| null
}
/**
* The type of event data for `dispatchEvent()` method.
*/
export type EventData<
TEvents extends EventDefinition,
TEventType extends keyof TEvents | string,
TMode extends Mode
> =
TEventType extends keyof TEvents
? (
// Require properties which are not generated automatically.
& Pick<
TEvents[TEventType],
Exclude<keyof TEvents[TEventType], OmittableEventKeys>
>
// Properties which are generated automatically are optional.
& Partial<Pick<Event, OmittableEventKeys>>
)
: (
TMode extends "standard"
? Event
: Event | NonStandardEvent
)
/**
* The string literal types of the properties which are generated
* automatically in `dispatchEvent()` method.
*/
export type OmittableEventKeys = Exclude<keyof Event, "type">
/**
* The type of event data.
*/
export type NonStandardEvent = {
[key: string]: any
type: string
}
/**
* The type of listeners.
*/
export type PickEvent<
TEvents extends EventDefinition,
TEventType extends keyof TEvents | string,
> =
TEventType extends keyof TEvents
? TEvents[TEventType]
: Event
/**
* Event type candidates.
*/
export type EventType<
TEvents extends EventDefinition,
TMode extends Mode
> =
TMode extends "strict"
? keyof TEvents
: keyof TEvents | string
/**
* - `"strict"` ..... Methods don't accept unknown events.
* `dispatchEvent()` accepts partial objects.
* - `"loose"` ...... Methods accept unknown events.
* `dispatchEvent()` accepts partial objects.
* - `"standard"` ... Methods accept unknown events.
* `dispatchEvent()` doesn't accept partial objects.
*/
export type Mode = "strict" | "standard" | "loose"
}
/**
* Specialized `type` property.
*/
export type Type<T extends string> = { type: T }
/**
* Define an event attribute (e.g. `eventTarget.onclick`).
* @param prototype The event target prototype to define an event attribute.
* @param eventName The event name to define.
*/
export function defineEventAttribute(
prototype: EventTarget,
eventName: string
): void
export default EventTarget

82
node_modules/event-target-shim/package.json generated vendored Normal file
View File

@@ -0,0 +1,82 @@
{
"name": "event-target-shim",
"version": "5.0.1",
"description": "An implementation of WHATWG EventTarget interface.",
"main": "dist/event-target-shim",
"types": "index.d.ts",
"files": [
"dist",
"index.d.ts"
],
"engines": {
"node": ">=6"
},
"scripts": {
"preversion": "npm test",
"version": "npm run build && git add dist/*",
"postversion": "git push && git push --tags",
"clean": "rimraf .nyc_output coverage",
"coverage": "nyc report --reporter lcov && opener coverage/lcov-report/index.html",
"lint": "eslint src test scripts --ext .js,.mjs",
"build": "rollup -c scripts/rollup.config.js",
"pretest": "npm run lint",
"test": "run-s test:*",
"test:mocha": "nyc --require ./scripts/babel-register mocha test/*.mjs",
"test:karma": "karma start scripts/karma.conf.js --single-run",
"watch": "run-p watch:*",
"watch:mocha": "mocha test/*.mjs --require ./scripts/babel-register --watch --watch-extensions js,mjs --growl",
"watch:karma": "karma start scripts/karma.conf.js --watch",
"codecov": "codecov"
},
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/plugin-transform-modules-commonjs": "^7.2.0",
"@babel/preset-env": "^7.2.3",
"@babel/register": "^7.0.0",
"@mysticatea/eslint-plugin": "^8.0.1",
"@mysticatea/spy": "^0.1.2",
"assert": "^1.4.1",
"codecov": "^3.1.0",
"eslint": "^5.12.1",
"karma": "^3.1.4",
"karma-chrome-launcher": "^2.2.0",
"karma-coverage": "^1.1.2",
"karma-firefox-launcher": "^1.0.0",
"karma-growl-reporter": "^1.0.0",
"karma-ie-launcher": "^1.0.0",
"karma-mocha": "^1.3.0",
"karma-rollup-preprocessor": "^7.0.0-rc.2",
"mocha": "^5.2.0",
"npm-run-all": "^4.1.5",
"nyc": "^13.1.0",
"opener": "^1.5.1",
"rimraf": "^2.6.3",
"rollup": "^1.1.1",
"rollup-plugin-babel": "^4.3.2",
"rollup-plugin-babel-minify": "^7.0.0",
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-json": "^3.1.0",
"rollup-plugin-node-resolve": "^4.0.0",
"rollup-watch": "^4.3.1",
"type-tester": "^1.0.0",
"typescript": "^3.2.4"
},
"repository": {
"type": "git",
"url": "https://github.com/mysticatea/event-target-shim.git"
},
"keywords": [
"w3c",
"whatwg",
"eventtarget",
"event",
"events",
"shim"
],
"author": "Toru Nagashima",
"license": "MIT",
"bugs": {
"url": "https://github.com/mysticatea/event-target-shim/issues"
},
"homepage": "https://github.com/mysticatea/event-target-shim"
}

21
node_modules/mri/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,21 @@
type Dict<T> = Record<string, T>;
type Arrayable<T> = T | T[];
type Default = Dict<any>;
declare function mri<T=Default>(args?: string[], options?: mri.Options): mri.Argv<T>;
declare namespace mri {
export interface Options {
boolean?: Arrayable<string>;
string?: Arrayable<string>;
alias?: Dict<Arrayable<string>>;
default?: Dict<any>;
unknown?(flag: string): void;
}
export type Argv<T=Default> = T & {
_: string[];
}
}
export = mri;

119
node_modules/mri/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,119 @@
function toArr(any) {
return any == null ? [] : Array.isArray(any) ? any : [any];
}
function toVal(out, key, val, opts) {
var x, old=out[key], nxt=(
!!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val))
: typeof val === 'boolean' ? val
: !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val))
: (x = +val,x * 0 === 0) ? x : val
);
out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]);
}
module.exports = function (args, opts) {
args = args || [];
opts = opts || {};
var k, arr, arg, name, val, out={ _:[] };
var i=0, j=0, idx=0, len=args.length;
const alibi = opts.alias !== void 0;
const strict = opts.unknown !== void 0;
const defaults = opts.default !== void 0;
opts.alias = opts.alias || {};
opts.string = toArr(opts.string);
opts.boolean = toArr(opts.boolean);
if (alibi) {
for (k in opts.alias) {
arr = opts.alias[k] = toArr(opts.alias[k]);
for (i=0; i < arr.length; i++) {
(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
}
}
}
for (i=opts.boolean.length; i-- > 0;) {
arr = opts.alias[opts.boolean[i]] || [];
for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]);
}
for (i=opts.string.length; i-- > 0;) {
arr = opts.alias[opts.string[i]] || [];
for (j=arr.length; j-- > 0;) opts.string.push(arr[j]);
}
if (defaults) {
for (k in opts.default) {
name = typeof opts.default[k];
arr = opts.alias[k] = opts.alias[k] || [];
if (opts[name] !== void 0) {
opts[name].push(k);
for (i=0; i < arr.length; i++) {
opts[name].push(arr[i]);
}
}
}
}
const keys = strict ? Object.keys(opts.alias) : [];
for (i=0; i < len; i++) {
arg = args[i];
if (arg === '--') {
out._ = out._.concat(args.slice(++i));
break;
}
for (j=0; j < arg.length; j++) {
if (arg.charCodeAt(j) !== 45) break; // "-"
}
if (j === 0) {
out._.push(arg);
} else if (arg.substring(j, j + 3) === 'no-') {
name = arg.substring(j + 3);
if (strict && !~keys.indexOf(name)) {
return opts.unknown(arg);
}
out[name] = false;
} else {
for (idx=j+1; idx < arg.length; idx++) {
if (arg.charCodeAt(idx) === 61) break; // "="
}
name = arg.substring(j, idx);
val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]);
arr = (j === 2 ? [name] : name);
for (idx=0; idx < arr.length; idx++) {
name = arr[idx];
if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
toVal(out, name, (idx + 1 < arr.length) || val, opts);
}
}
}
if (defaults) {
for (k in opts.default) {
if (out[k] === void 0) {
out[k] = opts.default[k];
}
}
}
if (alibi) {
for (k in out) {
arr = opts.alias[k] || [];
while (arr.length > 0) {
out[arr.shift()] = out[k];
}
}
}
return out;
}

119
node_modules/mri/lib/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,119 @@
function toArr(any) {
return any == null ? [] : Array.isArray(any) ? any : [any];
}
function toVal(out, key, val, opts) {
var x, old=out[key], nxt=(
!!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val))
: typeof val === 'boolean' ? val
: !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val))
: (x = +val,x * 0 === 0) ? x : val
);
out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]);
}
export default function (args, opts) {
args = args || [];
opts = opts || {};
var k, arr, arg, name, val, out={ _:[] };
var i=0, j=0, idx=0, len=args.length;
const alibi = opts.alias !== void 0;
const strict = opts.unknown !== void 0;
const defaults = opts.default !== void 0;
opts.alias = opts.alias || {};
opts.string = toArr(opts.string);
opts.boolean = toArr(opts.boolean);
if (alibi) {
for (k in opts.alias) {
arr = opts.alias[k] = toArr(opts.alias[k]);
for (i=0; i < arr.length; i++) {
(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
}
}
}
for (i=opts.boolean.length; i-- > 0;) {
arr = opts.alias[opts.boolean[i]] || [];
for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]);
}
for (i=opts.string.length; i-- > 0;) {
arr = opts.alias[opts.string[i]] || [];
for (j=arr.length; j-- > 0;) opts.string.push(arr[j]);
}
if (defaults) {
for (k in opts.default) {
name = typeof opts.default[k];
arr = opts.alias[k] = opts.alias[k] || [];
if (opts[name] !== void 0) {
opts[name].push(k);
for (i=0; i < arr.length; i++) {
opts[name].push(arr[i]);
}
}
}
}
const keys = strict ? Object.keys(opts.alias) : [];
for (i=0; i < len; i++) {
arg = args[i];
if (arg === '--') {
out._ = out._.concat(args.slice(++i));
break;
}
for (j=0; j < arg.length; j++) {
if (arg.charCodeAt(j) !== 45) break; // "-"
}
if (j === 0) {
out._.push(arg);
} else if (arg.substring(j, j + 3) === 'no-') {
name = arg.substring(j + 3);
if (strict && !~keys.indexOf(name)) {
return opts.unknown(arg);
}
out[name] = false;
} else {
for (idx=j+1; idx < arg.length; idx++) {
if (arg.charCodeAt(idx) === 61) break; // "="
}
name = arg.substring(j, idx);
val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]);
arr = (j === 2 ? [name] : name);
for (idx=0; idx < arr.length; idx++) {
name = arr[idx];
if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
toVal(out, name, (idx + 1 < arr.length) || val, opts);
}
}
}
if (defaults) {
for (k in opts.default) {
if (out[k] === void 0) {
out[k] = opts.default[k];
}
}
}
if (alibi) {
for (k in out) {
arr = opts.alias[k] || [];
while (arr.length > 0) {
out[arr.shift()] = out[k];
}
}
}
return out;
}

21
node_modules/mri/license.md generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.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.

43
node_modules/mri/package.json generated vendored Normal file
View File

@@ -0,0 +1,43 @@
{
"name": "mri",
"version": "1.2.0",
"description": "Quickly scan for CLI flags and arguments",
"repository": "lukeed/mri",
"module": "lib/index.mjs",
"main": "lib/index.js",
"types": "index.d.ts",
"license": "MIT",
"files": [
"*.d.ts",
"lib"
],
"author": {
"name": "Luke Edwards",
"email": "luke.edwards05@gmail.com",
"url": "https://lukeed.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"build": "bundt",
"bench": "node bench",
"pretest": "npm run build",
"test": "tape test/*.js | tap-spec"
},
"keywords": [
"argv",
"arguments",
"cli",
"minimist",
"options",
"optimist",
"parser",
"args"
],
"devDependencies": {
"bundt": "1.0.2",
"tap-spec": "4.1.2",
"tape": "4.13.3"
}
}

166
node_modules/mri/readme.md generated vendored Normal file
View File

@@ -0,0 +1,166 @@
# mri [![CI](https://github.com/lukeed/mri/workflows/CI/badge.svg?branch=master&event=push)](https://github.com/lukeed/mri/actions)
> Quickly scan for CLI flags and arguments
This is a [fast](#benchmarks) and lightweight alternative to [`minimist`](https://github.com/substack/minimist) and [`yargs-parser`](https://github.com/yargs/yargs-parser).
It only exists because I find that I usually don't need most of what `minimist` and `yargs-parser` have to offer. However, `mri` is similar _enough_ that it might function as a "drop-in replacement" for you, too!
See [Comparisons](#comparisons) for more info.
## Install
```sh
$ npm install --save mri
```
## Usage
```sh
$ demo-cli --foo --bar=baz -mtv -- hello world
```
```js
const mri = require('mri');
const argv = process.argv.slice(2);
mri(argv);
//=> { _: ['hello', 'world'], foo:true, bar:'baz', m:true, t:true, v:true }
mri(argv, { boolean:['bar'] });
//=> { _: ['baz', 'hello', 'world'], foo:true, bar:true, m:true, t:true, v:true }
mri(argv, {
alias: {
b: 'bar',
foo: ['f', 'fuz']
}
});
//=> { _: ['hello', 'world'], foo:true, f:true, fuz:true, b:'baz', bar:'baz', m:true, t:true, v:true }
```
## API
### mri(args, options)
Return: `Object`
#### args
Type: `Array`<br>
Default: `[]`
An array of arguments to parse. For CLI usage, send `process.argv.slice(2)`. See [`process.argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) for info.
#### options.alias
Type: `Object`<br>
Default: `{}`
An object of keys whose values are `String`s or `Array<String>` of aliases. These will be added to the parsed output with matching values.
#### options.boolean
Type: `Array|String`<br>
Default: `[]`
A single key (or array of keys) that should be parsed as `Boolean`s.
#### options.default
Type: `Object`<br>
Default: `{}`
An `key:value` object of defaults. If a default is provided for a key, its type (`typeof`) will be used to cast parsed arguments.
```js
mri(['--foo', 'bar']);
//=> { _:[], foo:'bar' }
mri(['--foo', 'bar'], {
default: { foo:true, baz:'hello', bat:42 }
});
//=> { _:['bar'], foo:true, baz:'hello', bat:42 }
```
> **Note:** Because `--foo` has a default of `true`, its output is cast to a Boolean. This means that `foo=true`, making `'bar'` an extra argument (`_` key).
#### options.string
Type: `Array|String`<br>
Default: `[]`
A single key (or array of keys) that should be parsed as `String`s.
#### options.unknown
Type: `Function`<br>
Default: `undefined`
Callback that is run when a parsed flag has not been defined as a known key or alias. Its only parameter is the unknown flag itself; eg `--foobar` or `-f`.
Once an unknown flag is encountered, parsing will terminate, regardless of your return value.
> **Note:** `mri` _only_ checks for unknown flags if `options.unknown` **and** `options.alias` are populated. Otherwise, everything will be accepted.
## Comparisons
#### minimist
- `mri` is 5x faster (see [benchmarks](#benchmarks))
- Numerical values are cast as `Number`s when possible
- A key (and its aliases) will always honor `opts.boolean` or `opts.string`
- Short flag groups are treated as `Boolean`s by default:
```js
minimist(['-abc', 'hello']);
//=> { _:[], a:'', b:'', c:'hello' }
mri(['-abc', 'hello']);
//=> { _:[], a:true, b:true, c:'hello' }
```
- The `opts.unknown` behaves differently:
- Unlike `minimist`, `mri` will not continue continue parsing after encountering an unknown flag
- Missing `options`:
- `opts.stopEarly`
- `opts['--']`
- Ignores newlines (`\n`) within args (see [test](https://github.com/substack/minimist/blob/master/test/parse.js#L69-L80))
- Ignores slashBreaks within args (see [test](https://github.com/substack/minimist/blob/master/test/parse.js#L147-L157))
- Ignores dot-nested flags (see [test](https://github.com/substack/minimist/blob/master/test/parse.js#L180-L197))
#### yargs-parser
- `mri` is 40x faster (see [benchmarks](#benchmarks))
- Numerical values are cast as `Number`s when possible
- A key (and its aliases) will always honor `opts.boolean` or `opts.string`
- Missing `options`:
- `opts.array`
- `opts.config`
- `opts.coerce`
- `opts.count`
- `opts.envPrefix`
- `opts.narg`
- `opts.normalize`
- `opts.configuration`
- `opts.number`
- `opts['--']`
- Missing [`parser.detailed()`](https://github.com/yargs/yargs-parser#requireyargs-parserdetailedargs-opts) method
- No [additional configuration](https://github.com/yargs/yargs-parser#configuration) object
- Added [`options.unknown`](#optionsunknown) feature
## Benchmarks
> Running Node.js v10.13.0
```
Load Times:
nopt 3.179ms
yargs-parser 2.137ms
minimist 0.746ms
mri 0.517ms
Benchmark:
minimist x 328,747 ops/sec ±1.09% (89 runs sampled)
mri x 1,622,801 ops/sec ±0.94% (92 runs sampled)
nopt x 888,223 ops/sec ±0.22% (92 runs sampled)
yargs-parser x 30,538 ops/sec ±0.81% (91 runs sampled)
```
## License
MIT © [Luke Edwards](https://lukeed.com)

162
node_modules/ms/index.js generated vendored Normal file
View File

@@ -0,0 +1,162 @@
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}

21
node_modules/ms/license.md generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020 Vercel, Inc.
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.

38
node_modules/ms/package.json generated vendored Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "ms",
"version": "2.1.3",
"description": "Tiny millisecond conversion utility",
"repository": "vercel/ms",
"main": "./index",
"files": [
"index.js"
],
"scripts": {
"precommit": "lint-staged",
"lint": "eslint lib/* bin/*",
"test": "mocha tests.js"
},
"eslintConfig": {
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
}
},
"lint-staged": {
"*.js": [
"npm run lint",
"prettier --single-quote --write",
"git add"
]
},
"license": "MIT",
"devDependencies": {
"eslint": "4.18.2",
"expect.js": "0.3.1",
"husky": "0.14.3",
"lint-staged": "5.0.0",
"mocha": "4.0.1",
"prettier": "2.0.5"
}
}

59
node_modules/ms/readme.md generated vendored Normal file
View File

@@ -0,0 +1,59 @@
# ms
![CI](https://github.com/vercel/ms/workflows/CI/badge.svg)
Use this package to easily convert various time formats to milliseconds.
## Examples
```js
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
ms('5s') // 5000
ms('1y') // 31557600000
ms('100') // 100
ms('-3 days') // -259200000
ms('-1h') // -3600000
ms('-200') // -200
```
### Convert from Milliseconds
```js
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(-3 * 60000) // "-3m"
ms(ms('10 hours')) // "10h"
```
### Time Format Written-Out
```js
ms(60000, { long: true }) // "1 minute"
ms(2 * 60000, { long: true }) // "2 minutes"
ms(-3 * 60000, { long: true }) // "-3 minutes"
ms(ms('10 hours'), { long: true }) // "10 hours"
```
## Features
- Works both in [Node.js](https://nodejs.org) and in the browser
- If a number is supplied to `ms`, a string with a unit is returned
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
## Related Packages
- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
## Caught a Bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
As always, you can run the tests using: `npm test`

22
node_modules/node-fetch/LICENSE.md generated vendored Normal file
View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2016 David Frank
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.

634
node_modules/node-fetch/README.md generated vendored Normal file
View File

@@ -0,0 +1,634 @@
node-fetch
==========
[![npm version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![coverage status][codecov-image]][codecov-url]
[![install size][install-size-image]][install-size-url]
[![Discord][discord-image]][discord-url]
A light-weight module that brings `window.fetch` to Node.js
(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567))
[![Backers][opencollective-image]][opencollective-url]
<!-- TOC -->
- [Motivation](#motivation)
- [Features](#features)
- [Difference from client-side fetch](#difference-from-client-side-fetch)
- [Installation](#installation)
- [Loading and configuring the module](#loading-and-configuring-the-module)
- [Common Usage](#common-usage)
- [Plain text or HTML](#plain-text-or-html)
- [JSON](#json)
- [Simple Post](#simple-post)
- [Post with JSON](#post-with-json)
- [Post with form parameters](#post-with-form-parameters)
- [Handling exceptions](#handling-exceptions)
- [Handling client and server errors](#handling-client-and-server-errors)
- [Advanced Usage](#advanced-usage)
- [Streams](#streams)
- [Buffer](#buffer)
- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)
- [Extract Set-Cookie Header](#extract-set-cookie-header)
- [Post data using a file stream](#post-data-using-a-file-stream)
- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)
- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)
- [API](#api)
- [fetch(url[, options])](#fetchurl-options)
- [Options](#options)
- [Class: Request](#class-request)
- [Class: Response](#class-response)
- [Class: Headers](#class-headers)
- [Interface: Body](#interface-body)
- [Class: FetchError](#class-fetcherror)
- [License](#license)
- [Acknowledgement](#acknowledgement)
<!-- /TOC -->
## Motivation
Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.
See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).
## Features
- Stay consistent with `window.fetch` API.
- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.
- Use native promise but allow substituting it with [insert your favorite promise library].
- Use native Node streams for body on both request and response.
- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.
- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting.
## Difference from client-side fetch
- See [Known Differences](LIMITS.md) for details.
- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.
- Pull requests are welcomed too!
## Installation
Current stable release (`2.x`)
```sh
$ npm install node-fetch
```
## Loading and configuring the module
We suggest you load the module via `require` until the stabilization of ES modules in node:
```js
const fetch = require('node-fetch');
```
If you are using a Promise library other than native, set it through `fetch.Promise`:
```js
const Bluebird = require('bluebird');
fetch.Promise = Bluebird;
```
## Common Usage
NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences.
#### Plain text or HTML
```js
fetch('https://github.com/')
.then(res => res.text())
.then(body => console.log(body));
```
#### JSON
```js
fetch('https://api.github.com/users/github')
.then(res => res.json())
.then(json => console.log(json));
```
#### Simple Post
```js
fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' })
.then(res => res.json()) // expecting a json response
.then(json => console.log(json));
```
#### Post with JSON
```js
const body = { a: 1 };
fetch('https://httpbin.org/post', {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));
```
#### Post with form parameters
`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.
NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:
```js
const { URLSearchParams } = require('url');
const params = new URLSearchParams();
params.append('a', 1);
fetch('https://httpbin.org/post', { method: 'POST', body: params })
.then(res => res.json())
.then(json => console.log(json));
```
#### Handling exceptions
NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information.
Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details.
```js
fetch('https://domain.invalid/')
.catch(err => console.error(err));
```
#### Handling client and server errors
It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:
```js
function checkStatus(res) {
if (res.ok) { // res.status >= 200 && res.status < 300
return res;
} else {
throw MyCustomError(res.statusText);
}
}
fetch('https://httpbin.org/status/400')
.then(checkStatus)
.then(res => console.log('will not get here...'))
```
## Advanced Usage
#### Streams
The "Node.js way" is to use streams when possible:
```js
fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
.then(res => {
const dest = fs.createWriteStream('./octocat.png');
res.body.pipe(dest);
});
```
In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch
errors -- the longer a response runs, the more likely it is to encounter an error.
```js
const fetch = require('node-fetch');
const response = await fetch('https://httpbin.org/stream/3');
try {
for await (const chunk of response.body) {
console.dir(JSON.parse(chunk.toString()));
}
} catch (err) {
console.error(err.stack);
}
```
In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams
did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors
directly from the stream and wait on it response to fully close.
```js
const fetch = require('node-fetch');
const read = async body => {
let error;
body.on('error', err => {
error = err;
});
for await (const chunk of body) {
console.dir(JSON.parse(chunk.toString()));
}
return new Promise((resolve, reject) => {
body.on('close', () => {
error ? reject(error) : resolve();
});
});
};
try {
const response = await fetch('https://httpbin.org/stream/3');
await read(response.body);
} catch (err) {
console.error(err.stack);
}
```
#### Buffer
If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API)
```js
const fileType = require('file-type');
fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
.then(res => res.buffer())
.then(buffer => fileType(buffer))
.then(type => { /* ... */ });
```
#### Accessing Headers and other Meta data
```js
fetch('https://github.com/')
.then(res => {
console.log(res.ok);
console.log(res.status);
console.log(res.statusText);
console.log(res.headers.raw());
console.log(res.headers.get('content-type'));
});
```
#### Extract Set-Cookie Header
Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.
```js
fetch(url).then(res => {
// returns an array of values, instead of a string of comma-separated values
console.log(res.headers.raw()['set-cookie']);
});
```
#### Post data using a file stream
```js
const { createReadStream } = require('fs');
const stream = createReadStream('input.txt');
fetch('https://httpbin.org/post', { method: 'POST', body: stream })
.then(res => res.json())
.then(json => console.log(json));
```
#### Post with form-data (detect multipart)
```js
const FormData = require('form-data');
const form = new FormData();
form.append('a', 1);
fetch('https://httpbin.org/post', { method: 'POST', body: form })
.then(res => res.json())
.then(json => console.log(json));
// OR, using custom headers
// NOTE: getHeaders() is non-standard API
const form = new FormData();
form.append('a', 1);
const options = {
method: 'POST',
body: form,
headers: form.getHeaders()
}
fetch('https://httpbin.org/post', options)
.then(res => res.json())
.then(json => console.log(json));
```
#### Request cancellation with AbortSignal
> NOTE: You may cancel streamed requests only on Node >= v8.0.0
You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).
An example of timing out a request after 150ms could be achieved as the following:
```js
import AbortController from 'abort-controller';
const controller = new AbortController();
const timeout = setTimeout(
() => { controller.abort(); },
150,
);
fetch(url, { signal: controller.signal })
.then(res => res.json())
.then(
data => {
useData(data)
},
err => {
if (err.name === 'AbortError') {
// request was aborted
}
},
)
.finally(() => {
clearTimeout(timeout);
});
```
See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples.
## API
### fetch(url[, options])
- `url` A string representing the URL for fetching
- `options` [Options](#fetch-options) for the HTTP(S) request
- Returns: <code>Promise&lt;[Response](#class-response)&gt;</code>
Perform an HTTP(S) fetch.
`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.
<a id="fetch-options"></a>
### Options
The default values are shown after each option key.
```js
{
// These properties are part of the Fetch Standard
method: 'GET',
headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)
body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream
redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect
signal: null, // pass an instance of AbortSignal to optionally abort requests
// The following properties are node-fetch extensions
follow: 20, // maximum redirect count. 0 to not follow redirect
timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.
compress: true, // support gzip/deflate content encoding. false to disable
size: 0, // maximum response body size in bytes. 0 to disable
agent: null // http(s).Agent instance or function that returns an instance (see below)
}
```
##### Default Headers
If no values are set, the following request headers will be sent automatically:
Header | Value
------------------- | --------------------------------------------------------
`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_
`Accept` | `*/*`
`Content-Length` | _(automatically calculated, if possible)_
`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_
`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)`
Note: when `body` is a `Stream`, `Content-Length` is not set automatically.
##### Custom Agent
The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:
- Support self-signed certificate
- Use only IPv4 or IPv6
- Custom DNS Lookup
See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.
If no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample.
In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.
```js
const httpAgent = new http.Agent({
keepAlive: true
});
const httpsAgent = new https.Agent({
keepAlive: true
});
const options = {
agent: function (_parsedURL) {
if (_parsedURL.protocol == 'http:') {
return httpAgent;
} else {
return httpsAgent;
}
}
}
```
<a id="class-request"></a>
### Class: Request
An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.
Due to the nature of Node.js, the following properties are not implemented at this moment:
- `type`
- `destination`
- `referrer`
- `referrerPolicy`
- `mode`
- `credentials`
- `cache`
- `integrity`
- `keepalive`
The following node-fetch extension properties are provided:
- `follow`
- `compress`
- `counter`
- `agent`
See [options](#fetch-options) for exact meaning of these extensions.
#### new Request(input[, options])
<small>*(spec-compliant)*</small>
- `input` A string representing a URL, or another `Request` (which will be cloned)
- `options` [Options][#fetch-options] for the HTTP(S) request
Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).
In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.
<a id="class-response"></a>
### Class: Response
An HTTP(S) response. This class implements the [Body](#iface-body) interface.
The following properties are not implemented in node-fetch at this moment:
- `Response.error()`
- `Response.redirect()`
- `type`
- `trailer`
#### new Response([body[, options]])
<small>*(spec-compliant)*</small>
- `body` A `String` or [`Readable` stream][node-readable]
- `options` A [`ResponseInit`][response-init] options dictionary
Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).
Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.
#### response.ok
<small>*(spec-compliant)*</small>
Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.
#### response.redirected
<small>*(spec-compliant)*</small>
Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.
<a id="class-headers"></a>
### Class: Headers
This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.
#### new Headers([init])
<small>*(spec-compliant)*</small>
- `init` Optional argument to pre-fill the `Headers` object
Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.
```js
// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class
const meta = {
'Content-Type': 'text/xml',
'Breaking-Bad': '<3'
};
const headers = new Headers(meta);
// The above is equivalent to
const meta = [
[ 'Content-Type', 'text/xml' ],
[ 'Breaking-Bad', '<3' ]
];
const headers = new Headers(meta);
// You can in fact use any iterable objects, like a Map or even another Headers
const meta = new Map();
meta.set('Content-Type', 'text/xml');
meta.set('Breaking-Bad', '<3');
const headers = new Headers(meta);
const copyOfHeaders = new Headers(headers);
```
<a id="iface-body"></a>
### Interface: Body
`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.
The following methods are not yet implemented in node-fetch at this moment:
- `formData()`
#### body.body
<small>*(deviation from spec)*</small>
* Node.js [`Readable` stream][node-readable]
Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].
#### body.bodyUsed
<small>*(spec-compliant)*</small>
* `Boolean`
A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.
#### body.arrayBuffer()
#### body.blob()
#### body.json()
#### body.text()
<small>*(spec-compliant)*</small>
* Returns: <code>Promise</code>
Consume the body and return a promise that will resolve to one of these formats.
#### body.buffer()
<small>*(node-fetch extension)*</small>
* Returns: <code>Promise&lt;Buffer&gt;</code>
Consume the body and return a promise that will resolve to a Buffer.
#### body.textConverted()
<small>*(node-fetch extension)*</small>
* Returns: <code>Promise&lt;String&gt;</code>
Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible.
(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.)
<a id="class-fetcherror"></a>
### Class: FetchError
<small>*(node-fetch extension)*</small>
An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.
<a id="class-aborterror"></a>
### Class: AbortError
<small>*(node-fetch extension)*</small>
An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.
## Acknowledgement
Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.
`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr).
## License
MIT
[npm-image]: https://flat.badgen.net/npm/v/node-fetch
[npm-url]: https://www.npmjs.com/package/node-fetch
[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch
[travis-url]: https://travis-ci.org/bitinn/node-fetch
[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master
[codecov-url]: https://codecov.io/gh/bitinn/node-fetch
[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch
[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch
[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square
[discord-url]: https://discord.gg/Zxbndcm
[opencollective-image]: https://opencollective.com/node-fetch/backers.svg
[opencollective-url]: https://opencollective.com/node-fetch
[whatwg-fetch]: https://fetch.spec.whatwg.org/
[response-init]: https://fetch.spec.whatwg.org/#responseinit
[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams
[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers
[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md
[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md
[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md

25
node_modules/node-fetch/browser.js generated vendored Normal file
View File

@@ -0,0 +1,25 @@
"use strict";
// ref: https://github.com/tc39/proposal-global
var getGlobal = function () {
// the only reliable means to get the global object is
// `Function('return this')()`
// However, this causes CSP violations in Chrome apps.
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
}
var globalObject = getGlobal();
module.exports = exports = globalObject.fetch;
// Needed for TypeScript and Webpack.
if (globalObject.fetch) {
exports.default = globalObject.fetch.bind(globalObject);
}
exports.Headers = globalObject.Headers;
exports.Request = globalObject.Request;
exports.Response = globalObject.Response;

1777
node_modules/node-fetch/lib/index.es.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1787
node_modules/node-fetch/lib/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1775
node_modules/node-fetch/lib/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

89
node_modules/node-fetch/package.json generated vendored Normal file
View File

@@ -0,0 +1,89 @@
{
"name": "node-fetch",
"version": "2.7.0",
"description": "A light-weight module that brings window.fetch to node.js",
"main": "lib/index.js",
"browser": "./browser.js",
"module": "lib/index.mjs",
"files": [
"lib/index.js",
"lib/index.mjs",
"lib/index.es.js",
"browser.js"
],
"engines": {
"node": "4.x || >=6.0.0"
},
"scripts": {
"build": "cross-env BABEL_ENV=rollup rollup -c",
"prepare": "npm run build",
"test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js",
"report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js",
"coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json"
},
"repository": {
"type": "git",
"url": "https://github.com/bitinn/node-fetch.git"
},
"keywords": [
"fetch",
"http",
"promise"
],
"author": "David Frank",
"license": "MIT",
"bugs": {
"url": "https://github.com/bitinn/node-fetch/issues"
},
"homepage": "https://github.com/bitinn/node-fetch",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
},
"devDependencies": {
"@ungap/url-search-params": "^0.1.2",
"abort-controller": "^1.1.0",
"abortcontroller-polyfill": "^1.3.0",
"babel-core": "^6.26.3",
"babel-plugin-istanbul": "^4.1.6",
"babel-plugin-transform-async-generator-functions": "^6.24.1",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "1.4.0",
"babel-register": "^6.16.3",
"chai": "^3.5.0",
"chai-as-promised": "^7.1.1",
"chai-iterator": "^1.1.1",
"chai-string": "~1.3.0",
"codecov": "3.3.0",
"cross-env": "^5.2.0",
"form-data": "^2.3.3",
"is-builtin-module": "^1.0.0",
"mocha": "^5.0.0",
"nyc": "11.9.0",
"parted": "^0.1.1",
"promise": "^8.0.3",
"resumer": "0.0.0",
"rollup": "^0.63.4",
"rollup-plugin-babel": "^3.0.7",
"string-to-arraybuffer": "^1.0.2",
"teeny-request": "3.7.0"
},
"release": {
"branches": [
"+([0-9]).x",
"main",
"next",
{
"name": "beta",
"prerelease": true
}
]
}
}

113
node_modules/p-timeout/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,113 @@
declare class TimeoutErrorClass extends Error {
readonly name: 'TimeoutError';
constructor(message?: string);
}
declare namespace pTimeout {
type TimeoutError = TimeoutErrorClass;
type Options = {
/**
Custom implementations for the `setTimeout` and `clearTimeout` functions.
Useful for testing purposes, in particular to work around [`sinon.useFakeTimers()`](https://sinonjs.org/releases/latest/fake-timers/).
@example
```
import pTimeout = require('p-timeout');
import sinon = require('sinon');
(async () => {
const originalSetTimeout = setTimeout;
const originalClearTimeout = clearTimeout;
sinon.useFakeTimers();
// Use `pTimeout` without being affected by `sinon.useFakeTimers()`:
await pTimeout(doSomething(), 2000, undefined, {
customTimers: {
setTimeout: originalSetTimeout,
clearTimeout: originalClearTimeout
}
});
})();
```
*/
readonly customTimers?: {
setTimeout: typeof global.setTimeout;
clearTimeout: typeof global.clearTimeout;
};
};
}
interface ClearablePromise<T> extends Promise<T>{
/**
Clear the timeout.
*/
clear: () => void;
}
declare const pTimeout: {
TimeoutError: typeof TimeoutErrorClass;
default: typeof pTimeout;
/**
Timeout a promise after a specified amount of time.
If you pass in a cancelable promise, specifically a promise with a `.cancel()` method, that method will be called when the `pTimeout` promise times out.
@param input - Promise to decorate.
@param milliseconds - Milliseconds before timing out.
@param message - Specify a custom error message or error. If you do a custom error, it's recommended to sub-class `pTimeout.TimeoutError`. Default: `'Promise timed out after 50 milliseconds'`.
@returns A decorated `input` that times out after `milliseconds` time. It has a `.clear()` method that clears the timeout.
@example
```
import delay = require('delay');
import pTimeout = require('p-timeout');
const delayedPromise = delay(200);
pTimeout(delayedPromise, 50).then(() => 'foo');
//=> [TimeoutError: Promise timed out after 50 milliseconds]
```
*/
<ValueType>(
input: PromiseLike<ValueType>,
milliseconds: number,
message?: string | Error,
options?: pTimeout.Options
): ClearablePromise<ValueType>;
/**
Timeout a promise after a specified amount of time.
If you pass in a cancelable promise, specifically a promise with a `.cancel()` method, that method will be called when the `pTimeout` promise times out.
@param input - Promise to decorate.
@param milliseconds - Milliseconds before timing out. Passing `Infinity` will cause it to never time out.
@param fallback - Do something other than rejecting with an error on timeout. You could for example retry.
@returns A decorated `input` that times out after `milliseconds` time. It has a `.clear()` method that clears the timeout.
@example
```
import delay = require('delay');
import pTimeout = require('p-timeout');
const delayedPromise = () => delay(200);
pTimeout(delayedPromise(), 50, () => {
return pTimeout(delayedPromise(), 300);
});
```
*/
<ValueType, ReturnType>(
input: PromiseLike<ValueType>,
milliseconds: number,
fallback: () => ReturnType | Promise<ReturnType>,
options?: pTimeout.Options
): ClearablePromise<ValueType | ReturnType>;
};
export = pTimeout;

71
node_modules/p-timeout/index.js generated vendored Normal file
View File

@@ -0,0 +1,71 @@
'use strict';
class TimeoutError extends Error {
constructor(message) {
super(message);
this.name = 'TimeoutError';
}
}
const pTimeout = (promise, milliseconds, fallback, options) => {
let timer;
const cancelablePromise = new Promise((resolve, reject) => {
if (typeof milliseconds !== 'number' || milliseconds < 0) {
throw new TypeError('Expected `milliseconds` to be a positive number');
}
if (milliseconds === Infinity) {
resolve(promise);
return;
}
options = {
customTimers: {setTimeout, clearTimeout},
...options
};
timer = options.customTimers.setTimeout.call(undefined, () => {
if (typeof fallback === 'function') {
try {
resolve(fallback());
} catch (error) {
reject(error);
}
return;
}
const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`;
const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);
if (typeof promise.cancel === 'function') {
promise.cancel();
}
reject(timeoutError);
}, milliseconds);
(async () => {
try {
resolve(await promise);
} catch (error) {
reject(error);
} finally {
options.customTimers.clearTimeout.call(undefined, timer);
}
})();
});
cancelablePromise.clear = () => {
clearTimeout(timer);
timer = undefined;
};
return cancelablePromise;
};
module.exports = pTimeout;
// TODO: Remove this for the next major release
module.exports.default = pTimeout;
module.exports.TimeoutError = TimeoutError;

9
node_modules/p-timeout/license generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://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.

44
node_modules/p-timeout/package.json generated vendored Normal file
View File

@@ -0,0 +1,44 @@
{
"name": "p-timeout",
"version": "4.1.0",
"description": "Timeout a promise after a specified amount of time",
"license": "MIT",
"repository": "sindresorhus/p-timeout",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=10"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"promise",
"timeout",
"error",
"invalidate",
"async",
"await",
"promises",
"time",
"out",
"cancel",
"bluebird"
],
"devDependencies": {
"ava": "^2.4.0",
"delay": "^4.4.0",
"p-cancelable": "^2.0.0",
"tsd": "^0.13.1",
"xo": "^0.35.0",
"in-range": "^2.0.0",
"time-span": "^4.0.0"
}
}

117
node_modules/p-timeout/readme.md generated vendored Normal file
View File

@@ -0,0 +1,117 @@
# p-timeout
> Timeout a promise after a specified amount of time
## Install
```
$ npm install p-timeout
```
## Usage
```js
const delay = require('delay');
const pTimeout = require('p-timeout');
const delayedPromise = delay(200);
pTimeout(delayedPromise, 50).then(() => 'foo');
//=> [TimeoutError: Promise timed out after 50 milliseconds]
```
## API
### pTimeout(input, milliseconds, message?, options?)
### pTimeout(input, milliseconds, fallback?, options?)
Returns a decorated `input` that times out after `milliseconds` time. It has a `.clear()` method that clears the timeout.
If you pass in a cancelable promise, specifically a promise with a `.cancel()` method, that method will be called when the `pTimeout` promise times out.
#### input
Type: `Promise`
Promise to decorate.
#### milliseconds
Type: `number`
Milliseconds before timing out.
Passing `Infinity` will cause it to never time out.
#### message
Type: `string | Error`\
Default: `'Promise timed out after 50 milliseconds'`
Specify a custom error message or error.
If you do a custom error, it's recommended to sub-class `pTimeout.TimeoutError`.
#### fallback
Type: `Function`
Do something other than rejecting with an error on timeout.
You could for example retry:
```js
const delay = require('delay');
const pTimeout = require('p-timeout');
const delayedPromise = () => delay(200);
pTimeout(delayedPromise(), 50, () => {
return pTimeout(delayedPromise(), 300);
});
```
#### options
Type: `object`
##### customTimers
Type: `object` with function properties `setTimeout` and `clearTimeout`
Custom implementations for the `setTimeout` and `clearTimeout` functions.
Useful for testing purposes, in particular to work around [`sinon.useFakeTimers()`](https://sinonjs.org/releases/latest/fake-timers/).
Example:
```js
const pTimeout = require('p-timeout');
const sinon = require('sinon');
(async () => {
const originalSetTimeout = setTimeout;
const originalClearTimeout = clearTimeout;
sinon.useFakeTimers();
// Use `pTimeout` without being affected by `sinon.useFakeTimers()`:
await pTimeout(doSomething(), 2000, undefined, {
customTimers: {
setTimeout: originalSetTimeout,
clearTimeout: originalClearTimeout
}
});
})();
```
### pTimeout.TimeoutError
Exposed for instance checking and sub-classing.
## Related
- [delay](https://github.com/sindresorhus/delay) - Delay a promise a specified amount of time
- [p-min-delay](https://github.com/sindresorhus/p-min-delay) - Delay a promise a minimum amount of time
- [p-retry](https://github.com/sindresorhus/p-retry) - Retry a promise-returning function
- [More…](https://github.com/sindresorhus/promise-fun)

44
node_modules/safe-compare/.npmignore generated vendored Normal file
View File

@@ -0,0 +1,44 @@
# Created by .ignore support plugin (hsz.mobi)
### Node template
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# IDE
.idea
.c9
.git
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directory
# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
node_modules
# misc
.DS_Store
.codeclimate.yml
.travis.yml
# test directory
benchmark
test

21
node_modules/safe-compare/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Michael Raith
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.

58
node_modules/safe-compare/README.md generated vendored Normal file
View File

@@ -0,0 +1,58 @@
# safe-compare
Constant-time comparison algorithm to prevent Node.js timing attacks.
For more information about Node.js timing attacks, please visit https://snyk.io/blog/node-js-timing-attack-ccc-ctf/.
[![npm package](https://img.shields.io/npm/v/safe-compare.svg?style=flat-square)](https://www.npmjs.org/package/safe-compare)
[![tag:?](https://img.shields.io/github/tag/Bruce17/safe-compare.svg?style=flat-square)](https://github.com/Bruce17/safe-compare/releases)
[![Dependency Status](https://david-dm.org/Bruce17/safe-compare.svg?style=flat-square)](https://david-dm.org/Bruce17/safe-compare)
[![devDependency Status](https://david-dm.org/Bruce17/safe-compare/dev-status.svg?style=flat-square)](https://david-dm.org/Bruce17/safe-compare#info=devDependencies)
[![Coverage Status](https://coveralls.io/repos/github/Bruce17/safe-compare/badge.svg?branch=master)](https://coveralls.io/github/Bruce17/safe-compare?branch=master)
[![Code Climate](https://codeclimate.com/github/Bruce17/safe-compare/badges/gpa.svg)](https://codeclimate.com/github/Bruce17/safe-compare)
[![Known Vulnerabilities](https://snyk.io/test/github/bruce17/safe-compare/badge.svg)](https://snyk.io/test/github/bruce17/safe-compare)
[![Build Status - Tarvis](https://travis-ci.org/Bruce17/safe-compare.svg?style=flat-square&branch=master)](https://travis-ci.org/Bruce17/safe-compare)
[![Build status - AppVeyor](https://ci.appveyor.com/api/projects/status/ounmeq5c4ajuu7g3/branch/master?svg=true)](https://ci.appveyor.com/project/Bruce17/safe-compare/branch/master)
**NOTICE**:
If you are using Node.js v6.6.0 or higher, you can use [crypto.timingSafeEqual(a, b)](https://nodejs.org/api/crypto.html#crypto_crypto_timingsafeequal_a_b) from the `crypto` module. Keep in mind that the method `crypto.timingSafeEqual` only accepts `Buffer`s with the same length! This bundle will handle strings with different lengths for you.
## Installation
```
$ npm install safe-compare --save
```
## Usage
```javascript
var safeCompare = require('safe-compare');
safeCompare('hello world', 'hello world'); // -> true
safeCompare('hello', 'not hello'); // -> false
safeCompare('hello foo', 'hello bar'); // -> false
```
Note: runtime is always corresponding to the length of the first parameter.
## Tests
```
$ npm test
```
## What's the improvement of this package?
This Node.js module is a improvement of the two existing modules [scmp](https://github.com/freewil/scmp) and [secure-compare](https://github.com/vdemedes/secure-compare). It uses the best parts of both implementations.
The implementation of [scmp](https://github.com/freewil/scmp) is a good base, but it has a shorter execution time if the string's length is not equal. The package [secure-compare](https://github.com/vdemedes/secure-compare) always compares the two input strings, but its implementation is not as clean as in [scmp](https://github.com/freewil/scmp).
## License
safe-compare is released under the MIT license.

56
node_modules/safe-compare/appveyor.yml generated vendored Normal file
View File

@@ -0,0 +1,56 @@
# Set build version.
version: "{build}-{branch}"
environment:
matrix:
- nodejs_version: "11"
- nodejs_version: "10"
- nodejs_version: "9"
- nodejs_version: "8"
- nodejs_version: "7"
- nodejs_version: "6"
- nodejs_version: "5"
- nodejs_version: "4"
- nodejs_version: "0.12"
- nodejs_version: "0.11"
- nodejs_version: "0.10"
# io.js
- nodejs_version: "1"
platform:
- x86
- x64
matrix:
# Fail fast and stop on build errors for the current tested version.
fast_finish: true
cache:
- node_modules -> package.json
# Fix Git line endings on checkout
#init:
# - git config --global core.autocrlf true
install:
- ps: Install-Product node $env:nodejs_version $env:platform
- npm install
test_script:
# Output used NodeJS/NPM versions
- node --version
- npm --version
# run tests
- npm run-script test
- npm run-script test-travis
#after_test:
# # send coverage data to coveralls
# - npm run-script coveralls
#
# # send coverage data to codeclimate
# - npm run-script codeclimate
# Don't actually build.
build: off

75
node_modules/safe-compare/index.js generated vendored Normal file
View File

@@ -0,0 +1,75 @@
/**
* @author Michael Raith
* @date 24.02.2016 12:04
*/
'use strict';
var crypto = require('crypto');
var bufferAlloc = require('buffer-alloc');
/**
* Do a constant time string comparison. Always compare the complete strings
* against each other to get a constant time. This method does not short-cut
* if the two string's length differs.
*
* @param {string} a
* @param {string} b
*
* @return {boolean}
*/
var safeCompare = function safeCompare(a, b) {
var strA = String(a);
var strB = String(b);
var lenA = strA.length;
var result = 0;
if (lenA !== strB.length) {
strB = strA;
result = 1;
}
for (var i = 0; i < lenA; i++) {
result |= (strA.charCodeAt(i) ^ strB.charCodeAt(i));
}
return result === 0;
};
/**
* Call native "crypto.timingSafeEqual" methods.
* All passed values will be converted into strings first.
*
* Runtime is always corresponding to the length of the first parameter (string
* a).
*
* @param {string} a
* @param {string} b
*
* @return {boolean}
*/
var nativeTimingSafeEqual = function nativeTimingSafeEqual(a, b) {
var strA = String(a);
var strB = String(b);
var aLen = Buffer.byteLength(strA);
var bLen = Buffer.byteLength(strB);
// Always use length of a to avoid leaking the length. Even if this is a
// false positive because one is a prefix of the other, the explicit length
// check at the end will catch that.
var bufA = bufferAlloc(aLen, 0, 'utf8');
bufA.write(strA);
var bufB = bufferAlloc(aLen, 0, 'utf8');
bufB.write(strB);
return crypto.timingSafeEqual(bufA, bufB) && aLen === bLen;
};
module.exports = (
typeof crypto.timingSafeEqual !== 'undefined' ?
nativeTimingSafeEqual :
safeCompare
);

46
node_modules/safe-compare/package.json generated vendored Normal file
View File

@@ -0,0 +1,46 @@
{
"name": "safe-compare",
"version": "1.1.4",
"description": "Constant-time comparison algorithm to prevent timing attacks.",
"main": "index.js",
"scripts": {
"test": "mocha",
"posttest": "matcha",
"test-travis": "node --harmony node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -u exports",
"coveralls": "node ./node_modules/.bin/coveralls < ./coverage/lcov.info",
"codeclimate": "node ./node_modules/.bin/codeclimate-test-reporter < ./coverage/lcov.info"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Bruce17/safe-compare.git"
},
"keywords": [
"safe-compare",
"secure-compare",
"compare",
"time-equivalent-comparison",
"time",
"equivalent",
"timing",
"attack",
"constant-time",
"constant",
"time"
],
"author": "Michael Raith",
"license": "MIT",
"readmeFilename": "README.md",
"bugs": {
"url": "https://github.com/Bruce17/safe-compare/issues"
},
"homepage": "https://github.com/Bruce17/safe-compare#readme",
"devDependencies": {
"coveralls": "^2.11.14",
"istanbul": "^0.4.5",
"matcha": "^0.7.0",
"mocha": "^3.1.2"
},
"dependencies": {
"buffer-alloc": "^1.2.0"
}
}

13
node_modules/sandwich-stream/.editorconfig generated vendored Normal file
View File

@@ -0,0 +1,13 @@
# editorconfig.org
root = true
[*]
indent_size = 4
indent_style = space
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false

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