diff --git a/GEMINI.md b/GEMINI.md index 1b532bf..796a6c2 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -5,9 +5,9 @@ ## 🛠️ Stack Tecnológica - **Frontend/Backend:** Remix (React) -- **Banco de Dados:** PostgreSQL (Local e Nuvem via Supabase) -- **Arquitetura de Storage:** Self-Hosted (MinIO) via API HTTP customizada (bypass do SDK Supabase para arquivos). -- **Infraestrutura Cloud:** Supabase (Auth, Database Sync) +- **Banco de Dados:** PostgreSQL (100% Local/Self-Hosted) +- **Arquitetura de Storage:** Self-Hosted (MinIO) - 100% Desacoplado do Supabase Cloud. +- **Sincronização:** API Local de alta performance para conciliação bancária (Asaas). - **Orquestração:** Portainer (Docker) ## ⚠️ Regras de Negócio Críticas (MANDATÓRIO) @@ -19,5 +19,6 @@ ## 📜 Padrões de Desenvolvimento 1. **Design System:** Estética Premium, Dark Mode por padrão (ou glassmorphism), micro-animações e ausência de placeholders. -2. **Segurança:** Todas as rotas sensíveis devem validar o token do Supabase. +2. **Segurança:** Todas as rotas sensíveis devem validar o token JWT local (via secrets do ambiente). Proibido usar Supabase SDK para lógica de autenticação ou sincronização no frontend. 3. **Resiliência:** Tratamento rigoroso de erros em chamadas de API de terceiros (Asaas, Evolution API). +4. **Upload de Arquivos:** Proibido o uso de Base64 para envio de novos arquivos ao servidor. Use obrigatoriamente `FormData` e envie o objeto `File/Blob` para as rotas de API que integram com o MinIO. diff --git a/MEMORY.md b/MEMORY.md index 029c4ef..1866c53 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -13,14 +13,23 @@ ### ⚙️ Módulo de Configurações e Infra (Manager) - **Arquitetura de Armazenamento:** Implementada a transição para **Self-Hosted Storage (MinIO)**. - - O arquivo `supabase.ts` foi substituído por uma versão que utiliza chamadas de API HTTP (`/api/upload`) em vez do SDK da Supabase, garantindo total controle sobre os arquivos no ambiente local. + - Extração de Base64 concluída com sucesso via `migrate_images_to_minio.ts`. + - O banco de dados de produção (PostgreSQL Local) foi populado com sucesso absoluto na VPS através da rota `/api/migracao-remota` utilizando o script `injetar_magia.ts`. + - O sistema agora é 100% Self-Hosted (PostgreSQL e MinIO próprios), sem dependência da nuvem do Supabase. - **Funcionalidades de Configuração:** - Gestão multi-unidade (Alternância entre Matriz e Filiais). - Validação de CNPJ e busca automática via CEP. - Monitoramento de logs de API em tempo real. - **Histórico de Estabilidade:** - - Realizamos um `reset --hard e2b9810` para remover tentativas falhas de otimização de build que causaram instabilidade. - O sistema voltou para o último estado "verde" conhecido. +- **Refatoração de Uploads (Missão 2):** + - [x] **Foto do Aluno (Manager):** Migrado de Base64 para envio via `FormData` direto ao MinIO no componente `Students.tsx`. + - [x] **Logo da Escola (Settings):** Removido falback agressivo para base64 e isolado backend para upload exclusivo no bucket `logos`. + - [x] **Imagens de Avaliações (Exams):** Ajustado para utilizar Rota isolada `form-data` para salvar no bucket `exames` do MinIO. + - [x] **Atestados (Portal):** Refatorado portal (backend e view) para upload do arquivo binário e salvar a url pública no JSON associado. + - [x] **Frequência e Biometria (AttendanceQuery):** Corrigido bug de contagem, deduplicação de aulas e janela de 30 minutos para validação facial. + - [x] **Financeiro (Manager):** Migração total para API PostgreSQL local, eliminando o Supabase Sync que causava erros na aba financeira. + - [x] **Telemetria do Sistema (Settings):** Cards reais de monitoramento de disco (Postgres) e objetos (MinIO). ### 🚀 Infraestrutura e Deploy - **Estado Atual:** O pipeline do GitHub Actions está configurado para gerar imagens Docker para `amd64` e `arm64`. @@ -28,7 +37,6 @@ ## 📋 Próximos Passos Pendentes -1. **Migração Schoodat:** Iniciar script de migração seguindo a regra de não alteração de senhas em `GEMINI.md`. +1. **Concluída a Arquitetura de Storage Local (MinIO):** Todo o sistema (Tanto portal quanto manager) agora utiliza `FormData` para envio físico de arquivos aos servidores, salvando apenas a `URL pública` no banco de dados. 2. **Otimização de Build:** Re-explorar o cache do Docker ou considerar a remoção do suporte nativo ARM64 se não for estritamente necessário para o servidor final. 3. **Financeiro:** Implementar visualização de extrato detalhado e integração com gateway de pagamento direto via cartão. -4. **Segurança:** Auditar as políticas de RLS no Supabase para as tabelas de sincronização. diff --git a/manager/components/Settings.tsx b/manager/components/Settings.tsx index 2a6b4c1..dc4519c 100644 --- a/manager/components/Settings.tsx +++ b/manager/components/Settings.tsx @@ -60,11 +60,23 @@ const Settings: React.FC = ({ data, updateData, setData }) => { const [apiLogs, setApiLogs] = useState([]); const [systemStats, setSystemStats] = useState(null); - React.useEffect(() => { + const fetchStats = () => { fetch('/api/system-stats') .then(res => res.json()) - .then(data => setSystemStats(data)) - .catch(err => console.error('Erro ao buscar stats do sistema:', err)); + .then(data => { + if (data.error) console.error('Erro na API:', data.error); + setSystemStats(data); + }) + .catch(err => { + console.error('Erro ao buscar stats do sistema:', err); + setSystemStats({ error: true }); + }); + }; + + React.useEffect(() => { + fetchStats(); + const interval = setInterval(fetchStats, 30000); // Atualiza a cada 30s + return () => clearInterval(interval); }, []); React.useEffect(() => { diff --git a/manager/server.selfhosted.js b/manager/server.selfhosted.js index 8059eff..d367cfb 100644 --- a/manager/server.selfhosted.js +++ b/manager/server.selfhosted.js @@ -28,7 +28,8 @@ import { getCobrancasByInstallmentId, updateCobrancaLinkCarne, updateCobrancaByField } from './services/database.js'; -import { uploadLogo as uploadLogoToStorage, uploadCarne as uploadCarneToStorage, getMinioStats } from './services/storage.js'; +import { uploadLogo as uploadLogoToStorage, uploadCarne as uploadCarneToStorage, getMinioStats, s3Client } from './services/storage.js'; +import { GetObjectCommand } from '@aws-sdk/client-s3'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -48,7 +49,25 @@ const cancelCache = new Set(); const sentCache = new Set(); const lockCache = new Set(); -const upload = multer({ storage: multer.memoryStorage() }); +// ============================================================ +// Proxy de Imagens do MinIO (acesso público via backend) +// ============================================================ +app.get('/storage/:bucket/:key', async (req, res) => { + try { + const { bucket, key } = req.params; + const command = new GetObjectCommand({ Bucket: bucket, Key: key }); + const data = await s3Client.send(command); + + res.set('Content-Type', data.ContentType || 'image/jpeg'); + res.set('Cache-Control', 'public, max-age=86400'); + data.Body.pipe(res); + } catch (e) { + res.status(404).send('Arquivo não encontrado'); + } +}); + +const multerStorage = multer.memoryStorage(); +const upload = multer({ storage: multerStorage, limits: { fileSize: 10 * 1024 * 1024 } }); // ============================================================ // ROTA NOVA: Login Administrativo (JWT) @@ -91,6 +110,44 @@ app.post('/api/auth/login', async (req, res) => { app.get('/api/school-data', async (req, res) => { try { const data = await getSchoolData(); + + // Normalizar URLs do MinIO para proxy relativo + // Converte URLs como https://storageedu.xxx/bucket/file para /storage/bucket/file + const MINIO_PUBLIC_URL = process.env.MINIO_PUBLIC_URL || ''; + const normalizeUrl = (url) => { + if (!url || typeof url !== 'string') return url; + // Se já é uma URL relativa de proxy, manter + if (url.startsWith('/storage/')) return url; + // Se é a URL pública do MinIO, converter para proxy + if (MINIO_PUBLIC_URL && url.startsWith(MINIO_PUBLIC_URL)) { + return url.replace(MINIO_PUBLIC_URL, '/storage'); + } + // Fallback: URL com http://localhost:9000 ou http://minio:9000 + const match = url.match(/^https?:\/\/[^\/]+\/(.+)$/); + if (match && (url.includes('minio') || url.includes('storageedu') || url.includes(':9000'))) { + return `/storage/${match[1]}`; + } + return url; + }; + + // Normalizar fotos de alunos + if (data.students) { + data.students.forEach(s => { if (s.photo) s.photo = normalizeUrl(s.photo); }); + } + // Normalizar logo + if (data.logo) data.logo = normalizeUrl(data.logo); + if (data.profile?.logo) data.profile.logo = normalizeUrl(data.profile.logo); + // Normalizar fotos nos registros de presença + if (data.attendance) { + data.attendance.forEach(a => { if (a.photo) a.photo = normalizeUrl(a.photo); }); + } + // Normalizar imagens de exames + if (data.exams) { + data.exams.forEach(e => { + if (e.questions) e.questions.forEach(q => { if (q.image) q.image = normalizeUrl(q.image); }); + }); + } + res.json({ data }); } catch (error) { console.error('Erro ao buscar school_data:', error); diff --git a/manager/services/storage.js b/manager/services/storage.js index c400a72..f6fb4fd 100644 --- a/manager/services/storage.js +++ b/manager/services/storage.js @@ -41,8 +41,9 @@ export async function uploadFile(bucket, fileName, fileBuffer, contentType) { await s3Client.send(command); - // Retorna a URL pública (MinIO com política de download anônimo) - return `${MINIO_PUBLIC_URL}/${bucket}/${fileName}`; + // Retorna URL relativa que será servida pelo proxy do backend + // Isso garante que o browser acessa via nosso servidor, sem precisar de acesso direto ao MinIO + return `/storage/${bucket}/${fileName}`; } /** diff --git a/node_modules/.bin/acorn b/node_modules/.bin/acorn new file mode 100644 index 0000000..679bd16 --- /dev/null +++ b/node_modules/.bin/acorn @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../acorn/bin/acorn" "$@" +else + exec node "$basedir/../acorn/bin/acorn" "$@" +fi diff --git a/node_modules/.bin/acorn.cmd b/node_modules/.bin/acorn.cmd new file mode 100644 index 0000000..a9324df --- /dev/null +++ b/node_modules/.bin/acorn.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\acorn\bin\acorn" %* diff --git a/node_modules/.bin/acorn.ps1 b/node_modules/.bin/acorn.ps1 new file mode 100644 index 0000000..6f6dcdd --- /dev/null +++ b/node_modules/.bin/acorn.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args + } else { + & "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../acorn/bin/acorn" $args + } else { + & "node$exe" "$basedir/../acorn/bin/acorn" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/fxparser b/node_modules/.bin/fxparser new file mode 100644 index 0000000..c722e41 --- /dev/null +++ b/node_modules/.bin/fxparser @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../fast-xml-parser/src/cli/cli.js" "$@" +else + exec node "$basedir/../fast-xml-parser/src/cli/cli.js" "$@" +fi diff --git a/node_modules/.bin/fxparser.cmd b/node_modules/.bin/fxparser.cmd new file mode 100644 index 0000000..043b763 --- /dev/null +++ b/node_modules/.bin/fxparser.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\fast-xml-parser\src\cli\cli.js" %* diff --git a/node_modules/.bin/fxparser.ps1 b/node_modules/.bin/fxparser.ps1 new file mode 100644 index 0000000..3e7252a --- /dev/null +++ b/node_modules/.bin/fxparser.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../fast-xml-parser/src/cli/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../fast-xml-parser/src/cli/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../fast-xml-parser/src/cli/cli.js" $args + } else { + & "node$exe" "$basedir/../fast-xml-parser/src/cli/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/ts-node b/node_modules/.bin/ts-node new file mode 100644 index 0000000..f3d4fab --- /dev/null +++ b/node_modules/.bin/ts-node @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../ts-node/dist/bin.js" "$@" +else + exec node "$basedir/../ts-node/dist/bin.js" "$@" +fi diff --git a/node_modules/.bin/ts-node-cwd b/node_modules/.bin/ts-node-cwd new file mode 100644 index 0000000..ae68e85 --- /dev/null +++ b/node_modules/.bin/ts-node-cwd @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../ts-node/dist/bin-cwd.js" "$@" +else + exec node "$basedir/../ts-node/dist/bin-cwd.js" "$@" +fi diff --git a/node_modules/.bin/ts-node-cwd.cmd b/node_modules/.bin/ts-node-cwd.cmd new file mode 100644 index 0000000..50c1bbc --- /dev/null +++ b/node_modules/.bin/ts-node-cwd.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-node\dist\bin-cwd.js" %* diff --git a/node_modules/.bin/ts-node-cwd.ps1 b/node_modules/.bin/ts-node-cwd.ps1 new file mode 100644 index 0000000..b12acfa --- /dev/null +++ b/node_modules/.bin/ts-node-cwd.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-cwd.js" $args + } else { + & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-cwd.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../ts-node/dist/bin-cwd.js" $args + } else { + & "node$exe" "$basedir/../ts-node/dist/bin-cwd.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/ts-node-esm b/node_modules/.bin/ts-node-esm new file mode 100644 index 0000000..19ea759 --- /dev/null +++ b/node_modules/.bin/ts-node-esm @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../ts-node/dist/bin-esm.js" "$@" +else + exec node "$basedir/../ts-node/dist/bin-esm.js" "$@" +fi diff --git a/node_modules/.bin/ts-node-esm.cmd b/node_modules/.bin/ts-node-esm.cmd new file mode 100644 index 0000000..ba439a0 --- /dev/null +++ b/node_modules/.bin/ts-node-esm.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-node\dist\bin-esm.js" %* diff --git a/node_modules/.bin/ts-node-esm.ps1 b/node_modules/.bin/ts-node-esm.ps1 new file mode 100644 index 0000000..d9806c0 --- /dev/null +++ b/node_modules/.bin/ts-node-esm.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-esm.js" $args + } else { + & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-esm.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../ts-node/dist/bin-esm.js" $args + } else { + & "node$exe" "$basedir/../ts-node/dist/bin-esm.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/ts-node-script b/node_modules/.bin/ts-node-script new file mode 100644 index 0000000..14c2f67 --- /dev/null +++ b/node_modules/.bin/ts-node-script @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../ts-node/dist/bin-script.js" "$@" +else + exec node "$basedir/../ts-node/dist/bin-script.js" "$@" +fi diff --git a/node_modules/.bin/ts-node-script.cmd b/node_modules/.bin/ts-node-script.cmd new file mode 100644 index 0000000..146251b --- /dev/null +++ b/node_modules/.bin/ts-node-script.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-node\dist\bin-script.js" %* diff --git a/node_modules/.bin/ts-node-script.ps1 b/node_modules/.bin/ts-node-script.ps1 new file mode 100644 index 0000000..3061e81 --- /dev/null +++ b/node_modules/.bin/ts-node-script.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-script.js" $args + } else { + & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-script.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../ts-node/dist/bin-script.js" $args + } else { + & "node$exe" "$basedir/../ts-node/dist/bin-script.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/ts-node-transpile-only b/node_modules/.bin/ts-node-transpile-only new file mode 100644 index 0000000..d3d4c0c --- /dev/null +++ b/node_modules/.bin/ts-node-transpile-only @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../ts-node/dist/bin-transpile.js" "$@" +else + exec node "$basedir/../ts-node/dist/bin-transpile.js" "$@" +fi diff --git a/node_modules/.bin/ts-node-transpile-only.cmd b/node_modules/.bin/ts-node-transpile-only.cmd new file mode 100644 index 0000000..60b2af3 --- /dev/null +++ b/node_modules/.bin/ts-node-transpile-only.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-node\dist\bin-transpile.js" %* diff --git a/node_modules/.bin/ts-node-transpile-only.ps1 b/node_modules/.bin/ts-node-transpile-only.ps1 new file mode 100644 index 0000000..9503db4 --- /dev/null +++ b/node_modules/.bin/ts-node-transpile-only.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-transpile.js" $args + } else { + & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-transpile.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../ts-node/dist/bin-transpile.js" $args + } else { + & "node$exe" "$basedir/../ts-node/dist/bin-transpile.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/ts-node.cmd b/node_modules/.bin/ts-node.cmd new file mode 100644 index 0000000..a2a9c92 --- /dev/null +++ b/node_modules/.bin/ts-node.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-node\dist\bin.js" %* diff --git a/node_modules/.bin/ts-node.ps1 b/node_modules/.bin/ts-node.ps1 new file mode 100644 index 0000000..90517a4 --- /dev/null +++ b/node_modules/.bin/ts-node.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../ts-node/dist/bin.js" $args + } else { + & "$basedir/node$exe" "$basedir/../ts-node/dist/bin.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../ts-node/dist/bin.js" $args + } else { + & "node$exe" "$basedir/../ts-node/dist/bin.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/ts-script b/node_modules/.bin/ts-script new file mode 100644 index 0000000..8f65f36 --- /dev/null +++ b/node_modules/.bin/ts-script @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../ts-node/dist/bin-script-deprecated.js" "$@" +else + exec node "$basedir/../ts-node/dist/bin-script-deprecated.js" "$@" +fi diff --git a/node_modules/.bin/ts-script.cmd b/node_modules/.bin/ts-script.cmd new file mode 100644 index 0000000..e3b0e81 --- /dev/null +++ b/node_modules/.bin/ts-script.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-node\dist\bin-script-deprecated.js" %* diff --git a/node_modules/.bin/ts-script.ps1 b/node_modules/.bin/ts-script.ps1 new file mode 100644 index 0000000..1b348af --- /dev/null +++ b/node_modules/.bin/ts-script.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-script-deprecated.js" $args + } else { + & "$basedir/node$exe" "$basedir/../ts-node/dist/bin-script-deprecated.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../ts-node/dist/bin-script-deprecated.js" $args + } else { + & "node$exe" "$basedir/../ts-node/dist/bin-script-deprecated.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/tsc b/node_modules/.bin/tsc new file mode 100644 index 0000000..c4864b9 --- /dev/null +++ b/node_modules/.bin/tsc @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../typescript/bin/tsc" "$@" +else + exec node "$basedir/../typescript/bin/tsc" "$@" +fi diff --git a/node_modules/.bin/tsc.cmd b/node_modules/.bin/tsc.cmd new file mode 100644 index 0000000..40bf128 --- /dev/null +++ b/node_modules/.bin/tsc.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\typescript\bin\tsc" %* diff --git a/node_modules/.bin/tsc.ps1 b/node_modules/.bin/tsc.ps1 new file mode 100644 index 0000000..112413b --- /dev/null +++ b/node_modules/.bin/tsc.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../typescript/bin/tsc" $args + } else { + & "$basedir/node$exe" "$basedir/../typescript/bin/tsc" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../typescript/bin/tsc" $args + } else { + & "node$exe" "$basedir/../typescript/bin/tsc" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/tsserver b/node_modules/.bin/tsserver new file mode 100644 index 0000000..6c19ce3 --- /dev/null +++ b/node_modules/.bin/tsserver @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../typescript/bin/tsserver" "$@" +else + exec node "$basedir/../typescript/bin/tsserver" "$@" +fi diff --git a/node_modules/.bin/tsserver.cmd b/node_modules/.bin/tsserver.cmd new file mode 100644 index 0000000..57f851f --- /dev/null +++ b/node_modules/.bin/tsserver.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\typescript\bin\tsserver" %* diff --git a/node_modules/.bin/tsserver.ps1 b/node_modules/.bin/tsserver.ps1 new file mode 100644 index 0000000..249f417 --- /dev/null +++ b/node_modules/.bin/tsserver.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../typescript/bin/tsserver" $args + } else { + & "$basedir/node$exe" "$basedir/../typescript/bin/tsserver" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../typescript/bin/tsserver" $args + } else { + & "node$exe" "$basedir/../typescript/bin/tsserver" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..0fd93f7 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,571 @@ +{ + "name": "remix_-edumanager---sistema-de-gestão-escolar-para-porteiner", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@nodable/entities": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-2.1.0.tgz", + "integrity": "sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/nodable" + } + ], + "license": "MIT" + }, + "node_modules/@tsconfig/node10": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.12.tgz", + "integrity": "sha512-UCYBaeFvM11aU2y3YPZ//O5Rhj+xKyzy7mvcIoAjASbigy8mHMryP5cK7dgjlz2hWxh1g5pLw084E0a/wlUSFQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/minio": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@types/minio/-/minio-7.1.0.tgz", + "integrity": "sha512-yUaFE62KI7lhQLH7lQpT1bzDmTOS+8bD7wGN8ySk8teLv9afbL7RIT3tSbeijq6sqeyS9kGpj9Kmp4gHNQJWCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/node": { + "version": "25.6.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz", + "integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.19.0" + } + }, + "node_modules/acorn": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", + "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true, + "license": "MIT" + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "license": "MIT" + }, + "node_modules/block-stream2": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/block-stream2/-/block-stream2-2.1.0.tgz", + "integrity": "sha512-suhjmLI57Ewpmq00qaygS8UgEq2ly2PCItenIyhMqVjo4t4pGzqMvfgJuX8iWTeSDdfSSqS6j38fL4ToNL7Pfg==", + "license": "MIT", + "dependencies": { + "readable-stream": "^3.4.0" + } + }, + "node_modules/browser-or-node": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/browser-or-node/-/browser-or-node-2.1.1.tgz", + "integrity": "sha512-8CVjaLJGuSKMVTxJ2DpBl5XnlNDiT4cQFeuCJJrvJmts9YrTZDizTX7PjC2s6W4x+MBGZeEY6dGMrF04/6Hgqg==", + "license": "MIT" + }, + "node_modules/buffer-crc32": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-1.0.0.tgz", + "integrity": "sha512-Db1SbgBS/fg/392AblrMJk97KggmvYhr4pB5ZIMTWtaivCPMWLkmb7m21cJvpvgK+J3nsU2CmmixNBZx4vFj/w==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/decode-uri-component": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.2.tgz", + "integrity": "sha512-FqUYQ+8o158GyGTrMFJms9qh3CqTKvAqgqsTnkLI8sKu0028orqBhxNMFkFen0zGyg6epACD32pjVk58ngIErQ==", + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/diff": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", + "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "license": "MIT" + }, + "node_modules/fast-xml-builder": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.1.5.tgz", + "integrity": "sha512-4TJn/8FKLeslLAH3dnohXqE3QSoxkhvaMzepOIZytwJXZO69Bfz0HBdDHzOTOon6G59Zrk6VQ2bEiv1t61rfkA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "path-expression-matcher": "^1.1.3" + } + }, + "node_modules/fast-xml-parser": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.7.1.tgz", + "integrity": "sha512-8Cc3f8GUGUULg34pBch/KGyPLglS+OFs05deyOlY7fL2MTagYPKrVQNmR1fLF/yJ9PH5ZSTd3YDF6pnmeZU+zA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "@nodable/entities": "^2.1.0", + "fast-xml-builder": "^1.1.5", + "path-expression-matcher": "^1.5.0", + "strnum": "^2.2.3" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/filter-obj": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/filter-obj/-/filter-obj-1.1.0.tgz", + "integrity": "sha512-8rXg1ZnX7xzy2NGDVkBVaAy+lSlPNwad13BtgSlLuxfIslyt5Vg64U7tFcCt4WS1R0hvtnQybT/IyCkGZ3DpXQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.3.0.tgz", + "integrity": "sha512-Zv/pA+ciVFbCSBBjGfaKUya/CcGmUHzTydLMaTwrUUEM2DIEO3iZvueGxmacvmN50fGpGVKeTXpb2LcYQxeVdg==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "license": "MIT" + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true, + "license": "ISC" + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minio": { + "version": "8.0.7", + "resolved": "https://registry.npmjs.org/minio/-/minio-8.0.7.tgz", + "integrity": "sha512-E737MgufW8CeQAsTAtnEMrxZ9scMSf29kkhZoXzDTKj/Jszzo2SfeZUH9wbDQH2Rsq6TCtl/yQL0+XdVKZansQ==", + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.4", + "block-stream2": "^2.1.0", + "browser-or-node": "^2.1.1", + "buffer-crc32": "^1.0.0", + "eventemitter3": "^5.0.1", + "fast-xml-parser": "^5.3.4", + "ipaddr.js": "^2.0.1", + "lodash": "^4.17.21", + "mime-types": "^2.1.35", + "query-string": "^7.1.3", + "stream-json": "^1.8.0", + "through2": "^4.0.2", + "xml2js": "^0.5.0 || ^0.6.2" + }, + "engines": { + "node": "^16 || ^18 || >=20" + } + }, + "node_modules/path-expression-matcher": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz", + "integrity": "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/query-string": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/query-string/-/query-string-7.1.3.tgz", + "integrity": "sha512-hh2WYhq4fi8+b+/2Kg9CEge4fDPvHS534aOOvOZeQ3+Vf2mCFsaFBYj0i+iXcAq6I9Vzp5fjMFBlONvayDC1qg==", + "license": "MIT", + "dependencies": { + "decode-uri-component": "^0.2.2", + "filter-obj": "^1.1.0", + "split-on-first": "^1.0.0", + "strict-uri-encode": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/sax": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz", + "integrity": "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=11.0.0" + } + }, + "node_modules/split-on-first": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/split-on-first/-/split-on-first-1.1.0.tgz", + "integrity": "sha512-43ZssAJaMusuKWL8sKUBQXHWOpq8d6CfN/u1p4gUzfJkM05C8rxTmYrkIPTXapZpORA6LkkzcUulJ8FqA7Uudw==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/stream-chain": { + "version": "2.2.5", + "resolved": "https://registry.npmjs.org/stream-chain/-/stream-chain-2.2.5.tgz", + "integrity": "sha512-1TJmBx6aSWqZ4tx7aTpBDXK0/e2hhcNSTV8+CbFJtDjbb+I1mZ8lHit0Grw9GRT+6JbIrrDd8esncgBi8aBXGA==", + "license": "BSD-3-Clause" + }, + "node_modules/stream-json": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/stream-json/-/stream-json-1.9.1.tgz", + "integrity": "sha512-uWkjJ+2Nt/LO9Z/JyKZbMusL8Dkh97uUBTv3AJQ74y07lVahLY4eEFsPsE97pxYBwr8nnjMAIch5eqI0gPShyw==", + "license": "BSD-3-Clause", + "dependencies": { + "stream-chain": "^2.2.5" + } + }, + "node_modules/strict-uri-encode": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strict-uri-encode/-/strict-uri-encode-2.0.0.tgz", + "integrity": "sha512-QwiXZgpRcKkhTj2Scnn++4PKtWsH0kpzZ62L2R6c/LUVYv7hVnZqcg2+sMuT6R7Jusu1vviK/MFsu6kNJfWlEQ==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strnum": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.2.3.tgz", + "integrity": "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, + "node_modules/through2": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", + "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", + "license": "MIT", + "dependencies": { + "readable-stream": "3" + } + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.19.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz", + "integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==", + "dev": true, + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true, + "license": "MIT" + }, + "node_modules/xml2js": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz", + "integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==", + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", + "license": "MIT", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + } + } +} diff --git a/node_modules/@cspotcode/source-map-support/LICENSE.md b/node_modules/@cspotcode/source-map-support/LICENSE.md new file mode 100644 index 0000000..6247ca9 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Evan Wallace + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@cspotcode/source-map-support/README.md b/node_modules/@cspotcode/source-map-support/README.md new file mode 100644 index 0000000..f739070 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/README.md @@ -0,0 +1,289 @@ +# Source Map Support + +[![NPM version](https://img.shields.io/npm/v/@cspotcode/source-map-support.svg?style=flat)](https://npmjs.org/package/@cspotcode/source-map-support) +[![NPM downloads](https://img.shields.io/npm/dm/@cspotcode/source-map-support.svg?style=flat)](https://npmjs.org/package/@cspotcode/source-map-support) +[![Build status](https://img.shields.io/github/workflow/status/cspotcode/node-source-map-support/Continuous%20Integration)](https://github.com/cspotcode/node-source-map-support/actions?query=workflow%3A%22Continuous+Integration%22) + +This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process. + +## Installation and Usage + +#### Node support + +``` +$ npm install @cspotcode/source-map-support +``` + +Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler): + +``` +//# sourceMappingURL=path/to/source.map +``` + +If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be +respected (e.g. if a file mentions the comment in code, or went through multiple transpilers). +The path should either be absolute or relative to the compiled file. + +From here you have two options. + +##### CLI Usage + +```bash +node -r @cspotcode/source-map-support/register compiled.js +# Or to enable hookRequire +node -r @cspotcode/source-map-support/register-hook-require compiled.js +``` + +##### Programmatic Usage + +Put the following line at the top of the compiled file. + +```js +require('@cspotcode/source-map-support').install(); +``` + +It is also possible to install the source map support directly by +requiring the `register` module which can be handy with ES6: + +```js +import '@cspotcode/source-map-support/register' + +// Instead of: +import sourceMapSupport from '@cspotcode/source-map-support' +sourceMapSupport.install() +``` +Note: if you're using babel-register, it includes source-map-support already. + +It is also very useful with Mocha: + +``` +$ mocha --require @cspotcode/source-map-support/register tests/ +``` + +#### Browser support + +This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code. + +This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify. + +```html + + +``` + +This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency: + +```html + +``` + +## Options + +This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer: + +```js +require('@cspotcode/source-map-support').install({ + handleUncaughtExceptions: false +}); +``` + +This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access. + +```js +require('@cspotcode/source-map-support').install({ + retrieveSourceMap: function(source) { + if (source === 'compiled.js') { + return { + url: 'original.js', + map: fs.readFileSync('compiled.js.map', 'utf8') + }; + } + return null; + } +}); +``` + +The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment. +In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'. + +```js +require('@cspotcode/source-map-support').install({ + environment: 'node' +}); +``` + +To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps. + + +```js +require('@cspotcode/source-map-support').install({ + hookRequire: true +}); +``` + +This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage. + +## Demos + +#### Basic Demo + +original.js: + +```js +throw new Error('test'); // This is the original code +``` + +compiled.js: + +```js +require('@cspotcode/source-map-support').install(); + +throw new Error('test'); // This is the compiled code +// The next line defines the sourceMapping. +//# sourceMappingURL=compiled.js.map +``` + +compiled.js.map: + +```json +{ + "version": 3, + "file": "compiled.js", + "sources": ["original.js"], + "names": [], + "mappings": ";;AAAA,MAAM,IAAI" +} +``` + +Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js): + +``` +$ node compiled.js + +original.js:1 +throw new Error('test'); // This is the original code + ^ +Error: test + at Object. (original.js:1:7) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### TypeScript Demo + +demo.ts: + +```typescript +declare function require(name: string); +require('@cspotcode/source-map-support').install(); +class Foo { + constructor() { this.bar(); } + bar() { throw new Error('this is a demo'); } +} +new Foo(); +``` + +Compile and run the file using the TypeScript compiler from the terminal: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('@cspotcode/source-map-support').install()` in the code base: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node -r source-map-support/register demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### CoffeeScript Demo + +demo.coffee: + +```coffee +require('@cspotcode/source-map-support').install() +foo = -> + bar = -> throw new Error 'this is a demo' + bar() +foo() +``` + +Compile and run the file using the CoffeeScript compiler from the terminal: + +```sh +$ npm install @cspotcode/source-map-support coffeescript +$ node_modules/.bin/coffee --map --compile demo.coffee +$ node demo.js + +demo.coffee:3 + bar = -> throw new Error 'this is a demo' + ^ +Error: this is a demo + at bar (demo.coffee:3:22) + at foo (demo.coffee:4:3) + at Object. (demo.coffee:5:1) + at Object. (demo.coffee:1:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) +``` + +## Tests + +This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests: + +* Build the tests using `build.js` +* Launch the HTTP server (`npm run serve-tests`) and visit + * http://127.0.0.1:1336/amd-test + * http://127.0.0.1:1336/browser-test + * http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details). +* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/ + +## License + +This code is available under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/node_modules/@cspotcode/source-map-support/browser-source-map-support.js b/node_modules/@cspotcode/source-map-support/browser-source-map-support.js new file mode 100644 index 0000000..782da50 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/browser-source-map-support.js @@ -0,0 +1,114 @@ +/* + * Support for source maps in V8 stack traces + * https://github.com/evanw/node-source-map-support + */ +/* + The buffer module from node.js, for the browser. + + @author Feross Aboukhadijeh + license MIT +*/ +(this.define||function(R,U){this.sourceMapSupport=U()})("browser-source-map-support",function(R){(function e(C,J,A){function p(f,c){if(!J[f]){if(!C[f]){var l="function"==typeof require&&require;if(!c&&l)return l(f,!0);if(t)return t(f,!0);throw Error("Cannot find module '"+f+"'");}l=J[f]={exports:{}};C[f][0].call(l.exports,function(q){var r=C[f][1][q];return p(r?r:q)},l,l.exports,e,C,J,A)}return J[f].exports}for(var t="function"==typeof require&&require,m=0;mm)return-1;if(58>m)return m-48+52;if(91>m)return m-65;if(123>m)return m-97+26}var t="undefined"!==typeof Uint8Array?Uint8Array:Array;e.toByteArray=function(m){function f(d){q[k++]=d}if(0>16);f((u&65280)>>8);f(u&255)}2===l?(u=p(m.charAt(c))<<2|p(m.charAt(c+1))>>4,f(u&255)):1===l&&(u=p(m.charAt(c))<<10|p(m.charAt(c+1))<<4|p(m.charAt(c+2))>>2,f(u>>8&255),f(u&255));return q};e.fromByteArray=function(m){var f=m.length%3,c="",l;var q=0;for(l=m.length-f;q> +18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r&63);c+=r}switch(f){case 1:r=m[m.length-1];c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>2);c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<4&63);c+="==";break;case 2:r=(m[m.length-2]<<8)+ +m[m.length-1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>10),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>4&63),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<2&63),c+="="}return c}})("undefined"===typeof A?this.base64js={}:A)},{}],3:[function(C,J,A){},{}],4:[function(C,J,A){(function(e){var p=Object.prototype.toString,t="function"===typeof e.alloc&&"function"===typeof e.allocUnsafe&&"function"=== +typeof e.from;J.exports=function(m,f,c){if("number"===typeof m)throw new TypeError('"value" argument must not be a number');if("ArrayBuffer"===p.call(m).slice(8,-1)){f>>>=0;var l=m.byteLength-f;if(0>l)throw new RangeError("'offset' is out of bounds");if(void 0===c)c=l;else if(c>>>=0,c>l)throw new RangeError("'length' is out of bounds");return t?e.from(m.slice(f,f+c)):new e(new Uint8Array(m.slice(f,f+c)))}if("string"===typeof m){c=f;if("string"!==typeof c||""===c)c="utf8";if(!e.isEncoding(c))throw new TypeError('"encoding" must be a valid string encoding'); +return t?e.from(m,c):new e(m,c)}return t?e.from(m):new e(m)}}).call(this,C("buffer").Buffer)},{buffer:5}],5:[function(C,J,A){function e(a,b,h){if(!(this instanceof e))return new e(a,b,h);var w=typeof a;if("number"===w)var y=0>>0:0;else if("string"===w){if("base64"===b)for(a=(a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")).replace(L,"");0!==a.length%4;)a+="=";y=e.byteLength(a,b)}else if("object"===w&&null!==a)"Buffer"===a.type&&z(a.data)&&(a=a.data),y=0<+a.length?Math.floor(+a.length):0;else throw new TypeError("must start with number, buffer, array or string"); +if(this.length>G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");if(e.TYPED_ARRAY_SUPPORT)var I=e._augment(new Uint8Array(y));else I=this,I.length=y,I._isBuffer=!0;if(e.TYPED_ARRAY_SUPPORT&&"number"===typeof a.byteLength)I._set(a);else{var K=a;if(z(K)||e.isBuffer(K)||K&&"object"===typeof K&&"number"===typeof K.length)if(e.isBuffer(a))for(b=0;ba)throw new RangeError("offset is not uint");if(a+b>h)throw new RangeError("Trying to access beyond buffer length");}function m(a,b,h,w,y,I){if(!e.isBuffer(a))throw new TypeError("buffer must be a Buffer instance");if(b>y||ba.length)throw new TypeError("index out of range"); +}function f(a,b,h,w){0>b&&(b=65535+b+1);for(var y=0,I=Math.min(a.length-h,2);y>>8*(w?y:1-y)}function c(a,b,h,w){0>b&&(b=4294967295+b+1);for(var y=0,I=Math.min(a.length-h,4);y>>8*(w?y:3-y)&255}function l(a,b,h,w,y,I){if(b>y||ba.length)throw new TypeError("index out of range");}function q(a,b,h,w,y){y||l(a,b,h,4,3.4028234663852886E38,-3.4028234663852886E38);v.write(a,b,h,w,23,4);return h+4}function r(a, +b,h,w,y){y||l(a,b,h,8,1.7976931348623157E308,-1.7976931348623157E308);v.write(a,b,h,w,52,8);return h+8}function k(a){for(var b=[],h=0;h=w)b.push(w);else{var y=h;55296<=w&&57343>=w&&h++;w=encodeURIComponent(a.slice(y,h+1)).substr(1).split("%");for(y=0;y=b.length||y>=a.length);y++)b[y+ +h]=a[y];return y}function g(a){try{return decodeURIComponent(a)}catch(b){return String.fromCharCode(65533)}}var n=C("base64-js"),v=C("ieee754"),z=C("is-array");A.Buffer=e;A.SlowBuffer=e;A.INSPECT_MAX_BYTES=50;e.poolSize=8192;var G=1073741823;e.TYPED_ARRAY_SUPPORT=function(){try{var a=new ArrayBuffer(0),b=new Uint8Array(a);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray&&0===(new Uint8Array(1)).subarray(1,1).byteLength}catch(h){return!1}}();e.isBuffer=function(a){return!(null== +a||!a._isBuffer)};e.compare=function(a,b){if(!e.isBuffer(a)||!e.isBuffer(b))throw new TypeError("Arguments must be Buffers");for(var h=a.length,w=b.length,y=0,I=Math.min(h,w);y>>1;break;case "utf8":case "utf-8":h=k(a).length;break;case "base64":h=n.toByteArray(a).length; +break;default:h=a.length}return h};e.prototype.length=void 0;e.prototype.parent=void 0;e.prototype.toString=function(a,b,h){var w=!1;b>>>=0;h=void 0===h||Infinity===h?this.length:h>>>0;a||(a="utf8");0>b&&(b=0);h>this.length&&(h=this.length);if(h<=b)return"";for(;;)switch(a){case "hex":a=b;b=h;h=this.length;if(!a||0>a)a=0;if(!b||0>b||b>h)b=h;w="";for(h=a;hw?"0"+w.toString(16):w.toString(16),w=a+w;return w;case "utf8":case "utf-8":w=a="";for(h=Math.min(this.length,h);b= +this[b]?(a+=g(w)+String.fromCharCode(this[b]),w=""):w+="%"+this[b].toString(16);return a+g(w);case "ascii":return p(this,b,h);case "binary":return p(this,b,h);case "base64":return b=0===b&&h===this.length?n.fromByteArray(this):n.fromByteArray(this.slice(b,h)),b;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":b=this.slice(b,h);h="";for(a=0;ab&&(a+=" ... "));return""};e.prototype.compare=function(a){if(!e.isBuffer(a))throw new TypeError("Argument must be a Buffer");return e.compare(this,a)};e.prototype.get=function(a){console.log(".get() is deprecated. Access using array indexes instead."); +return this.readUInt8(a)};e.prototype.set=function(a,b){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(a,b)};e.prototype.write=function(a,b,h,w){if(isFinite(b))isFinite(h)||(w=h,h=void 0);else{var y=w;w=b;b=h;h=y}b=Number(b)||0;y=this.length-b;h?(h=Number(h),h>y&&(h=y)):h=y;w=String(w||"utf8").toLowerCase();switch(w){case "hex":b=Number(b)||0;w=this.length-b;h?(h=Number(h),h>w&&(h=w)):h=w;w=a.length;if(0!==w%2)throw Error("Invalid hex string");h>w/ +2&&(h=w/2);for(w=0;w>8;K%=256;y.push(K);y.push(w)}a=d(y,this,b,h,2);break;default:throw new TypeError("Unknown encoding: "+ +w);}return a};e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};e.prototype.slice=function(a,b){var h=this.length;a=~~a;b=void 0===b?h:~~b;0>a?(a+=h,0>a&&(a=0)):a>h&&(a=h);0>b?(b+=h,0>b&&(b=0)):b>h&&(b=h);b>>=0;h||m(this,a,b,1,255,0);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));this[b]=a;return b+1};e.prototype.writeUInt16LE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeUInt16BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeUInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b+3]=a>>>24,this[b+2]=a>>>16,this[b+1]=a>>>8,this[b]=a):c(this,a,b,!0);return b+4};e.prototype.writeUInt32BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeInt8=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,1,127,-128);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));0>a&&(a=255+a+1);this[b]=a;return b+1};e.prototype.writeInt16LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeInt16BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8,this[b+2]=a>>>16,this[b+3]=a>>>24):c(this,a,b,!0);return b+4};e.prototype.writeInt32BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);0>a&&(a=4294967295+a+1);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+ +2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeFloatLE=function(a,b,h){return q(this,a,b,!0,h)};e.prototype.writeFloatBE=function(a,b,h){return q(this,a,b,!1,h)};e.prototype.writeDoubleLE=function(a,b,h){return r(this,a,b,!0,h)};e.prototype.writeDoubleBE=function(a,b,h){return r(this,a,b,!1,h)};e.prototype.copy=function(a,b,h,w){h||(h=0);w||0===w||(w=this.length);b||(b=0);if(w!==h&&0!==a.length&&0!==this.length){if(wb||b>=a.length)throw new TypeError("targetStart out of bounds"); +if(0>h||h>=this.length)throw new TypeError("sourceStart out of bounds");if(0>w||w>this.length)throw new TypeError("sourceEnd out of bounds");w>this.length&&(w=this.length);a.length-bw||!e.TYPED_ARRAY_SUPPORT)for(var y=0;yb||b>=this.length)throw new TypeError("start out of bounds"); +if(0>h||h>this.length)throw new TypeError("end out of bounds");if("number"===typeof a)for(;b>1,r=-7;f=t?f-1:0;var k=t?-1:1,u=e[p+f];f+=k;t=u&(1<<-r)-1;u>>=-r;for(r+=c;0>=-r;for(r+=m;0>1,u=23===f?Math.pow(2,-24)-Math.pow(2,-77):0;c=m?0:c-1;var d=m?1:-1,g=0>p||0===p&&0>1/p?1:0;p=Math.abs(p);isNaN(p)||Infinity===p?(p=isNaN(p)?1:0,m=r):(m=Math.floor(Math.log(p)/Math.LN2),1>p*(l=Math.pow(2,-m))&&(m--,l*=2),p=1<=m+k?p+u/l:p+u*Math.pow(2,1-k),2<=p*l&&(m++,l/=2),m+k>=r?(p=0,m=r):1<=m+k?(p=(p*l-1)*Math.pow(2,f),m+=k):(p=p*Math.pow(2,k-1)*Math.pow(2,f),m=0));for(;8<=f;e[t+c]=p&255,c+= +d,p/=256,f-=8);m=m<z?[]:n.slice(v,z-v+1)}c=A.resolve(c).substr(1);l=A.resolve(l).substr(1); +for(var r=q(c.split("/")),k=q(l.split("/")),u=Math.min(r.length,k.length),d=u,g=0;gl&&(l=c.length+l);return c.substr(l,q)}}).call(this,C("g5I+bs"))},{"g5I+bs":9}],9:[function(C,J,A){function e(){}C=J.exports={};C.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(t){return window.setImmediate(t)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var p=[];window.addEventListener("message",function(t){var m=t.source;m!==window&&null!== +m||"process-tick"!==t.data||(t.stopPropagation(),0p?(-p<<1)+1:p<<1;do p=m&31,m>>>=5,0=f)throw Error("Expected more digits in base 64 VLQ value.");var q=e.decode(p.charCodeAt(t++));if(-1===q)throw Error("Invalid base64 digit: "+p.charAt(t-1));var r=!!(q&32);q&=31;c+=q<>1;m.value=1===(c&1)?-p:p;m.rest=t}},{"./base64":12}],12:[function(C, +J,A){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");A.encode=function(p){if(0<=p&&p=p?p-65:97<=p&&122>=p?p-97+26:48<=p&&57>=p?p-48+52:43==p?62:47==p?63:-1}},{}],13:[function(C,J,A){function e(p,t,m,f,c,l){var q=Math.floor((t-p)/2)+p,r=c(m,f[q],!0);return 0===r?q:0p?-1:p}A.GREATEST_LOWER_BOUND=1;A.LEAST_UPPER_BOUND=2;A.search=function(p,t,m,f){if(0===t.length)return-1;p=e(-1,t.length,p,t,m,f||A.GREATEST_LOWER_BOUND);if(0>p)return-1;for(;0<=p-1&&0===m(t[p],t[p-1],!0);)--p;return p}},{}],14:[function(C,J,A){function e(){this._array=[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var p=C("./util");e.prototype.unsortedForEach=function(t,m){this._array.forEach(t,m)};e.prototype.add=function(t){var m=this._last,f=m.generatedLine, +c=t.generatedLine,l=m.generatedColumn,q=t.generatedColumn;c>f||c==f&&q>=l||0>=p.compareByGeneratedPositionsInflated(m,t)?this._last=t:this._sorted=!1;this._array.push(t)};e.prototype.toArray=function(){this._sorted||(this._array.sort(p.compareByGeneratedPositionsInflated),this._sorted=!0);return this._array};A.MappingList=e},{"./util":19}],15:[function(C,J,A){function e(t,m,f){var c=t[m];t[m]=t[f];t[f]=c}function p(t,m,f,c){if(f=m(t[r],q)&&(l+=1,e(t,l,r));e(t,l+1,r);l+=1;p(t,m,f,l-1);p(t,m,l+1,c)}}A.quickSort=function(t,m){p(t,m,0,t.length-1)}},{}],16:[function(C,J,A){function e(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));return null!=d.sections?new m(d,u):new p(d,u)}function p(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version"),n=f.getArg(d,"sources"),v=f.getArg(d,"names",[]),z=f.getArg(d,"sourceRoot",null),G=f.getArg(d,"sourcesContent",null),D=f.getArg(d, +"mappings");d=f.getArg(d,"file",null);if(g!=this._version)throw Error("Unsupported version: "+g);z&&(z=f.normalize(z));n=n.map(String).map(f.normalize).map(function(L){return z&&f.isAbsolute(z)&&f.isAbsolute(L)?f.relative(z,L):L});this._names=l.fromArray(v.map(String),!0);this._sources=l.fromArray(n,!0);this.sourceRoot=z;this.sourcesContent=G;this._mappings=D;this._sourceMapURL=u;this.file=d}function t(){this.generatedColumn=this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source= +null}function m(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version");d=f.getArg(d,"sections");if(g!=this._version)throw Error("Unsupported version: "+g);this._sources=new l;this._names=new l;var n={line:-1,column:0};this._sections=d.map(function(v){if(v.url)throw Error("Support for url field in sections not implemented.");var z=f.getArg(v,"offset"),G=f.getArg(z,"line"),D=f.getArg(z,"column");if(G=k[d])throw new TypeError("Line must be greater than or equal to 1, got "+ +k[d]);if(0>k[g])throw new TypeError("Column must be greater than or equal to 0, got "+k[g]);return c.search(k,u,n,v)};p.prototype.computeColumnSpans=function(){for(var k=0;k=this._sources.size()&&!this.sourcesContent.some(function(k){return null==k}):!1};p.prototype.sourceContentFor=function(k,u){if(!this.sourcesContent)return null;var d=k;null!=this.sourceRoot&&(d=f.relative(this.sourceRoot,d));if(this._sources.has(d))return this.sourcesContent[this._sources.indexOf(d)]; +var g=this.sources,n;for(n=0;n +g||95!==d.charCodeAt(g-1)||95!==d.charCodeAt(g-2)||111!==d.charCodeAt(g-3)||116!==d.charCodeAt(g-4)||111!==d.charCodeAt(g-5)||114!==d.charCodeAt(g-6)||112!==d.charCodeAt(g-7)||95!==d.charCodeAt(g-8)||95!==d.charCodeAt(g-9))return!1;for(g-=10;0<=g;g--)if(36!==d.charCodeAt(g))return!1;return!0}function r(d,g){return d===g?0:null===d?1:null===g?-1:d>g?1:-1}A.getArg=function(d,g,n){if(g in d)return d[g];if(3===arguments.length)return n;throw Error('"'+g+'" is a required argument.');};var k=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/, +u=/^data:.+,.+$/;A.urlParse=e;A.urlGenerate=p;A.normalize=t;A.join=m;A.isAbsolute=function(d){return"/"===d.charAt(0)||k.test(d)};A.relative=function(d,g){""===d&&(d=".");d=d.replace(/\/$/,"");for(var n=0;0!==g.indexOf(d+"/");){var v=d.lastIndexOf("/");if(0>v)return g;d=d.slice(0,v);if(d.match(/^([^\/]+:\/)?\/*$/))return g;++n}return Array(n+1).join("../")+g.substr(d.length+1)};C=!("__proto__"in Object.create(null));A.toSetString=C?f:c;A.fromSetString=C?f:l;A.compareByOriginalPositions=function(d, +g,n){var v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;if(0!==v||n)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v)return v;v=d.generatedLine-g.generatedLine;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsDeflated=function(d,g,n){var v=d.generatedLine-g.generatedLine;if(0!==v)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v||n)return v;v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine- +g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsInflated=function(d,g){var n=d.generatedLine-g.generatedLine;if(0!==n)return n;n=d.generatedColumn-g.generatedColumn;if(0!==n)return n;n=r(d.source,g.source);if(0!==n)return n;n=d.originalLine-g.originalLine;if(0!==n)return n;n=d.originalColumn-g.originalColumn;return 0!==n?n:r(d.name,g.name)};A.parseSourceMapInput=function(d){return JSON.parse(d.replace(/^\)]}'[^\n]*\n/, +""))};A.computeSourceURL=function(d,g,n){g=g||"";d&&("/"!==d[d.length-1]&&"/"!==g[0]&&(d+="/"),g=d+g);if(n){d=e(n);if(!d)throw Error("sourceMapURL could not be parsed");d.path&&(n=d.path.lastIndexOf("/"),0<=n&&(d.path=d.path.substring(0,n+1)));g=m(p(d),g)}return t(g)}},{}],20:[function(C,J,A){A.SourceMapGenerator=C("./lib/source-map-generator").SourceMapGenerator;A.SourceMapConsumer=C("./lib/source-map-consumer").SourceMapConsumer;A.SourceNode=C("./lib/source-node").SourceNode},{"./lib/source-map-consumer":16, +"./lib/source-map-generator":17,"./lib/source-node":18}],21:[function(C,J,A){(function(e){function p(){return"browser"===a?!0:"node"===a?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type)}function t(x){return function(B){for(var F=0;F";B=this.getLineNumber();null!=B&&(x+=":"+B,(B= +this.getColumnNumber())&&(x+=":"+B))}B="";var F=this.getFunctionName(),E=!0,H=this.isConstructor();if(this.isToplevel()||H)H?B+="new "+(F||""):F?B+=F:(B+=x,E=!1);else{H=this.getTypeName();"[object Object]"===H&&(H="null");var M=this.getMethodName();F?(H&&0!=F.indexOf(H)&&(B+=H+"."),B+=F,M&&F.indexOf("."+M)!=F.length-M.length-1&&(B+=" [as "+M+"]")):B+=H+"."+(M||"")}E&&(B+=" ("+x+")");return B}function q(x){var B={};Object.getOwnPropertyNames(Object.getPrototypeOf(x)).forEach(function(F){B[F]= +/^(?:is|get)/.test(F)?function(){return x[F].call(x)}:x[F]});B.toString=l;return B}function r(x,B){void 0===B&&(B={nextPosition:null,curPosition:null});if(x.isNative())return B.curPosition=null,x;var F=x.getFileName()||x.getScriptNameOrSourceURL();if(F){var E=x.getLineNumber(),H=x.getColumnNumber()-1,M=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/,S=M.test;var V="object"===typeof e&&null!==e?e.version:"";M=S.call(M,V)?0:62;1===E&&H>M&&!p()&&!x.isEval()&&(H-=M);var O= +f({source:F,line:E,column:H});B.curPosition=O;x=q(x);var T=x.getFunctionName;x.getFunctionName=function(){return null==B.nextPosition?T():B.nextPosition.name||T()};x.getFileName=function(){return O.source};x.getLineNumber=function(){return O.line};x.getColumnNumber=function(){return O.column+1};x.getScriptNameOrSourceURL=function(){return O.source};return x}var Q=x.isEval()&&x.getEvalOrigin();Q&&(Q=c(Q),x=q(x),x.getEvalOrigin=function(){return Q});return x}function k(x,B){L&&(b={},h={});for(var F= +(x.name||"Error")+": "+(x.message||""),E={nextPosition:null,curPosition:null},H=[],M=B.length-1;0<=M;M--)H.push("\n at "+r(B[M],E)),E.nextPosition=E.curPosition;E.curPosition=E.nextPosition=null;return F+H.reverse().join("")}function u(x){var B=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(x.stack);if(B){x=B[1];var F=+B[2];B=+B[3];var E=b[x];if(!E&&v&&v.existsSync(x))try{E=v.readFileSync(x,"utf8")}catch(H){E=""}if(E&&(E=E.split(/(?:\r\n|\r|\n)/)[F-1]))return x+":"+F+"\n"+E+"\n"+Array(B).join(" ")+ +"^"}return null}function d(){var x=e.emit;e.emit=function(B){if("uncaughtException"===B){var F=arguments[1]&&arguments[1].stack,E=0=12" + }, + "volta": { + "node": "16.11.0", + "npm": "7.24.2" + } +} diff --git a/node_modules/@cspotcode/source-map-support/register-hook-require.d.ts b/node_modules/@cspotcode/source-map-support/register-hook-require.d.ts new file mode 100644 index 0000000..a787e69 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/register-hook-require.d.ts @@ -0,0 +1,7 @@ +// tslint:disable:no-useless-files + +// For following usage: +// import '@cspotcode/source-map-support/register-hook-require' +// Instead of: +// import sourceMapSupport from '@cspotcode/source-map-support' +// sourceMapSupport.install({hookRequire: true}) diff --git a/node_modules/@cspotcode/source-map-support/register-hook-require.js b/node_modules/@cspotcode/source-map-support/register-hook-require.js new file mode 100644 index 0000000..6bc12ab --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/register-hook-require.js @@ -0,0 +1,3 @@ +require('./').install({ + hookRequire: true +}); diff --git a/node_modules/@cspotcode/source-map-support/register.d.ts b/node_modules/@cspotcode/source-map-support/register.d.ts new file mode 100644 index 0000000..063cd7c --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/register.d.ts @@ -0,0 +1,7 @@ +// tslint:disable:no-useless-files + +// For following usage: +// import '@cspotcode/source-map-support/register' +// Instead of: +// import sourceMapSupport from '@cspotcode/source-map-support' +// sourceMapSupport.install() diff --git a/node_modules/@cspotcode/source-map-support/register.js b/node_modules/@cspotcode/source-map-support/register.js new file mode 100644 index 0000000..4f68e67 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/register.js @@ -0,0 +1 @@ +require('./').install(); diff --git a/node_modules/@cspotcode/source-map-support/source-map-support.d.ts b/node_modules/@cspotcode/source-map-support/source-map-support.d.ts new file mode 100644 index 0000000..d8cb9d8 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/source-map-support.d.ts @@ -0,0 +1,76 @@ +// Type definitions for source-map-support 0.5 +// Project: https://github.com/evanw/node-source-map-support +// Definitions by: Bart van der Schoor +// Jason Cheatham +// Alcedo Nathaniel De Guzman Jr +// Griffin Yourick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface RawSourceMap { + version: 3; + sources: string[]; + names: string[]; + sourceRoot?: string; + sourcesContent?: string[]; + mappings: string; + file: string; +} + +/** + * Output of retrieveSourceMap(). + * From source-map-support: + * The map field may be either a string or the parsed JSON object (i.e., + * it must be a valid argument to the SourceMapConsumer constructor). + */ +export interface UrlAndMap { + url: string; + map: string | RawSourceMap; +} + +/** + * Options to install(). + */ +export interface Options { + handleUncaughtExceptions?: boolean | undefined; + hookRequire?: boolean | undefined; + emptyCacheBetweenOperations?: boolean | undefined; + environment?: 'auto' | 'browser' | 'node' | undefined; + overrideRetrieveFile?: boolean | undefined; + overrideRetrieveSourceMap?: boolean | undefined; + retrieveFile?(path: string): string; + retrieveSourceMap?(source: string): UrlAndMap | null; + /** + * Set false to disable redirection of require / import `source-map-support` to `@cspotcode/source-map-support` + */ + redirectConflictingLibrary?: boolean; + /** + * Callback will be called every time we redirect due to `redirectConflictingLibrary` + * This allows consumers to log helpful warnings if they choose. + * @param parent NodeJS.Module which made the require() or require.resolve() call + * @param options options object internally passed to node's `_resolveFilename` hook + */ + onConflictingLibraryRedirect?: (request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void; +} + +export interface Position { + source: string; + line: number; + column: number; +} + +export function wrapCallSite(frame: any /* StackFrame */): any /* StackFrame */; +export function getErrorSource(error: Error): string | null; +export function mapSourcePosition(position: Position): Position; +export function retrieveSourceMap(source: string): UrlAndMap | null; +export function resetRetrieveHandlers(): void; + +/** + * Install SourceMap support. + * @param options Can be used to e.g. disable uncaughtException handler. + */ +export function install(options?: Options): void; + +/** + * Uninstall SourceMap support. + */ +export function uninstall(): void; diff --git a/node_modules/@cspotcode/source-map-support/source-map-support.js b/node_modules/@cspotcode/source-map-support/source-map-support.js new file mode 100644 index 0000000..ad830b6 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/source-map-support.js @@ -0,0 +1,938 @@ +const { TraceMap, originalPositionFor, AnyMap } = require('@jridgewell/trace-mapping'); +var path = require('path'); +const { fileURLToPath, pathToFileURL } = require('url'); +var util = require('util'); + +var fs; +try { + fs = require('fs'); + if (!fs.existsSync || !fs.readFileSync) { + // fs doesn't have all methods we need + fs = null; + } +} catch (err) { + /* nop */ +} + +/** + * Requires a module which is protected against bundler minification. + * + * @param {NodeModule} mod + * @param {string} request + */ +function dynamicRequire(mod, request) { + return mod.require(request); +} + +/** + * @typedef {{ + * enabled: boolean; + * originalValue: any; + * installedValue: any; + * }} HookState + * Used for installing and uninstalling hooks + */ + +// Increment this if the format of sharedData changes in a breaking way. +var sharedDataVersion = 1; + +/** + * @template T + * @param {T} defaults + * @returns {T} + */ +function initializeSharedData(defaults) { + var sharedDataKey = 'source-map-support/sharedData'; + if (typeof Symbol !== 'undefined') { + sharedDataKey = Symbol.for(sharedDataKey); + } + var sharedData = this[sharedDataKey]; + if (!sharedData) { + sharedData = { version: sharedDataVersion }; + if (Object.defineProperty) { + Object.defineProperty(this, sharedDataKey, { value: sharedData }); + } else { + this[sharedDataKey] = sharedData; + } + } + if (sharedDataVersion !== sharedData.version) { + throw new Error("Multiple incompatible instances of source-map-support were loaded"); + } + for (var key in defaults) { + if (!(key in sharedData)) { + sharedData[key] = defaults[key]; + } + } + return sharedData; +} + +// If multiple instances of source-map-support are loaded into the same +// context, they shouldn't overwrite each other. By storing handlers, caches, +// and other state on a shared object, different instances of +// source-map-support can work together in a limited way. This does require +// that future versions of source-map-support continue to support the fields on +// this object. If this internal contract ever needs to be broken, increment +// sharedDataVersion. (This version number is not the same as any of the +// package's version numbers, which should reflect the *external* API of +// source-map-support.) +var sharedData = initializeSharedData({ + + // Only install once if called multiple times + // Remember how the environment looked before installation so we can restore if able + /** @type {HookState} */ + errorPrepareStackTraceHook: undefined, + /** @type {HookState} */ + processEmitHook: undefined, + /** @type {HookState} */ + moduleResolveFilenameHook: undefined, + + /** @type {Array<(request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void>} */ + onConflictingLibraryRedirectArr: [], + + // If true, the caches are reset before a stack trace formatting operation + emptyCacheBetweenOperations: false, + + // Maps a file path to a string containing the file contents + fileContentsCache: Object.create(null), + + // Maps a file path to a source map for that file + /** @type {Record C:/dir/file + '/'; // file:///root-dir/file -> /root-dir/file + }); + } + const key = getCacheKey(path); + if(hasFileContentsCacheFromKey(key)) { + return getFileContentsCacheFromKey(key); + } + + var contents = ''; + try { + if (!fs) { + // Use SJAX if we are in the browser + var xhr = new XMLHttpRequest(); + xhr.open('GET', path, /** async */ false); + xhr.send(null); + if (xhr.readyState === 4 && xhr.status === 200) { + contents = xhr.responseText; + } + } else if (fs.existsSync(path)) { + // Otherwise, use the filesystem + contents = fs.readFileSync(path, 'utf8'); + } + } catch (er) { + /* ignore any errors */ + } + + return setFileContentsCache(path, contents); +}); + +// Support URLs relative to a directory, but be careful about a protocol prefix +// in case we are in the browser (i.e. directories may start with "http://" or "file:///") +function supportRelativeURL(file, url) { + if(!file) return url; + // given that this happens within error formatting codepath, probably best to + // fallback instead of throwing if anything goes wrong + try { + // if should output a URL + if(isAbsoluteUrl(file) || isSchemeRelativeUrl(file)) { + if(isAbsoluteUrl(url) || isSchemeRelativeUrl(url)) { + return new URL(url, file).toString(); + } + if(path.isAbsolute(url)) { + return new URL(pathToFileURL(url), file).toString(); + } + // url is relative path or URL + return new URL(url.replace(/\\/g, '/'), file).toString(); + } + // if should output a path (unless URL is something like https://) + if(path.isAbsolute(file)) { + if(isFileUrl(url)) { + return fileURLToPath(url); + } + if(isSchemeRelativeUrl(url)) { + return fileURLToPath(new URL(url, 'file://')); + } + if(isAbsoluteUrl(url)) { + // url is a non-file URL + // Go with the URL + return url; + } + if(path.isAbsolute(url)) { + // Normalize at all? decodeURI or normalize slashes? + return path.normalize(url); + } + // url is relative path or URL + return path.join(file, '..', decodeURI(url)); + } + // If we get here, file is relative. + // Shouldn't happen since node identifies modules with absolute paths or URLs. + // But we can take a stab at returning something meaningful anyway. + if(isAbsoluteUrl(url) || isSchemeRelativeUrl(url)) { + return url; + } + return path.join(file, '..', url); + } catch(e) { + return url; + } +} + +// Return pathOrUrl in the same style as matchStyleOf: either a file URL or a native path +function matchStyleOfPathOrUrl(matchStyleOf, pathOrUrl) { + try { + if(isAbsoluteUrl(matchStyleOf) || isSchemeRelativeUrl(matchStyleOf)) { + if(isAbsoluteUrl(pathOrUrl) || isSchemeRelativeUrl(pathOrUrl)) return pathOrUrl; + if(path.isAbsolute(pathOrUrl)) return pathToFileURL(pathOrUrl).toString(); + } else if(path.isAbsolute(matchStyleOf)) { + if(isAbsoluteUrl(pathOrUrl) || isSchemeRelativeUrl(pathOrUrl)) { + return fileURLToPath(new URL(pathOrUrl, 'file://')); + } + } + return pathOrUrl; + } catch(e) { + return pathOrUrl; + } +} + +function retrieveSourceMapURL(source) { + var fileData; + + if (isInBrowser()) { + try { + var xhr = new XMLHttpRequest(); + xhr.open('GET', source, false); + xhr.send(null); + fileData = xhr.readyState === 4 ? xhr.responseText : null; + + // Support providing a sourceMappingURL via the SourceMap header + var sourceMapHeader = xhr.getResponseHeader("SourceMap") || + xhr.getResponseHeader("X-SourceMap"); + if (sourceMapHeader) { + return sourceMapHeader; + } + } catch (e) { + } + } + + // Get the URL of the source map + fileData = retrieveFile(tryFileURLToPath(source)); + var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg; + // Keep executing the search to find the *last* sourceMappingURL to avoid + // picking up sourceMappingURLs from comments, strings, etc. + var lastMatch, match; + while (match = re.exec(fileData)) lastMatch = match; + if (!lastMatch) return null; + return lastMatch[1]; +}; + +// Can be overridden by the retrieveSourceMap option to install. Takes a +// generated source filename; returns a {map, optional url} object, or null if +// there is no source map. The map field may be either a string or the parsed +// JSON object (ie, it must be a valid argument to the SourceMapConsumer +// constructor). +/** @type {(source: string) => import('./source-map-support').UrlAndMap | null} */ +var retrieveSourceMap = handlerExec(sharedData.retrieveMapHandlers, sharedData.internalRetrieveMapHandlers); +sharedData.internalRetrieveMapHandlers.push(function(source) { + var sourceMappingURL = retrieveSourceMapURL(source); + if (!sourceMappingURL) return null; + + // Read the contents of the source map + var sourceMapData; + if (reSourceMap.test(sourceMappingURL)) { + // Support source map URL as a data url + var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1); + sourceMapData = Buffer.from(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + // Support source map URLs relative to the source URL + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(tryFileURLToPath(sourceMappingURL)); + } + + if (!sourceMapData) { + return null; + } + + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); + +function mapSourcePosition(position) { + var sourceMap = getSourceMapCache(position.source); + if (!sourceMap) { + // Call the (overrideable) retrieveSourceMap function to get the source map. + var urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap) { + sourceMap = setSourceMapCache(position.source, { + url: urlAndMap.url, + map: new AnyMap(urlAndMap.map, urlAndMap.url) + }); + + // Overwrite trace-mapping's resolutions, because they do not handle + // Windows paths the way we want. + // TODO Remove now that windows path support was added to resolve-uri and thus trace-mapping? + sourceMap.map.resolvedSources = sourceMap.map.sources.map(s => supportRelativeURL(sourceMap.url, s)); + + // Load all sources stored inline with the source map into the file cache + // to pretend like they are already loaded. They may not exist on disk. + if (sourceMap.map.sourcesContent) { + sourceMap.map.resolvedSources.forEach(function(resolvedSource, i) { + var contents = sourceMap.map.sourcesContent[i]; + if (contents) { + setFileContentsCache(resolvedSource, contents); + } + }); + } + } else { + sourceMap = setSourceMapCache(position.source, { + url: null, + map: null + }); + } + } + + // Resolve the source URL relative to the URL of the source map + if (sourceMap && sourceMap.map) { + var originalPosition = originalPositionFor(sourceMap.map, position); + + // Only return the original position if a matching line was found. If no + // matching line is found then we return position instead, which will cause + // the stack trace to print the path and line for the compiled file. It is + // better to give a precise location in the compiled file than a vague + // location in the original file. + if (originalPosition.source !== null) { + // originalPosition.source has *already* been resolved against sourceMap.url + // so is *already* as absolute as possible. + // However, we want to ensure we output in same format as input: URL or native path + originalPosition.source = matchStyleOfPathOrUrl( + position.source, originalPosition.source); + return originalPosition; + } + } + + return position; +} + +// Parses code generated by FormatEvalOrigin(), a function inside V8: +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +function mapEvalOrigin(origin) { + // Most eval() calls are in this format + var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + var position = mapSourcePosition({ + source: match[2], + line: +match[3], + column: match[4] - 1 + }); + return 'eval at ' + match[1] + ' (' + position.source + ':' + + position.line + ':' + (position.column + 1) + ')'; + } + + // Parse nested eval() calls using recursion + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) { + return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')'; + } + + // Make sure we still return useful information if we didn't find anything + return origin; +} + +// This is copied almost verbatim from the V8 source code at +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +// Update 2022-04-29: +// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/builtins/builtins-callsite.cc#L175-L179 +// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/objects/call-site-info.cc#L795-L804 +// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/objects/call-site-info.cc#L717-L750 +// The implementation of wrapCallSite() used to just forward to the actual source +// code of CallSite.prototype.toString but unfortunately a new release of V8 +// did something to the prototype chain and broke the shim. The only fix I +// could find was copy/paste. +function CallSiteToString() { + var fileName; + var fileLocation = ""; + if (this.isNative()) { + fileLocation = "native"; + } else { + fileName = this.getScriptNameOrSourceURL(); + if (!fileName && this.isEval()) { + fileLocation = this.getEvalOrigin(); + fileLocation += ", "; // Expecting source position to follow. + } + + if (fileName) { + fileLocation += fileName; + } else { + // Source code does not originate from a file and is not native, but we + // can still get the source position inside the source string, e.g. in + // an eval string. + fileLocation += ""; + } + var lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += ":" + lineNumber; + var columnNumber = this.getColumnNumber(); + if (columnNumber) { + fileLocation += ":" + columnNumber; + } + } + } + + var line = ""; + var isAsync = this.isAsync ? this.isAsync() : false; + if(isAsync) { + line += 'async '; + var isPromiseAll = this.isPromiseAll ? this.isPromiseAll() : false; + var isPromiseAny = this.isPromiseAny ? this.isPromiseAny() : false; + if(isPromiseAny || isPromiseAll) { + line += isPromiseAll ? 'Promise.all (index ' : 'Promise.any (index '; + var promiseIndex = this.getPromiseIndex(); + line += promiseIndex + ')'; + } + } + var functionName = this.getFunctionName(); + var addSuffix = true; + var isConstructor = this.isConstructor(); + var isMethodCall = !(this.isToplevel() || isConstructor); + if (isMethodCall) { + var typeName = this.getTypeName(); + // Fixes shim to be backward compatable with Node v0 to v4 + if (typeName === "[object Object]") { + typeName = "null"; + } + var methodName = this.getMethodName(); + if (functionName) { + if (typeName && functionName.indexOf(typeName) != 0) { + line += typeName + "."; + } + line += functionName; + if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) { + line += " [as " + methodName + "]"; + } + } else { + line += typeName + "." + (methodName || ""); + } + } else if (isConstructor) { + line += "new " + (functionName || ""); + } else if (functionName) { + line += functionName; + } else { + line += fileLocation; + addSuffix = false; + } + if (addSuffix) { + line += " (" + fileLocation + ")"; + } + return line; +} + +function cloneCallSite(frame) { + var object = {}; + Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { + object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; + }); + object.toString = CallSiteToString; + return object; +} + +function wrapCallSite(frame, state) { + // provides interface backward compatibility + if (state === undefined) { + state = { nextPosition: null, curPosition: null } + } + if(frame.isNative()) { + state.curPosition = null; + return frame; + } + + // Most call sites will return the source file from getFileName(), but code + // passed to eval() ending in "//# sourceURL=..." will return the source file + // from getScriptNameOrSourceURL() instead + var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + // v8 does not expose its internal isWasm, etc methods, so we do this instead. + if(source.startsWith('wasm://')) { + state.curPosition = null; + return frame; + } + + var line = frame.getLineNumber(); + var column = frame.getColumnNumber() - 1; + + // Fix position in Node where some (internal) code is prepended. + // See https://github.com/evanw/node-source-map-support/issues/36 + // Header removed in node at ^10.16 || >=11.11.0 + // v11 is not an LTS candidate, we can just test the one version with it. + // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11 + var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/; + var headerLength = noHeader.test(process.version) ? 0 : 62; + if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) { + column -= headerLength; + } + + var position = mapSourcePosition({ + source: source, + line: line, + column: column + }); + state.curPosition = position; + frame = cloneCallSite(frame); + var originalFunctionName = frame.getFunctionName; + frame.getFunctionName = function() { + if (state.nextPosition == null) { + return originalFunctionName(); + } + return state.nextPosition.name || originalFunctionName(); + }; + frame.getFileName = function() { return position.source; }; + frame.getLineNumber = function() { return position.line; }; + frame.getColumnNumber = function() { return position.column + 1; }; + frame.getScriptNameOrSourceURL = function() { return position.source; }; + return frame; + } + + // Code called using eval() needs special handling + var origin = frame.isEval() && frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(origin); + frame = cloneCallSite(frame); + frame.getEvalOrigin = function() { return origin; }; + return frame; + } + + // If we get here then we were unable to change the source position + return frame; +} + +var kIsNodeError = undefined; +try { + // Get a deliberate ERR_INVALID_ARG_TYPE + // TODO is there a better way to reliably get an instance of NodeError? + path.resolve(123); +} catch(e) { + const symbols = Object.getOwnPropertySymbols(e); + const symbol = symbols.find(function (s) {return s.toString().indexOf('kIsNodeError') >= 0}); + if(symbol) kIsNodeError = symbol; +} + +const ErrorPrototypeToString = (err) =>Error.prototype.toString.call(err); + +/** @param {HookState} hookState */ +function createPrepareStackTrace(hookState) { + return prepareStackTrace; + + // This function is part of the V8 stack trace API, for more info see: + // https://v8.dev/docs/stack-trace-api + function prepareStackTrace(error, stack) { + if(!hookState.enabled) return hookState.originalValue.apply(this, arguments); + + if (sharedData.emptyCacheBetweenOperations) { + clearCaches(); + } + + // node gives its own errors special treatment. Mimic that behavior + // https://github.com/nodejs/node/blob/3cbaabc4622df1b4009b9d026a1a970bdbae6e89/lib/internal/errors.js#L118-L128 + // https://github.com/nodejs/node/pull/39182 + var errorString; + if (kIsNodeError) { + if(kIsNodeError in error) { + errorString = `${error.name} [${error.code}]: ${error.message}`; + } else { + errorString = ErrorPrototypeToString(error); + } + } else { + var name = error.name || 'Error'; + var message = error.message || ''; + errorString = message ? name + ": " + message : name; + } + + var state = { nextPosition: null, curPosition: null }; + var processedStack = []; + for (var i = stack.length - 1; i >= 0; i--) { + processedStack.push('\n at ' + wrapCallSite(stack[i], state)); + state.nextPosition = state.curPosition; + } + state.curPosition = state.nextPosition = null; + return errorString + processedStack.reverse().join(''); + } +} + +// Generate position and snippet of original source with pointer +function getErrorSource(error) { + var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); + if (match) { + var source = match[1]; + var line = +match[2]; + var column = +match[3]; + + // Support the inline sourceContents inside the source map + var contents = getFileContentsCache(source); + + const sourceAsPath = tryFileURLToPath(source); + + // Support files on disk + if (!contents && fs && fs.existsSync(sourceAsPath)) { + try { + contents = fs.readFileSync(sourceAsPath, 'utf8'); + } catch (er) { + contents = ''; + } + } + + // Format the line from the original source code like node does + if (contents) { + var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; + if (code) { + return source + ':' + line + '\n' + code + '\n' + + new Array(column).join(' ') + '^'; + } + } + } + return null; +} + +function printFatalErrorUponExit (error) { + var source = getErrorSource(error); + + // Ensure error is printed synchronously and not truncated + if (process.stderr._handle && process.stderr._handle.setBlocking) { + process.stderr._handle.setBlocking(true); + } + + if (source) { + console.error(source); + } + + // Matches node's behavior for colorized output + console.error( + util.inspect(error, { + customInspect: false, + colors: process.stderr.isTTY + }) + ); +} + +function shimEmitUncaughtException () { + const originalValue = process.emit; + var hook = sharedData.processEmitHook = { + enabled: true, + originalValue, + installedValue: undefined + }; + var isTerminatingDueToFatalException = false; + var fatalException; + + process.emit = sharedData.processEmitHook.installedValue = function (type) { + const hadListeners = originalValue.apply(this, arguments); + if(hook.enabled) { + if (type === 'uncaughtException' && !hadListeners) { + isTerminatingDueToFatalException = true; + fatalException = arguments[1]; + process.exit(1); + } + if (type === 'exit' && isTerminatingDueToFatalException) { + printFatalErrorUponExit(fatalException); + } + } + return hadListeners; + }; +} + +var originalRetrieveFileHandlers = sharedData.retrieveFileHandlers.slice(0); +var originalRetrieveMapHandlers = sharedData.retrieveMapHandlers.slice(0); + +exports.wrapCallSite = wrapCallSite; +exports.getErrorSource = getErrorSource; +exports.mapSourcePosition = mapSourcePosition; +exports.retrieveSourceMap = retrieveSourceMap; + +exports.install = function(options) { + options = options || {}; + + if (options.environment) { + environment = options.environment; + if (["node", "browser", "auto"].indexOf(environment) === -1) { + throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}") + } + } + + // Use dynamicRequire to avoid including in browser bundles + var Module = dynamicRequire(module, 'module'); + + // Redirect subsequent imports of "source-map-support" + // to this package + const {redirectConflictingLibrary = true, onConflictingLibraryRedirect} = options; + if(redirectConflictingLibrary) { + if (!sharedData.moduleResolveFilenameHook) { + const originalValue = Module._resolveFilename; + const moduleResolveFilenameHook = sharedData.moduleResolveFilenameHook = { + enabled: true, + originalValue, + installedValue: undefined, + } + Module._resolveFilename = sharedData.moduleResolveFilenameHook.installedValue = function (request, parent, isMain, options) { + if (moduleResolveFilenameHook.enabled) { + // Match all source-map-support entrypoints: source-map-support, source-map-support/register + let requestRedirect; + if (request === 'source-map-support') { + requestRedirect = './'; + } else if (request === 'source-map-support/register') { + requestRedirect = './register'; + } + + if (requestRedirect !== undefined) { + const newRequest = require.resolve(requestRedirect); + for (const cb of sharedData.onConflictingLibraryRedirectArr) { + cb(request, parent, isMain, options, newRequest); + } + request = newRequest; + } + } + + return originalValue.call(this, request, parent, isMain, options); + } + } + if (onConflictingLibraryRedirect) { + sharedData.onConflictingLibraryRedirectArr.push(onConflictingLibraryRedirect); + } + } + + // Allow sources to be found by methods other than reading the files + // directly from disk. + if (options.retrieveFile) { + if (options.overrideRetrieveFile) { + sharedData.retrieveFileHandlers.length = 0; + } + + sharedData.retrieveFileHandlers.unshift(options.retrieveFile); + } + + // Allow source maps to be found by methods other than reading the files + // directly from disk. + if (options.retrieveSourceMap) { + if (options.overrideRetrieveSourceMap) { + sharedData.retrieveMapHandlers.length = 0; + } + + sharedData.retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + + // Support runtime transpilers that include inline source maps + if (options.hookRequire && !isInBrowser()) { + var $compile = Module.prototype._compile; + + if (!$compile.__sourceMapSupport) { + Module.prototype._compile = function(content, filename) { + setFileContentsCache(filename, content); + setSourceMapCache(filename, undefined); + return $compile.call(this, content, filename); + }; + + Module.prototype._compile.__sourceMapSupport = true; + } + } + + // Configure options + if (!sharedData.emptyCacheBetweenOperations) { + sharedData.emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? + options.emptyCacheBetweenOperations : false; + } + + + // Install the error reformatter + if (!sharedData.errorPrepareStackTraceHook) { + const originalValue = Error.prepareStackTrace; + sharedData.errorPrepareStackTraceHook = { + enabled: true, + originalValue, + installedValue: undefined + }; + Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.installedValue = createPrepareStackTrace(sharedData.errorPrepareStackTraceHook); + } + + if (!sharedData.processEmitHook) { + var installHandler = 'handleUncaughtExceptions' in options ? + options.handleUncaughtExceptions : true; + + // Do not override 'uncaughtException' with our own handler in Node.js + // Worker threads. Workers pass the error to the main thread as an event, + // rather than printing something to stderr and exiting. + try { + // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify. + var worker_threads = dynamicRequire(module, 'worker_threads'); + if (worker_threads.isMainThread === false) { + installHandler = false; + } + } catch(e) {} + + // Provide the option to not install the uncaught exception handler. This is + // to support other uncaught exception handlers (in test frameworks, for + // example). If this handler is not installed and there are no other uncaught + // exception handlers, uncaught exceptions will be caught by node's built-in + // exception handler and the process will still be terminated. However, the + // generated JavaScript code will be shown above the stack trace instead of + // the original source code. + if (installHandler && hasGlobalProcessEventEmitter()) { + shimEmitUncaughtException(); + } + } +}; + +exports.uninstall = function() { + if(sharedData.processEmitHook) { + // Disable behavior + sharedData.processEmitHook.enabled = false; + // If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us. + if(process.emit === sharedData.processEmitHook.installedValue) { + process.emit = sharedData.processEmitHook.originalValue; + } + sharedData.processEmitHook = undefined; + } + if(sharedData.errorPrepareStackTraceHook) { + // Disable behavior + sharedData.errorPrepareStackTraceHook.enabled = false; + // If possible or necessary, remove our hook function. + // In vanilla environments, prepareStackTrace is `undefined`. + // We cannot delegate to `undefined` the way we can to a function w/`.apply()`; our only option is to remove the function. + // If we are the *first* hook installed, and another was installed on top of us, we have no choice but to remove both. + if(Error.prepareStackTrace === sharedData.errorPrepareStackTraceHook.installedValue || typeof sharedData.errorPrepareStackTraceHook.originalValue !== 'function') { + Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.originalValue; + } + sharedData.errorPrepareStackTraceHook = undefined; + } + if (sharedData.moduleResolveFilenameHook) { + // Disable behavior + sharedData.moduleResolveFilenameHook.enabled = false; + // If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us. + var Module = dynamicRequire(module, 'module'); + if(Module._resolveFilename === sharedData.moduleResolveFilenameHook.installedValue) { + Module._resolveFilename = sharedData.moduleResolveFilenameHook.originalValue; + } + sharedData.moduleResolveFilenameHook = undefined; + } + sharedData.onConflictingLibraryRedirectArr.length = 0; +} + +exports.resetRetrieveHandlers = function() { + sharedData.retrieveFileHandlers.length = 0; + sharedData.retrieveMapHandlers.length = 0; +} diff --git a/node_modules/@jridgewell/resolve-uri/LICENSE b/node_modules/@jridgewell/resolve-uri/LICENSE new file mode 100644 index 0000000..0a81b2a --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/LICENSE @@ -0,0 +1,19 @@ +Copyright 2019 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/README.md b/node_modules/@jridgewell/resolve-uri/README.md new file mode 100644 index 0000000..2fe70df --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/README.md @@ -0,0 +1,40 @@ +# @jridgewell/resolve-uri + +> Resolve a URI relative to an optional base URI + +Resolve any combination of absolute URIs, protocol-realtive URIs, absolute paths, or relative paths. + +## Installation + +```sh +npm install @jridgewell/resolve-uri +``` + +## Usage + +```typescript +function resolve(input: string, base?: string): string; +``` + +```js +import resolve from '@jridgewell/resolve-uri'; + +resolve('foo', 'https://example.com'); // => 'https://example.com/foo' +``` + +| Input | Base | Resolution | Explanation | +|-----------------------|-------------------------|--------------------------------|--------------------------------------------------------------| +| `https://example.com` | _any_ | `https://example.com/` | Input is normalized only | +| `//example.com` | `https://base.com/` | `https://example.com/` | Input inherits the base's protocol | +| `//example.com` | _rest_ | `//example.com/` | Input is normalized only | +| `/example` | `https://base.com/` | `https://base.com/example` | Input inherits the base's origin | +| `/example` | `//base.com/` | `//base.com/example` | Input inherits the base's host and remains protocol relative | +| `/example` | _rest_ | `/example` | Input is normalized only | +| `example` | `https://base.com/dir/` | `https://base.com/dir/example` | Input is joined with the base | +| `example` | `https://base.com/file` | `https://base.com/example` | Input is joined with the base without its file | +| `example` | `//base.com/dir/` | `//base.com/dir/example` | Input is joined with the base's last directory | +| `example` | `//base.com/file` | `//base.com/example` | Input is joined with the base without its file | +| `example` | `/base/dir/` | `/base/dir/example` | Input is joined with the base's last directory | +| `example` | `/base/file` | `/base/example` | Input is joined with the base without its file | +| `example` | `base/dir/` | `base/dir/example` | Input is joined with the base's last directory | +| `example` | `base/file` | `base/example` | Input is joined with the base without its file | diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs new file mode 100644 index 0000000..e958e88 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs @@ -0,0 +1,232 @@ +// Matches the scheme of a URL, eg "http://" +const schemeRegex = /^[\w+.-]+:\/\//; +/** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ +const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; +/** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ +const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; +function isAbsoluteUrl(input) { + return schemeRegex.test(input); +} +function isSchemeRelativeUrl(input) { + return input.startsWith('//'); +} +function isAbsolutePath(input) { + return input.startsWith('/'); +} +function isFileUrl(input) { + return input.startsWith('file:'); +} +function isRelative(input) { + return /^[.?#]/.test(input); +} +function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); +} +function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); +} +function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; +} +function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} +function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } +} +/** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ +function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; +} +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +export { resolve as default }; +//# sourceMappingURL=resolve-uri.mjs.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map new file mode 100644 index 0000000..1de97d0 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.mjs","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"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AI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;KACpF;AACH;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js new file mode 100644 index 0000000..a783049 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js @@ -0,0 +1,240 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resolveURI = factory()); +})(this, (function () { 'use strict'; + + // Matches the scheme of a URL, eg "http://" + const schemeRegex = /^[\w+.-]+:\/\//; + /** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ + const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; + /** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ + const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; + function isAbsoluteUrl(input) { + return schemeRegex.test(input); + } + function isSchemeRelativeUrl(input) { + return input.startsWith('//'); + } + function isAbsolutePath(input) { + return input.startsWith('/'); + } + function isFileUrl(input) { + return input.startsWith('file:'); + } + function isRelative(input) { + return /^[.?#]/.test(input); + } + function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); + } + function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); + } + function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; + } + function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; + } + function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } + } + /** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ + function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; + } + /** + * Attempts to resolve `input` URL/path relative to `base`. + */ + function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } + } + + return resolve; + +})); +//# sourceMappingURL=resolve-uri.umd.js.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map new file mode 100644 index 0000000..70a37f2 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.umd.js","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":";;;;;;IAAA;IACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;IAErC;;;;;;;;;;IAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;IAE5F;;;;;;;;;IASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;IAuBpF,SAAS,aAAa,CAAC,KAAa;QAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,SAAS,mBAAmB,CAAC,KAAa;QACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;IAED,SAAS,cAAc,CAAC,KAAa;QACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAED,SAAS,SAAS,CAAC,KAAa;QAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACnC,CAAC;IAED,SAAS,UAAU,CAAC,KAAa;QAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED,SAAS,gBAAgB,CAAC,KAAa;QACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;QACpC,OAAO,OAAO,CACZ,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,GAAG,EACf,KAAK,CAAC,CAAC,CA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KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;oBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;iBAChC;gBAED,OAAO,IAAI,GAAG,SAAS,CAAC;aACzB;YAED;gBACE,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;YAE9B;gBACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;SACpF;IACH;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts new file mode 100644 index 0000000..b7f0b3b --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts @@ -0,0 +1,4 @@ +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/resolve-uri/package.json b/node_modules/@jridgewell/resolve-uri/package.json new file mode 100644 index 0000000..02a4c51 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/package.json @@ -0,0 +1,69 @@ +{ + "name": "@jridgewell/resolve-uri", + "version": "3.1.2", + "description": "Resolve a URI relative to an optional base URI", + "keywords": [ + "resolve", + "uri", + "url", + "path" + ], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/resolve-uri", + "main": "dist/resolve-uri.umd.js", + "module": "dist/resolve-uri.mjs", + "types": "dist/types/resolve-uri.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/resolve-uri.d.ts", + "browser": "./dist/resolve-uri.umd.js", + "require": "./dist/resolve-uri.umd.js", + "import": "./dist/resolve-uri.mjs" + }, + "./dist/resolve-uri.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@jridgewell/resolve-uri-latest": "npm:@jridgewell/resolve-uri@*", + "@rollup/plugin-typescript": "8.3.0", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "c8": "7.11.0", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.66.0", + "typescript": "4.5.5" + } +} diff --git a/node_modules/@jridgewell/sourcemap-codec/LICENSE b/node_modules/@jridgewell/sourcemap-codec/LICENSE new file mode 100644 index 0000000..1f6ce94 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/LICENSE @@ -0,0 +1,19 @@ +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@jridgewell/sourcemap-codec/README.md b/node_modules/@jridgewell/sourcemap-codec/README.md new file mode 100644 index 0000000..b3e0708 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/README.md @@ -0,0 +1,264 @@ +# @jridgewell/sourcemap-codec + +Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). + + +## Why? + +Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap. + +This package makes the process slightly easier. + + +## Installation + +```bash +npm install @jridgewell/sourcemap-codec +``` + + +## Usage + +```js +import { encode, decode } from '@jridgewell/sourcemap-codec'; + +var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); + +assert.deepEqual( decoded, [ + // the first line (of the generated code) has no mappings, + // as shown by the starting semi-colon (which separates lines) + [], + + // the second line contains four (comma-separated) segments + [ + // segments are encoded as you'd expect: + // [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] + + // i.e. the first segment begins at column 2, and maps back to the second column + // of the second line (both zero-based) of the 0th source, and uses the 0th + // name in the `map.names` array + [ 2, 0, 2, 2, 0 ], + + // the remaining segments are 4-length rather than 5-length, + // because they don't map a name + [ 4, 0, 2, 4 ], + [ 6, 0, 2, 5 ], + [ 7, 0, 2, 7 ] + ], + + // the final line contains two segments + [ + [ 2, 1, 10, 19 ], + [ 12, 1, 11, 20 ] + ] +]); + +var encoded = encode( decoded ); +assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); +``` + +## Benchmarks + +``` +node v20.10.0 + +amp.js.map - 45120 segments + +Decode Memory Usage: +local code 5815135 bytes +@jridgewell/sourcemap-codec 1.4.15 5868160 bytes +sourcemap-codec 5492584 bytes +source-map-0.6.1 13569984 bytes +source-map-0.8.0 6390584 bytes +chrome dev tools 8011136 bytes +Smallest memory usage is sourcemap-codec + +Decode speed: +decode: local code x 492 ops/sec ±1.22% (90 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 499 ops/sec ±1.16% (89 runs sampled) +decode: sourcemap-codec x 376 ops/sec ±1.66% (89 runs sampled) +decode: source-map-0.6.1 x 34.99 ops/sec ±0.94% (48 runs sampled) +decode: source-map-0.8.0 x 351 ops/sec ±0.07% (95 runs sampled) +chrome dev tools x 165 ops/sec ±0.91% (86 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 444248 bytes +@jridgewell/sourcemap-codec 1.4.15 623024 bytes +sourcemap-codec 8696280 bytes +source-map-0.6.1 8745176 bytes +source-map-0.8.0 8736624 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 796 ops/sec ±0.11% (97 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 795 ops/sec ±0.25% (98 runs sampled) +encode: sourcemap-codec x 231 ops/sec ±0.83% (86 runs sampled) +encode: source-map-0.6.1 x 166 ops/sec ±0.57% (86 runs sampled) +encode: source-map-0.8.0 x 203 ops/sec ±0.45% (88 runs sampled) +Fastest is encode: local code,encode: @jridgewell/sourcemap-codec 1.4.15 + + +*** + + +babel.min.js.map - 347793 segments + +Decode Memory Usage: +local code 35424960 bytes +@jridgewell/sourcemap-codec 1.4.15 35424696 bytes +sourcemap-codec 36033464 bytes +source-map-0.6.1 62253704 bytes +source-map-0.8.0 43843920 bytes +chrome dev tools 45111400 bytes +Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15 + +Decode speed: +decode: local code x 38.18 ops/sec ±5.44% (52 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 38.36 ops/sec ±5.02% (52 runs sampled) +decode: sourcemap-codec x 34.05 ops/sec ±4.45% (47 runs sampled) +decode: source-map-0.6.1 x 4.31 ops/sec ±2.76% (15 runs sampled) +decode: source-map-0.8.0 x 55.60 ops/sec ±0.13% (73 runs sampled) +chrome dev tools x 16.94 ops/sec ±3.78% (46 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +local code 2606016 bytes +@jridgewell/sourcemap-codec 1.4.15 2626440 bytes +sourcemap-codec 21152576 bytes +source-map-0.6.1 25023928 bytes +source-map-0.8.0 25256448 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 127 ops/sec ±0.18% (83 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 128 ops/sec ±0.26% (83 runs sampled) +encode: sourcemap-codec x 29.31 ops/sec ±2.55% (53 runs sampled) +encode: source-map-0.6.1 x 18.85 ops/sec ±3.19% (36 runs sampled) +encode: source-map-0.8.0 x 19.34 ops/sec ±1.97% (36 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15 + + +*** + + +preact.js.map - 1992 segments + +Decode Memory Usage: +local code 261696 bytes +@jridgewell/sourcemap-codec 1.4.15 244296 bytes +sourcemap-codec 302816 bytes +source-map-0.6.1 939176 bytes +source-map-0.8.0 336 bytes +chrome dev tools 587368 bytes +Smallest memory usage is source-map-0.8.0 + +Decode speed: +decode: local code x 17,782 ops/sec ±0.32% (97 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 17,863 ops/sec ±0.40% (100 runs sampled) +decode: sourcemap-codec x 12,453 ops/sec ±0.27% (101 runs sampled) +decode: source-map-0.6.1 x 1,288 ops/sec ±1.05% (96 runs sampled) +decode: source-map-0.8.0 x 9,289 ops/sec ±0.27% (101 runs sampled) +chrome dev tools x 4,769 ops/sec ±0.18% (100 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 262944 bytes +@jridgewell/sourcemap-codec 1.4.15 25544 bytes +sourcemap-codec 323048 bytes +source-map-0.6.1 507808 bytes +source-map-0.8.0 507480 bytes +Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15 + +Encode speed: +encode: local code x 24,207 ops/sec ±0.79% (95 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 24,288 ops/sec ±0.48% (96 runs sampled) +encode: sourcemap-codec x 6,761 ops/sec ±0.21% (100 runs sampled) +encode: source-map-0.6.1 x 5,374 ops/sec ±0.17% (99 runs sampled) +encode: source-map-0.8.0 x 5,633 ops/sec ±0.32% (99 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15,encode: local code + + +*** + + +react.js.map - 5726 segments + +Decode Memory Usage: +local code 678816 bytes +@jridgewell/sourcemap-codec 1.4.15 678816 bytes +sourcemap-codec 816400 bytes +source-map-0.6.1 2288864 bytes +source-map-0.8.0 721360 bytes +chrome dev tools 1012512 bytes +Smallest memory usage is local code + +Decode speed: +decode: local code x 6,178 ops/sec ±0.19% (98 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 6,261 ops/sec ±0.22% (100 runs sampled) +decode: sourcemap-codec x 4,472 ops/sec ±0.90% (99 runs sampled) +decode: source-map-0.6.1 x 449 ops/sec ±0.31% (95 runs sampled) +decode: source-map-0.8.0 x 3,219 ops/sec ±0.13% (100 runs sampled) +chrome dev tools x 1,743 ops/sec ±0.20% (99 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 140960 bytes +@jridgewell/sourcemap-codec 1.4.15 159808 bytes +sourcemap-codec 969304 bytes +source-map-0.6.1 930520 bytes +source-map-0.8.0 930248 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 8,013 ops/sec ±0.19% (100 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 7,989 ops/sec ±0.20% (101 runs sampled) +encode: sourcemap-codec x 2,472 ops/sec ±0.21% (99 runs sampled) +encode: source-map-0.6.1 x 2,200 ops/sec ±0.17% (99 runs sampled) +encode: source-map-0.8.0 x 2,220 ops/sec ±0.37% (99 runs sampled) +Fastest is encode: local code + + +*** + + +vscode.map - 2141001 segments + +Decode Memory Usage: +local code 198955264 bytes +@jridgewell/sourcemap-codec 1.4.15 199175352 bytes +sourcemap-codec 199102688 bytes +source-map-0.6.1 386323432 bytes +source-map-0.8.0 244116432 bytes +chrome dev tools 293734280 bytes +Smallest memory usage is local code + +Decode speed: +decode: local code x 3.90 ops/sec ±22.21% (15 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 3.95 ops/sec ±23.53% (15 runs sampled) +decode: sourcemap-codec x 3.82 ops/sec ±17.94% (14 runs sampled) +decode: source-map-0.6.1 x 0.61 ops/sec ±7.81% (6 runs sampled) +decode: source-map-0.8.0 x 9.54 ops/sec ±0.28% (28 runs sampled) +chrome dev tools x 2.18 ops/sec ±10.58% (10 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +local code 13509880 bytes +@jridgewell/sourcemap-codec 1.4.15 13537648 bytes +sourcemap-codec 32540104 bytes +source-map-0.6.1 127531040 bytes +source-map-0.8.0 127535312 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 20.10 ops/sec ±0.19% (38 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 20.26 ops/sec ±0.32% (38 runs sampled) +encode: sourcemap-codec x 5.44 ops/sec ±1.64% (18 runs sampled) +encode: source-map-0.6.1 x 2.30 ops/sec ±4.79% (10 runs sampled) +encode: source-map-0.8.0 x 2.46 ops/sec ±6.53% (10 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15 +``` + +# License + +MIT diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 0000000..532bab3 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,423 @@ +// src/vlq.ts +var comma = ",".charCodeAt(0); +var semicolon = ";".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -2147483648 | -value; + } + return relative + value; +} +function encodeInteger(builder, num, relative) { + let delta = num - relative; + delta = delta < 0 ? -delta << 1 | 1 : delta << 1; + do { + let clamped = delta & 31; + delta >>>= 5; + if (delta > 0) clamped |= 32; + builder.write(intToChar[clamped]); + } while (delta > 0); + return num; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} + +// src/strings.ts +var bufLength = 1024 * 16; +var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + } +} : { + decode(buf) { + let out = ""; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + } +}; +var StringWriter = class { + constructor() { + this.pos = 0; + this.out = ""; + this.buffer = new Uint8Array(bufLength); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +}; +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/scopes.ts +var EMPTY = []; +function decodeOriginalScopes(input) { + const { length } = input; + const reader = new StringReader(input); + const scopes = []; + const stack = []; + let line = 0; + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + if (!hasMoreVlq(reader, length)) { + const last = stack.pop(); + last[2] = line; + last[3] = column; + continue; + } + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 1; + const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]; + let vars = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + scopes.push(scope); + stack.push(scope); + } + return scopes; +} +function encodeOriginalScopes(scopes) { + const writer = new StringWriter(); + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + return writer.flush(); +} +function _encodeOriginalScopes(scopes, index, writer, state) { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + if (index > 0) writer.write(comma); + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + const fields = scope.length === 6 ? 1 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) encodeInteger(writer, scope[5], 0); + for (const v of vars) { + encodeInteger(writer, v, 0); + } + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + return index; +} +function decodeGeneratedRanges(input) { + const { length } = input; + const reader = new StringReader(input); + const ranges = []; + const stack = []; + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + do { + const semi = reader.indexOf(";"); + let genColumn = 0; + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop(); + last[2] = genLine; + last[3] = genColumn; + continue; + } + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 1; + const hasCallsite = fields & 2; + const hasScope = fields & 4; + let callsite = null; + let bindings = EMPTY; + let range; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger( + reader, + definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0 + ); + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex]; + } else { + range = [genLine, genColumn, 0, 0]; + } + range.isScope = !!hasScope; + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger( + reader, + sameSource && prevLine === callsiteLine ? callsiteColumn : 0 + ); + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + ranges.push(range); + stack.push(range); + } + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + return ranges; +} +function encodeGeneratedRanges(ranges) { + if (ranges.length === 0) return ""; + const writer = new StringWriter(); + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + return writer.flush(); +} +function _encodeGeneratedRanges(ranges, index, writer, state) { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings + } = range; + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + state[1] = encodeInteger(writer, range[1], state[1]); + const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0); + encodeInteger(writer, fields, 0); + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn); + encodeInteger(writer, expRange[0], 0); + } + } + } + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + return index; +} +function catchupLine(writer, lastLine, line) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + genColumn = encodeInteger(writer, segment[0], genColumn); + if (segment.length === 1) continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + if (segment.length === 4) continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + return writer.flush(); +} +export { + decode, + decodeGeneratedRanges, + decodeOriginalScopes, + encode, + encodeGeneratedRanges, + encodeOriginalScopes +}; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 0000000..c276844 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/vlq.ts", "../src/strings.ts", "../src/scopes.ts", "../src/sourcemap-codec.ts"], + "mappings": ";AAEO,IAAM,QAAQ,IAAI,WAAW,CAAC;AAC9B,IAAM,YAAY,IAAI,WAAW,CAAC;AAEzC,IAAM,QAAQ;AACd,IAAM,YAAY,IAAI,WAAW,EAAE;AACnC,IAAM,YAAY,IAAI,WAAW,GAAG;AAEpC,SAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,QAAM,IAAI,MAAM,WAAW,CAAC;AAC5B,YAAU,CAAC,IAAI;AACf,YAAU,CAAC,IAAI;AACjB;AAEO,SAAS,cAAc,QAAsB,UA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B,YAAQ,KAAK,IAAI;AACjB,WAAO,MAAM,OAAO;AAAA,EACtB,SAAS,OAAO,OAAO;AAEvB,SAAO;AACT;AAEA,SAAS,KAAK,MAA0B;AACtC,OAAK,KAAK,cAAc;AAC1B;AAEA,SAAS,eAAe,GAAqB,GAA6B;AACxE,SAAO,EAAE,CAAC,IAAI,EAAE,CAAC;AACnB;AAIO,SAAS,OAAO,SAA8C;AACnE,QAAM,SAAS,IAAI,aAAa;AAChC,MAAI,eAAe;AACnB,MAAI,aAAa;AACjB,MAAI,eAAe;AACnB,MAAI,aAAa;AAEjB,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,OAAO,QAAQ,CAAC;AACtB,QAAI,IAAI,EAAG,QAAO,MAAM,SAAS;AACjC,QAAI,KAAK,WAAW,EAAG;AAEvB,QAAI,YAAY;AAEhB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,UAAU,KAAK,CAAC;AACtB,UAAI,IAAI,EAAG,QAAO,MAAM,KAAK;AAE7B,kBAAY,cAAc,QAAQ,QAAQ,CAAC,GAAG,SAAS;AAEvD,UAAI,QAAQ,WAAW,EAAG;AAC1B,qBAAe,cAAc,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAC7D,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AACzD,qBAAe,cAAc,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAE7D,UAAI,QAAQ,WAAW,EAAG;AAC1B,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO,OAAO,MAAM;AACtB;", + "names": [] +} diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 0000000..2d8e459 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,464 @@ +(function (global, factory) { + if (typeof exports === 'object' && typeof module !== 'undefined') { + factory(module); + module.exports = def(module); + } else if (typeof define === 'function' && define.amd) { + define(['module'], function(mod) { + factory.apply(this, arguments); + mod.exports = def(mod); + }); + } else { + const mod = { exports: {} }; + factory(mod); + global = typeof globalThis !== 'undefined' ? globalThis : global || self; + global.sourcemapCodec = def(mod); + } + function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; } +})(this, (function (module) { +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/sourcemap-codec.ts +var sourcemap_codec_exports = {}; +__export(sourcemap_codec_exports, { + decode: () => decode, + decodeGeneratedRanges: () => decodeGeneratedRanges, + decodeOriginalScopes: () => decodeOriginalScopes, + encode: () => encode, + encodeGeneratedRanges: () => encodeGeneratedRanges, + encodeOriginalScopes: () => encodeOriginalScopes +}); +module.exports = __toCommonJS(sourcemap_codec_exports); + +// src/vlq.ts +var comma = ",".charCodeAt(0); +var semicolon = ";".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -2147483648 | -value; + } + return relative + value; +} +function encodeInteger(builder, num, relative) { + let delta = num - relative; + delta = delta < 0 ? -delta << 1 | 1 : delta << 1; + do { + let clamped = delta & 31; + delta >>>= 5; + if (delta > 0) clamped |= 32; + builder.write(intToChar[clamped]); + } while (delta > 0); + return num; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} + +// src/strings.ts +var bufLength = 1024 * 16; +var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + } +} : { + decode(buf) { + let out = ""; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + } +}; +var StringWriter = class { + constructor() { + this.pos = 0; + this.out = ""; + this.buffer = new Uint8Array(bufLength); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +}; +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/scopes.ts +var EMPTY = []; +function decodeOriginalScopes(input) { + const { length } = input; + const reader = new StringReader(input); + const scopes = []; + const stack = []; + let line = 0; + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + if (!hasMoreVlq(reader, length)) { + const last = stack.pop(); + last[2] = line; + last[3] = column; + continue; + } + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 1; + const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]; + let vars = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + scopes.push(scope); + stack.push(scope); + } + return scopes; +} +function encodeOriginalScopes(scopes) { + const writer = new StringWriter(); + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + return writer.flush(); +} +function _encodeOriginalScopes(scopes, index, writer, state) { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + if (index > 0) writer.write(comma); + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + const fields = scope.length === 6 ? 1 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) encodeInteger(writer, scope[5], 0); + for (const v of vars) { + encodeInteger(writer, v, 0); + } + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + return index; +} +function decodeGeneratedRanges(input) { + const { length } = input; + const reader = new StringReader(input); + const ranges = []; + const stack = []; + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + do { + const semi = reader.indexOf(";"); + let genColumn = 0; + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop(); + last[2] = genLine; + last[3] = genColumn; + continue; + } + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 1; + const hasCallsite = fields & 2; + const hasScope = fields & 4; + let callsite = null; + let bindings = EMPTY; + let range; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger( + reader, + definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0 + ); + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex]; + } else { + range = [genLine, genColumn, 0, 0]; + } + range.isScope = !!hasScope; + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger( + reader, + sameSource && prevLine === callsiteLine ? callsiteColumn : 0 + ); + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + ranges.push(range); + stack.push(range); + } + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + return ranges; +} +function encodeGeneratedRanges(ranges) { + if (ranges.length === 0) return ""; + const writer = new StringWriter(); + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + return writer.flush(); +} +function _encodeGeneratedRanges(ranges, index, writer, state) { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings + } = range; + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + state[1] = encodeInteger(writer, range[1], state[1]); + const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0); + encodeInteger(writer, fields, 0); + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn); + encodeInteger(writer, expRange[0], 0); + } + } + } + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + return index; +} +function catchupLine(writer, lastLine, line) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + genColumn = encodeInteger(writer, segment[0], genColumn); + if (segment.length === 1) continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + if (segment.length === 4) continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + return writer.flush(); +} +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 0000000..abc18d2 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/sourcemap-codec.ts", "../src/vlq.ts", "../src/strings.ts", "../src/scopes.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,QAAQ,IAAI,WAAW,CAAC;AAC9B,IAAM,YAAY,IAAI,WAAW,CAAC;AAEzC,IAAM,QAAQ;AACd,IAAM,YAAY,IAAI,WAAW,EAAE;AACnC,IAAM,YAAY,IAAI,WAAW,GAAG;AAEpC,SAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,QAAM,IAAI,MAAM,WAAW,CAAC;AAC5B,YAAU,CAAC,IAAI;AACf,YAAU,CAAC,IAAI;AACjB;AAEO,SAAS,cAAc,QAAsB,UAA0B;AAC5E,MAAI,QAAQ;AACZ,MAAI,QAAQ;AACZ,MAAI,UAAU;AAEd,KAAG;AACD,UAAM,IAAI,OAAO,KAAK;AACtB,cAAU,UAAU,CAAC;AACrB,cAAU,UAAU,OAAO;AAC3B,aAAS;AAAA,EACX,SAAS,UAAU;AAEnB,QAAM,eAAe,QAAQ;AAC7B,aAAW;AAEX,MAAI,cAAc;AAChB,YAAQ,cAAc,CAAC;AAAA,EACzB;AAEA,SAAO,WAAW;AACpB;AAEO,SAAS,cAAc,SAAuB,KAAa,UAA0B;AAC1F,MAAI,QAAQ,MAAM;AAElB,UAAQ,QAAQ,IAAK,CAAC,SAAS,IAAK,IAAI,SAAS;AAC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AQ,CAAC;AACtB,QAAI,IAAI,EAAG,QAAO,MAAM,SAAS;AACjC,QAAI,KAAK,WAAW,EAAG;AAEvB,QAAI,YAAY;AAEhB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,UAAU,KAAK,CAAC;AACtB,UAAI,IAAI,EAAG,QAAO,MAAM,KAAK;AAE7B,kBAAY,cAAc,QAAQ,QAAQ,CAAC,GAAG,SAAS;AAEvD,UAAI,QAAQ,WAAW,EAAG;AAC1B,qBAAe,cAAc,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAC7D,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AACzD,qBAAe,cAAc,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAE7D,UAAI,QAAQ,WAAW,EAAG;AAC1B,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO,OAAO,MAAM;AACtB;", + "names": [] +} diff --git a/node_modules/@jridgewell/sourcemap-codec/package.json b/node_modules/@jridgewell/sourcemap-codec/package.json new file mode 100644 index 0000000..da55137 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/package.json @@ -0,0 +1,63 @@ +{ + "name": "@jridgewell/sourcemap-codec", + "version": "1.5.5", + "description": "Encode/decode sourcemap mappings", + "keywords": [ + "sourcemap", + "vlq" + ], + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.mjs", + "types": "types/sourcemap-codec.d.cts", + "files": [ + "dist", + "src", + "types" + ], + "exports": { + ".": [ + { + "import": { + "types": "./types/sourcemap-codec.d.mts", + "default": "./dist/sourcemap-codec.mjs" + }, + "default": { + "types": "./types/sourcemap-codec.d.cts", + "default": "./dist/sourcemap-codec.umd.js" + } + }, + "./dist/sourcemap-codec.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:code benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:code build:types", + "build:code": "node ../../esbuild.mjs sourcemap-codec.ts", + "build:types": "run-s build:types:force build:types:emit build:types:mts", + "build:types:force": "rimraf tsconfig.build.tsbuildinfo", + "build:types:emit": "tsc --project tsconfig.build.json", + "build:types:mts": "node ../../mts-types.mjs", + "clean": "run-s -n clean:code clean:types", + "clean:code": "tsc --build --clean tsconfig.build.json", + "clean:types": "rimraf dist types", + "test": "run-s -n test:types test:only test:format", + "test:format": "prettier --check '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:types": "eslint '{src,test}/**/*.ts'", + "lint": "run-s -n lint:types lint:format", + "lint:format": "npm run test:format -- --write", + "lint:types": "npm run test:types -- --fix", + "prepublishOnly": "npm run-s -n build test" + }, + "homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/sourcemap-codec", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemaps.git", + "directory": "packages/sourcemap-codec" + }, + "author": "Justin Ridgewell ", + "license": "MIT" +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts b/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts new file mode 100644 index 0000000..d194c2f --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts @@ -0,0 +1,345 @@ +import { StringReader, StringWriter } from './strings'; +import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq'; + +const EMPTY: any[] = []; + +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; + +type Mix = (A & O) | (B & O); + +export type OriginalScope = Mix< + [Line, Column, Line, Column, Kind], + [Line, Column, Line, Column, Kind, Name], + { vars: Var[] } +>; + +export type GeneratedRange = Mix< + [Line, Column, Line, Column], + [Line, Column, Line, Column, SourcesIndex, ScopesIndex], + { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; + } +>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; + +export function decodeOriginalScopes(input: string): OriginalScope[] { + const { length } = input; + const reader = new StringReader(input); + const scopes: OriginalScope[] = []; + const stack: OriginalScope[] = []; + let line = 0; + + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + + if (!hasMoreVlq(reader, length)) { + const last = stack.pop()!; + last[2] = line; + last[3] = column; + continue; + } + + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 0b0001; + + const scope: OriginalScope = ( + hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind] + ) as OriginalScope; + + let vars: Var[] = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + + scopes.push(scope); + stack.push(scope); + } + + return scopes; +} + +export function encodeOriginalScopes(scopes: OriginalScope[]): string { + const writer = new StringWriter(); + + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + + return writer.flush(); +} + +function _encodeOriginalScopes( + scopes: OriginalScope[], + index: number, + writer: StringWriter, + state: [ + number, // GenColumn + ], +): number { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + + if (index > 0) writer.write(comma); + + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + + const fields = scope.length === 6 ? 0b0001 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) encodeInteger(writer, scope[5], 0); + + for (const v of vars) { + encodeInteger(writer, v, 0); + } + + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + + return index; +} + +export function decodeGeneratedRanges(input: string): GeneratedRange[] { + const { length } = input; + const reader = new StringReader(input); + const ranges: GeneratedRange[] = []; + const stack: GeneratedRange[] = []; + + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + + do { + const semi = reader.indexOf(';'); + let genColumn = 0; + + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop()!; + last[2] = genLine; + last[3] = genColumn; + continue; + } + + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 0b0001; + const hasCallsite = fields & 0b0010; + const hasScope = fields & 0b0100; + + let callsite: CallSite | null = null; + let bindings: Binding[] = EMPTY; + let range: GeneratedRange; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger( + reader, + definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0, + ); + + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex] as GeneratedRange; + } else { + range = [genLine, genColumn, 0, 0] as GeneratedRange; + } + + range.isScope = !!hasScope; + + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger( + reader, + sameSource && prevLine === callsiteLine ? callsiteColumn : 0, + ); + + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges: BindingExpressionRange[]; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + + ranges.push(range); + stack.push(range); + } + + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + + return ranges; +} + +export function encodeGeneratedRanges(ranges: GeneratedRange[]): string { + if (ranges.length === 0) return ''; + + const writer = new StringWriter(); + + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + + return writer.flush(); +} + +function _encodeGeneratedRanges( + ranges: GeneratedRange[], + index: number, + writer: StringWriter, + state: [ + number, // GenLine + number, // GenColumn + number, // DefSourcesIndex + number, // DefScopesIndex + number, // CallSourcesIndex + number, // CallLine + number, // CallColumn + ], +): number { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings, + } = range; + + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + + state[1] = encodeInteger(writer, range[1], state[1]); + + const fields = + (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0); + encodeInteger(writer, fields, 0); + + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite!; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1]!, bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2]!, bindingStartColumn); + encodeInteger(writer, expRange[0]!, 0); + } + } + } + + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + + return index; +} + +function catchupLine(writer: StringWriter, lastLine: number, line: number) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts b/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts new file mode 100644 index 0000000..a81f894 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts @@ -0,0 +1,111 @@ +import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq'; +import { StringWriter, StringReader } from './strings'; + +export { + decodeOriginalScopes, + encodeOriginalScopes, + decodeGeneratedRanges, + encodeGeneratedRanges, +} from './scopes'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes'; + +export type SourceMapSegment = + | [number] + | [number, number, number, number] + | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; + +export function decode(mappings: string): SourceMapMappings { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded: SourceMapMappings = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + + do { + const semi = reader.indexOf(';'); + const line: SourceMapLine = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + + while (reader.pos < semi) { + let seg: SourceMapSegment; + + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + + line.push(seg); + reader.pos++; + } + + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + + return decoded; +} + +function sort(line: SourceMapSegment[]) { + line.sort(sortComparator); +} + +function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number { + return a[0] - b[0]; +} + +export function encode(decoded: SourceMapMappings): string; +export function encode(decoded: Readonly): string; +export function encode(decoded: Readonly): string { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + + let genColumn = 0; + + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + + genColumn = encodeInteger(writer, segment[0], genColumn); + + if (segment.length === 1) continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + + if (segment.length === 4) continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + + return writer.flush(); +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/strings.ts b/node_modules/@jridgewell/sourcemap-codec/src/strings.ts new file mode 100644 index 0000000..d161965 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/strings.ts @@ -0,0 +1,65 @@ +const bufLength = 1024 * 16; + +// Provide a fallback for older environments. +const td = + typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf: Uint8Array): string { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf: Uint8Array): string { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + +export class StringWriter { + pos = 0; + private out = ''; + private buffer = new Uint8Array(bufLength); + + write(v: number): void { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + + flush(): string { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +} + +export class StringReader { + pos = 0; + declare private buffer: string; + + constructor(buffer: string) { + this.buffer = buffer; + } + + next(): number { + return this.buffer.charCodeAt(this.pos++); + } + + peek(): number { + return this.buffer.charCodeAt(this.pos); + } + + indexOf(char: string): number { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts b/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts new file mode 100644 index 0000000..a42c681 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts @@ -0,0 +1,55 @@ +import type { StringReader, StringWriter } from './strings'; + +export const comma = ','.charCodeAt(0); +export const semicolon = ';'.charCodeAt(0); + +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII + +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} + +export function decodeInteger(reader: StringReader, relative: number): number { + let value = 0; + let shift = 0; + let integer = 0; + + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + + const shouldNegate = value & 1; + value >>>= 1; + + if (shouldNegate) { + value = -0x80000000 | -value; + } + + return relative + value; +} + +export function encodeInteger(builder: StringWriter, num: number, relative: number): number { + let delta = num - relative; + + delta = delta < 0 ? (-delta << 1) | 1 : delta << 1; + do { + let clamped = delta & 0b011111; + delta >>>= 5; + if (delta > 0) clamped |= 0b100000; + builder.write(intToChar[clamped]); + } while (delta > 0); + + return num; +} + +export function hasMoreVlq(reader: StringReader, max: number) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} diff --git a/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts new file mode 100644 index 0000000..c583c75 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts @@ -0,0 +1,50 @@ +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; +type Mix = (A & O) | (B & O); +export type OriginalScope = Mix<[ + Line, + Column, + Line, + Column, + Kind +], [ + Line, + Column, + Line, + Column, + Kind, + Name +], { + vars: Var[]; +}>; +export type GeneratedRange = Mix<[ + Line, + Column, + Line, + Column +], [ + Line, + Column, + Line, + Column, + SourcesIndex, + ScopesIndex +], { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; +}>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; +export declare function decodeOriginalScopes(input: string): OriginalScope[]; +export declare function encodeOriginalScopes(scopes: OriginalScope[]): string; +export declare function decodeGeneratedRanges(input: string): GeneratedRange[]; +export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string; +export {}; +//# sourceMappingURL=scopes.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map new file mode 100644 index 0000000..630e647 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CAyCnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA2CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAoGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts new file mode 100644 index 0000000..c583c75 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts @@ -0,0 +1,50 @@ +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; +type Mix = (A & O) | (B & O); +export type OriginalScope = Mix<[ + Line, + Column, + Line, + Column, + Kind +], [ + Line, + Column, + Line, + Column, + Kind, + Name +], { + vars: Var[]; +}>; +export type GeneratedRange = Mix<[ + Line, + Column, + Line, + Column +], [ + Line, + Column, + Line, + Column, + SourcesIndex, + ScopesIndex +], { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; +}>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; +export declare function decodeOriginalScopes(input: string): OriginalScope[]; +export declare function encodeOriginalScopes(scopes: OriginalScope[]): string; +export declare function decodeGeneratedRanges(input: string): GeneratedRange[]; +export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string; +export {}; +//# sourceMappingURL=scopes.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map new file mode 100644 index 0000000..630e647 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CAyCnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA2CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAoGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts new file mode 100644 index 0000000..5f35e22 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts @@ -0,0 +1,9 @@ +export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.cts'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.cts'; +export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; +//# sourceMappingURL=sourcemap-codec.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map new file mode 100644 index 0000000..7123d52 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts new file mode 100644 index 0000000..199fb9f --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts @@ -0,0 +1,9 @@ +export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.mts'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.mts'; +export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; +//# sourceMappingURL=sourcemap-codec.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map new file mode 100644 index 0000000..7123d52 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts new file mode 100644 index 0000000..62faceb --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts @@ -0,0 +1,16 @@ +export declare class StringWriter { + pos: number; + private out; + private buffer; + write(v: number): void; + flush(): string; +} +export declare class StringReader { + pos: number; + private buffer; + constructor(buffer: string); + next(): number; + peek(): number; + indexOf(char: string): number; +} +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map new file mode 100644 index 0000000..d3602da --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts new file mode 100644 index 0000000..62faceb --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts @@ -0,0 +1,16 @@ +export declare class StringWriter { + pos: number; + private out; + private buffer; + write(v: number): void; + flush(): string; +} +export declare class StringReader { + pos: number; + private buffer; + constructor(buffer: string); + next(): number; + peek(): number; + indexOf(char: string): number; +} +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map new file mode 100644 index 0000000..d3602da --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts new file mode 100644 index 0000000..dbd6602 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts @@ -0,0 +1,7 @@ +import type { StringReader, StringWriter } from './strings.cts'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader, relative: number): number; +export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; +//# sourceMappingURL=vlq.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map new file mode 100644 index 0000000..6fdc356 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts new file mode 100644 index 0000000..2c739bc --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts @@ -0,0 +1,7 @@ +import type { StringReader, StringWriter } from './strings.mts'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader, relative: number): number; +export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; +//# sourceMappingURL=vlq.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map new file mode 100644 index 0000000..6fdc356 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/LICENSE b/node_modules/@jridgewell/trace-mapping/LICENSE new file mode 100644 index 0000000..37bb488 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@jridgewell/trace-mapping/README.md b/node_modules/@jridgewell/trace-mapping/README.md new file mode 100644 index 0000000..8286cee --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/README.md @@ -0,0 +1,193 @@ +# @jridgewell/trace-mapping + +> Trace the original position through a source map + +`trace-mapping` allows you to take the line and column of an output file and trace it to the +original location in the source file through a source map. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapConsumer`. This +provides the same `originalPositionFor` and `generatedPositionFor` API, without requiring WASM. + +## Installation + +```sh +npm install @jridgewell/trace-mapping +``` + +## Usage + +```typescript +import { TraceMap, originalPositionFor, generatedPositionFor } from '@jridgewell/trace-mapping'; + +const tracer = new TraceMap({ + version: 3, + sources: ['input.js'], + names: ['foo'], + mappings: 'KAyCIA', +}); + +// Lines start at line 1, columns at column 0. +const traced = originalPositionFor(tracer, { line: 1, column: 5 }); +assert.deepEqual(traced, { + source: 'input.js', + line: 42, + column: 4, + name: 'foo', +}); + +const generated = generatedPositionFor(tracer, { + source: 'input.js', + line: 42, + column: 4, +}); +assert.deepEqual(generated, { + line: 1, + column: 5, +}); +``` + +We also provide a lower level API to get the actual segment that matches our line and column. Unlike +`originalPositionFor`, `traceSegment` uses a 0-base for `line`: + +```typescript +import { traceSegment } from '@jridgewell/trace-mapping'; + +// line is 0-base. +const traced = traceSegment(tracer, /* line */ 0, /* column */ 5); + +// Segments are [outputColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] +// Again, line is 0-base and so is sourceLine +assert.deepEqual(traced, [5, 0, 41, 4, 0]); +``` + +### SectionedSourceMaps + +The sourcemap spec defines a special `sections` field that's designed to handle concatenation of +output code with associated sourcemaps. This type of sourcemap is rarely used (no major build tool +produces it), but if you are hand coding a concatenation you may need it. We provide an `AnyMap` +helper that can receive either a regular sourcemap or a `SectionedSourceMap` and returns a +`TraceMap` instance: + +```typescript +import { AnyMap } from '@jridgewell/trace-mapping'; +const fooOutput = 'foo'; +const barOutput = 'bar'; +const output = [fooOutput, barOutput].join('\n'); + +const sectioned = new AnyMap({ + version: 3, + sections: [ + { + // 0-base line and column + offset: { line: 0, column: 0 }, + // fooOutput's sourcemap + map: { + version: 3, + sources: ['foo.js'], + names: ['foo'], + mappings: 'AAAAA', + }, + }, + { + // barOutput's sourcemap will not affect the first line, only the second + offset: { line: 1, column: 0 }, + map: { + version: 3, + sources: ['bar.js'], + names: ['bar'], + mappings: 'AAAAA', + }, + }, + ], +}); + +const traced = originalPositionFor(sectioned, { + line: 2, + column: 0, +}); + +assert.deepEqual(traced, { + source: 'bar.js', + line: 1, + column: 0, + name: 'bar', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map +trace-mapping: decoded JSON input x 183 ops/sec ±0.41% (87 runs sampled) +trace-mapping: encoded JSON input x 384 ops/sec ±0.89% (89 runs sampled) +trace-mapping: decoded Object input x 3,085 ops/sec ±0.24% (100 runs sampled) +trace-mapping: encoded Object input x 452 ops/sec ±0.80% (84 runs sampled) +source-map-js: encoded Object input x 88.82 ops/sec ±0.45% (77 runs sampled) +source-map-0.6.1: encoded Object input x 38.39 ops/sec ±1.88% (52 runs sampled) +Fastest is trace-mapping: decoded Object input + +trace-mapping: decoded originalPositionFor x 4,025,347 ops/sec ±0.15% (97 runs sampled) +trace-mapping: encoded originalPositionFor x 3,333,136 ops/sec ±1.26% (90 runs sampled) +source-map-js: encoded originalPositionFor x 824,978 ops/sec ±1.06% (94 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 741,300 ops/sec ±0.93% (92 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 2,587,603 ops/sec ±0.75% (97 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +*** + +babel.min.js.map +trace-mapping: decoded JSON input x 17.43 ops/sec ±8.81% (33 runs sampled) +trace-mapping: encoded JSON input x 34.18 ops/sec ±4.67% (50 runs sampled) +trace-mapping: decoded Object input x 1,010 ops/sec ±0.41% (98 runs sampled) +trace-mapping: encoded Object input x 39.45 ops/sec ±4.01% (52 runs sampled) +source-map-js: encoded Object input x 6.57 ops/sec ±3.04% (21 runs sampled) +source-map-0.6.1: encoded Object input x 4.23 ops/sec ±2.93% (15 runs sampled) +Fastest is trace-mapping: decoded Object input + +trace-mapping: decoded originalPositionFor x 7,576,265 ops/sec ±0.74% (96 runs sampled) +trace-mapping: encoded originalPositionFor x 5,019,743 ops/sec ±0.74% (94 runs sampled) +source-map-js: encoded originalPositionFor x 3,396,137 ops/sec ±42.32% (95 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 3,753,176 ops/sec ±0.72% (95 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 6,423,633 ops/sec ±0.74% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +*** + +preact.js.map +trace-mapping: decoded JSON input x 3,499 ops/sec ±0.18% (98 runs sampled) +trace-mapping: encoded JSON input x 6,078 ops/sec ±0.25% (99 runs sampled) +trace-mapping: decoded Object input x 254,788 ops/sec ±0.13% (100 runs sampled) +trace-mapping: encoded Object input x 14,063 ops/sec ±0.27% (94 runs sampled) +source-map-js: encoded Object input x 2,465 ops/sec ±0.25% (98 runs sampled) +source-map-0.6.1: encoded Object input x 1,174 ops/sec ±1.90% (95 runs sampled) +Fastest is trace-mapping: decoded Object input + +trace-mapping: decoded originalPositionFor x 7,720,171 ops/sec ±0.14% (97 runs sampled) +trace-mapping: encoded originalPositionFor x 6,864,485 ops/sec ±0.16% (101 runs sampled) +source-map-js: encoded originalPositionFor x 2,387,219 ops/sec ±0.28% (98 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 1,565,339 ops/sec ±0.32% (101 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 3,819,732 ops/sec ±0.38% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +*** + +react.js.map +trace-mapping: decoded JSON input x 1,719 ops/sec ±0.19% (99 runs sampled) +trace-mapping: encoded JSON input x 4,284 ops/sec ±0.51% (99 runs sampled) +trace-mapping: decoded Object input x 94,668 ops/sec ±0.08% (99 runs sampled) +trace-mapping: encoded Object input x 5,287 ops/sec ±0.24% (99 runs sampled) +source-map-js: encoded Object input x 814 ops/sec ±0.20% (98 runs sampled) +source-map-0.6.1: encoded Object input x 429 ops/sec ±0.24% (94 runs sampled) +Fastest is trace-mapping: decoded Object input + +trace-mapping: decoded originalPositionFor x 28,927,989 ops/sec ±0.61% (94 runs sampled) +trace-mapping: encoded originalPositionFor x 27,394,475 ops/sec ±0.55% (97 runs sampled) +source-map-js: encoded originalPositionFor x 16,856,730 ops/sec ±0.45% (96 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 12,258,950 ops/sec ±0.41% (97 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 22,272,990 ops/sec ±0.58% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor +``` + +[source-map]: https://www.npmjs.com/package/source-map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs new file mode 100644 index 0000000..8fce400 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs @@ -0,0 +1,514 @@ +import { encode, decode } from '@jridgewell/sourcemap-codec'; +import resolveUri from '@jridgewell/resolve-uri'; + +function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; +const REV_GENERATED_LINE = 1; +const REV_GENERATED_COLUMN = 2; + +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; +} + +let found = false; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; i++, index++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; i--, index--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; +} +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); +} + +// Rebuilds the original source files, with mappings that are ordered by source line/column instead +// of generated line/column. +function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like +// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. +// Numeric properties on objects are magically sorted in ascending order by the engine regardless of +// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending +// order when iterating with for-in. +function buildNullArray() { + return { __proto__: null }; +} + +const AnyMap = function (map, mapUrl) { + const parsed = typeof map === 'string' ? JSON.parse(map) : map; + if (!('sections' in parsed)) + return new TraceMap(parsed, mapUrl); + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const { sections } = parsed; + let i = 0; + for (; i < sections.length - 1; i++) { + const no = sections[i + 1].offset; + addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, no.line, no.column); + } + if (sections.length > 0) { + addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, Infinity, Infinity); + } + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + }; + return presortedDecodedMap(joined); +}; +function addSection(section, mapUrl, mappings, sources, sourcesContent, names, stopLine, stopColumn) { + const map = AnyMap(section.map, mapUrl); + const { line: lineOffset, column: columnOffset } = section.offset; + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources } = map; + append(sources, resolvedSources); + append(sourcesContent, map.sourcesContent || fillSourcesContent(resolvedSources.length)); + append(names, map.names); + // If this section jumps forwards several lines, we need to add lines to the output mappings catch up. + for (let i = mappings.length; i <= lineOffset; i++) + mappings.push([]); + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. + const stopI = stopLine - lineOffset; + const len = Math.min(decoded.length, stopI + 1); + for (let i = 0; i < len; i++) { + const line = decoded[i]; + // On the 0th loop, the line will already exist due to a previous section, or the line catch up + // loop above. + const out = i === 0 ? mappings[lineOffset] : (mappings[lineOffset + i] = []); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (i === stopI && column >= stopColumn) + break; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + if (seg.length === 4) { + out.push([column, sourcesIndex, sourceLine, sourceColumn]); + continue; + } + out.push([column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } +} +function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); +} +// Sourcemaps don't need to have sourcesContent, and if they don't, we need to create an array of +// equal length to the sources. This is because the sources and sourcesContent are paired arrays, +// where `sourcesContent[i]` is the content of the `sources[i]` file. If we didn't, then joined +// sourcemap would desynchronize the sources/contents. +function fillSourcesContent(len) { + const sourcesContent = []; + for (let i = 0; i < len; i++) + sourcesContent[i] = null; + return sourcesContent; +} + +const INVALID_ORIGINAL_MAPPING = Object.freeze({ + source: null, + line: null, + column: null, + name: null, +}); +const INVALID_GENERATED_MAPPING = Object.freeze({ + line: null, + column: null, +}); +const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; +const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +let encodedMappings; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +let decodedMappings; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +let traceSegment; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +let originalPositionFor; +/** + * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided + * the found mapping is from the same source and line as the originalPositionFor mapping. + * + * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1` + * using the same needle that would return `id` when calling `originalPositionFor`. + */ +let generatedPositionFor; +/** + * Iterates each mapping in generated position order. + */ +let eachMapping; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +let presortedDecodedMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let decodedMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let encodedMap; +class TraceMap { + constructor(map, mapUrl) { + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + const isString = typeof map === 'string'; + if (!isString && map.constructor === TraceMap) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + if (sourceRoot || mapUrl) { + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + } + else { + this.resolvedSources = sources.map((s) => s || ''); + } + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + } +} +(() => { + encodedMappings = (map) => { + var _a; + return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = encode(map._decoded))); + }; + decodedMappings = (map) => { + return (map._decoded || (map._decoded = decode(map._encoded))); + }; + traceSegment = (map, line, column) => { + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + }; + originalPositionFor = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return INVALID_ORIGINAL_MAPPING; + const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (segment == null) + return INVALID_ORIGINAL_MAPPING; + if (segment.length == 1) + return INVALID_ORIGINAL_MAPPING; + const { names, resolvedSources } = map; + return { + source: resolvedSources[segment[SOURCES_INDEX]], + line: segment[SOURCE_LINE] + 1, + column: segment[SOURCE_COLUMN], + name: segment.length === 5 ? names[segment[NAMES_INDEX]] : null, + }; + }; + generatedPositionFor = (map, { source, line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return INVALID_GENERATED_MAPPING; + const generated = (map._bySources || (map._bySources = buildBySources(decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const memos = map._bySourceMemos; + const segments = generated[sourceIndex][line]; + if (segments == null) + return INVALID_GENERATED_MAPPING; + const segment = traceSegmentInternal(segments, memos[sourceIndex], line, column, bias || GREATEST_LOWER_BOUND); + if (segment == null) + return INVALID_GENERATED_MAPPING; + return { + line: segment[REV_GENERATED_LINE] + 1, + column: segment[REV_GENERATED_COLUMN], + }; + }; + eachMapping = (map, cb) => { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + }; + presortedDecodedMap = (map, mapUrl) => { + const clone = Object.assign({}, map); + clone.mappings = []; + const tracer = new TraceMap(clone, mapUrl); + tracer._decoded = map.mappings; + return tracer; + }; + decodedMap = (map) => { + return { + version: 3, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings: decodedMappings(map), + }; + }; + encodedMap = (map) => { + return { + version: 3, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings: encodedMappings(map), + }; + }; +})(); +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return null; + return segments[index]; +} + +export { AnyMap, GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap, decodedMap, decodedMappings, eachMapping, encodedMap, encodedMappings, generatedPositionFor, originalPositionFor, presortedDecodedMap, traceSegment }; +//# sourceMappingURL=trace-mapping.mjs.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map new file mode 100644 index 0000000..fec7769 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.mjs","sources":["../../src/resolve.ts","../../src/strip-filename.ts","../../src/sourcemap-segment.ts","../../src/sort.ts","../../src/binary-search.ts","../../src/by-source.ts","../../src/any-map.ts","../../src/trace-mapping.ts"],"sourcesContent":[null,null,null,null,null,null,null,null],"names":["bsFound"],"mappings":";;;SAEwB,OAAO,CAAC,KAAa,EAAE,IAAwB;;;;IAIrE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,IAAI,IAAI,GAAG,CAAC;IAE7C,OAAO,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACjC;;ACTA;;;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,KAAK,KAAK,CAAC,CAAC,IAAI,KAAK,KAAK,QAAQ,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IAC3D,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;AACzB;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js new file mode 100644 index 0000000..8b755bd --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js @@ -0,0 +1,528 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/sourcemap-codec'), require('@jridgewell/resolve-uri')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/sourcemap-codec', '@jridgewell/resolve-uri'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.traceMapping = {}, global.sourcemapCodec, global.resolveURI)); +})(this, (function (exports, sourcemapCodec, resolveUri) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + var resolveUri__default = /*#__PURE__*/_interopDefaultLegacy(resolveUri); + + function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri__default["default"](input, base); + } + + /** + * Removes everything after the last "/", but leaves the slash. + */ + function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + + const COLUMN = 0; + const SOURCES_INDEX = 1; + const SOURCE_LINE = 2; + const SOURCE_COLUMN = 3; + const NAMES_INDEX = 4; + const REV_GENERATED_LINE = 1; + const REV_GENERATED_COLUMN = 2; + + function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; + } + function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; + } + function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; + } + function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; + } + + let found = false; + /** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ + function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; + } + function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; i++, index++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; i--, index--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; + } + /** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ + function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); + } + + // Rebuilds the original source files, with mappings that are ordered by source line/column instead + // of generated line/column. + function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; + } + function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like + // a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. + // Numeric properties on objects are magically sorted in ascending order by the engine regardless of + // the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending + // order when iterating with for-in. + function buildNullArray() { + return { __proto__: null }; + } + + const AnyMap = function (map, mapUrl) { + const parsed = typeof map === 'string' ? JSON.parse(map) : map; + if (!('sections' in parsed)) + return new TraceMap(parsed, mapUrl); + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const { sections } = parsed; + let i = 0; + for (; i < sections.length - 1; i++) { + const no = sections[i + 1].offset; + addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, no.line, no.column); + } + if (sections.length > 0) { + addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, Infinity, Infinity); + } + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + }; + return exports.presortedDecodedMap(joined); + }; + function addSection(section, mapUrl, mappings, sources, sourcesContent, names, stopLine, stopColumn) { + const map = AnyMap(section.map, mapUrl); + const { line: lineOffset, column: columnOffset } = section.offset; + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = exports.decodedMappings(map); + const { resolvedSources } = map; + append(sources, resolvedSources); + append(sourcesContent, map.sourcesContent || fillSourcesContent(resolvedSources.length)); + append(names, map.names); + // If this section jumps forwards several lines, we need to add lines to the output mappings catch up. + for (let i = mappings.length; i <= lineOffset; i++) + mappings.push([]); + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. + const stopI = stopLine - lineOffset; + const len = Math.min(decoded.length, stopI + 1); + for (let i = 0; i < len; i++) { + const line = decoded[i]; + // On the 0th loop, the line will already exist due to a previous section, or the line catch up + // loop above. + const out = i === 0 ? mappings[lineOffset] : (mappings[lineOffset + i] = []); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (i === stopI && column >= stopColumn) + break; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + if (seg.length === 4) { + out.push([column, sourcesIndex, sourceLine, sourceColumn]); + continue; + } + out.push([column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } + } + function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); + } + // Sourcemaps don't need to have sourcesContent, and if they don't, we need to create an array of + // equal length to the sources. This is because the sources and sourcesContent are paired arrays, + // where `sourcesContent[i]` is the content of the `sources[i]` file. If we didn't, then joined + // sourcemap would desynchronize the sources/contents. + function fillSourcesContent(len) { + const sourcesContent = []; + for (let i = 0; i < len; i++) + sourcesContent[i] = null; + return sourcesContent; + } + + const INVALID_ORIGINAL_MAPPING = Object.freeze({ + source: null, + line: null, + column: null, + name: null, + }); + const INVALID_GENERATED_MAPPING = Object.freeze({ + line: null, + column: null, + }); + const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; + const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; + const LEAST_UPPER_BOUND = -1; + const GREATEST_LOWER_BOUND = 1; + /** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ + exports.encodedMappings = void 0; + /** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ + exports.decodedMappings = void 0; + /** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ + exports.traceSegment = void 0; + /** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ + exports.originalPositionFor = void 0; + /** + * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided + * the found mapping is from the same source and line as the originalPositionFor mapping. + * + * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1` + * using the same needle that would return `id` when calling `originalPositionFor`. + */ + exports.generatedPositionFor = void 0; + /** + * Iterates each mapping in generated position order. + */ + exports.eachMapping = void 0; + /** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ + exports.presortedDecodedMap = void 0; + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.decodedMap = void 0; + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.encodedMap = void 0; + class TraceMap { + constructor(map, mapUrl) { + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + const isString = typeof map === 'string'; + if (!isString && map.constructor === TraceMap) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + if (sourceRoot || mapUrl) { + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + } + else { + this.resolvedSources = sources.map((s) => s || ''); + } + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + } + } + (() => { + exports.encodedMappings = (map) => { + var _a; + return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = sourcemapCodec.encode(map._decoded))); + }; + exports.decodedMappings = (map) => { + return (map._decoded || (map._decoded = sourcemapCodec.decode(map._encoded))); + }; + exports.traceSegment = (map, line, column) => { + const decoded = exports.decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + }; + exports.originalPositionFor = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = exports.decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return INVALID_ORIGINAL_MAPPING; + const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (segment == null) + return INVALID_ORIGINAL_MAPPING; + if (segment.length == 1) + return INVALID_ORIGINAL_MAPPING; + const { names, resolvedSources } = map; + return { + source: resolvedSources[segment[SOURCES_INDEX]], + line: segment[SOURCE_LINE] + 1, + column: segment[SOURCE_COLUMN], + name: segment.length === 5 ? names[segment[NAMES_INDEX]] : null, + }; + }; + exports.generatedPositionFor = (map, { source, line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return INVALID_GENERATED_MAPPING; + const generated = (map._bySources || (map._bySources = buildBySources(exports.decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const memos = map._bySourceMemos; + const segments = generated[sourceIndex][line]; + if (segments == null) + return INVALID_GENERATED_MAPPING; + const segment = traceSegmentInternal(segments, memos[sourceIndex], line, column, bias || GREATEST_LOWER_BOUND); + if (segment == null) + return INVALID_GENERATED_MAPPING; + return { + line: segment[REV_GENERATED_LINE] + 1, + column: segment[REV_GENERATED_COLUMN], + }; + }; + exports.eachMapping = (map, cb) => { + const decoded = exports.decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + }; + exports.presortedDecodedMap = (map, mapUrl) => { + const clone = Object.assign({}, map); + clone.mappings = []; + const tracer = new TraceMap(clone, mapUrl); + tracer._decoded = map.mappings; + return tracer; + }; + exports.decodedMap = (map) => { + return { + version: 3, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings: exports.decodedMappings(map), + }; + }; + exports.encodedMap = (map) => { + return { + version: 3, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings: exports.encodedMappings(map), + }; + }; + })(); + function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return null; + return segments[index]; + } + + exports.AnyMap = AnyMap; + exports.GREATEST_LOWER_BOUND = GREATEST_LOWER_BOUND; + exports.LEAST_UPPER_BOUND = LEAST_UPPER_BOUND; + exports.TraceMap = TraceMap; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=trace-mapping.umd.js.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map new file mode 100644 index 0000000..4ef72e7 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.umd.js","sources":["../../src/resolve.ts","../../src/strip-filename.ts","../../src/sourcemap-segment.ts","../../src/sort.ts","../../src/binary-search.ts","../../src/by-source.ts","../../src/any-map.ts","../../src/trace-mapping.ts"],"sourcesContent":[null,null,null,null,null,null,null,null],"names":["resolveUri","presortedDecodedMap","decodedMappings","encodedMappings","traceSegment","originalPositionFor","generatedPositionFor","eachMapping","decodedMap","encodedMap","encode","decode","bs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,SAAS,oBAAoB,CAC3B,QAA+C,EAC/C,IAAe,EACf,IAAY,EACZ,MAAc,EACd,IAA4D;QAE5D,IAAI,KAAK,GAAG,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;QAC/D,IAAIS,KAAO,EAAE;YACX,KAAK,GAAG,CAAC,IAAI,KAAK,iBAAiB,GAAG,UAAU,GAAG,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;SACzF;aAAM,IAAI,IAAI,KAAK,iBAAiB;YAAE,KAAK,EAAE,CAAC;QAE/C,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,KAAK,KAAK,QAAQ,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QAC3D,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzB;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts new file mode 100644 index 0000000..08bca6b --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts @@ -0,0 +1,8 @@ +import { TraceMap } from './trace-mapping'; +import type { SectionedSourceMapInput } from './types'; +declare type AnyMap = { + new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; + (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; +}; +export declare const AnyMap: AnyMap; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts new file mode 100644 index 0000000..88820e5 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts @@ -0,0 +1,32 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +export declare type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts new file mode 100644 index 0000000..8d1e538 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts @@ -0,0 +1,7 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; +import type { MemoState } from './binary-search'; +export declare type Source = { + __proto__: null; + [line: number]: Exclude[]; +}; +export default function buildBySources(decoded: readonly SourceMapSegment[][], memos: MemoState[]): Source[]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts new file mode 100644 index 0000000..cf7d4f8 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts @@ -0,0 +1 @@ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts new file mode 100644 index 0000000..2bfb5dc --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts @@ -0,0 +1,2 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export default function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 0000000..6d70924 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,16 @@ +declare type GeneratedColumn = number; +declare type SourcesIndex = number; +declare type SourceLine = number; +declare type SourceColumn = number; +declare type NamesIndex = number; +declare type GeneratedLine = number; +export declare type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts new file mode 100644 index 0000000..bead5c1 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts @@ -0,0 +1,4 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts new file mode 100644 index 0000000..8cd4574 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts @@ -0,0 +1,70 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping } from './types'; +export type { SourceMapSegment } from './sourcemap-segment'; +export type { SourceMapInput, SectionedSourceMapInput, DecodedSourceMap, EncodedSourceMap, SectionedSourceMap, InvalidOriginalMapping, OriginalMapping as Mapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, EachMapping, } from './types'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare let decodedMappings: (map: TraceMap) => Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare let traceSegment: (map: TraceMap, line: number, column: number) => Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare let originalPositionFor: (map: TraceMap, needle: Needle) => OriginalMapping | InvalidOriginalMapping; +/** + * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided + * the found mapping is from the same source and line as the originalPositionFor mapping. + * + * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1` + * using the same needle that would return `id` when calling `originalPositionFor`. + */ +export declare let generatedPositionFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping | InvalidGeneratedMapping; +/** + * Iterates each mapping in generated position order. + */ +export declare let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let decodedMap: (map: TraceMap) => Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let encodedMap: (map: TraceMap) => EncodedSourceMap; +export { AnyMap } from './any-map'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: SourceMapInput, mapUrl?: string | null); +} diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts new file mode 100644 index 0000000..2cc90c0 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts @@ -0,0 +1,85 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { TraceMap } from './trace-mapping'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export declare type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export declare type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export declare type GeneratedMapping = { + line: number; + column: number; +}; +export declare type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export declare type SourceMapInput = string | EncodedSourceMap | DecodedSourceMap | TraceMap; +export declare type SectionedSourceMapInput = SourceMapInput | SectionedSourceMap; +export declare type Needle = { + line: number; + column: number; + bias?: 1 | -1; +}; +export declare type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: 1 | -1; +}; +export declare type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; +} diff --git a/node_modules/@jridgewell/trace-mapping/package.json b/node_modules/@jridgewell/trace-mapping/package.json new file mode 100644 index 0000000..a957780 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/package.json @@ -0,0 +1,70 @@ +{ + "name": "@jridgewell/trace-mapping", + "version": "0.3.9", + "description": "Trace the original position through a source map", + "keywords": [ + "source", + "map" + ], + "main": "dist/trace-mapping.umd.js", + "module": "dist/trace-mapping.mjs", + "typings": "dist/types/trace-mapping.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": { + "browser": "./dist/trace-mapping.umd.js", + "require": "./dist/trace-mapping.umd.js", + "import": "./dist/trace-mapping.mjs" + }, + "./package.json": "./package.json" + }, + "author": "Justin Ridgewell ", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/trace-mapping.git" + }, + "license": "MIT", + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node benchmark/index.mjs", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "ava debug", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts' '**/*.md'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "c8 ava", + "test:watch": "ava --watch" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "ava": "4.0.1", + "benchmark": "2.1.4", + "c8": "7.11.0", + "esbuild": "0.14.14", + "esbuild-node-loader": "0.6.4", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.64.0", + "typescript": "4.5.4" + }, + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } +} diff --git a/node_modules/@nodable/entities/README.md b/node_modules/@nodable/entities/README.md new file mode 100644 index 0000000..18a7fb6 --- /dev/null +++ b/node_modules/@nodable/entities/README.md @@ -0,0 +1,41 @@ +# @nodable/entities + +Fast, zero-dependency XML/HTML entity encoder and decoder for Node.js. + +## Install + +```bash +npm install @nodable/entities +``` + +## Quick start + +```js +import { EntityEncoder, EntityDecoder, ALL_ENTITIES } from '@nodable/entities'; + +// Encode: plain text → entity references +const enc = new EntityEncoder(); +enc.encode('Hello © 2024 & '); +// → 'Hello © 2024 & <stuff>' + +// Decode: entity references → plain text +const dec = new EntityDecoder({ namedEntities: ALL_ENTITIES }); +dec.decode('Hello © 2024 & <stuff>'); +// → 'Hello © 2024 & ' +``` + +## Performance + +| | encode | decode | +|---|---|---| +| `entities` (npm) | 3.65 M req/s | 1.76 M req/s | +| `@nodable/entities` | 3.33 M req/s | **5.19 M req/s** | + +## Documentation + +- [EntityEncoder](docs/EntityEncoder.md) — options, API, recipes +- [EntityDecoder](docs/EntityDecoder.md) — options, API, security limits, entity sets + +## License + +MIT \ No newline at end of file diff --git a/node_modules/@nodable/entities/package.json b/node_modules/@nodable/entities/package.json new file mode 100644 index 0000000..b47e260 --- /dev/null +++ b/node_modules/@nodable/entities/package.json @@ -0,0 +1,54 @@ +{ + "name": "@nodable/entities", + "version": "2.1.0", + "description": "Entity parser for XML, HTML, External entites with security and NCR control", + "main": "./src/index.js", + "type": "module", + "sideEffects": false, + "types": "./src/index.d.ts", + "scripts": { + "test": "node --experimental-vm-modules node_modules/.bin/jest", + "test:watch": "node --experimental-vm-modules node_modules/.bin/jest --watch", + "test:coverage": "node --experimental-vm-modules node_modules/.bin/jest --coverage", + "lint": "eslint src/ test/" + }, + "files": [ + "src", + "README.md" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/nodable/val-parsers.git" + }, + "keywords": [ + "fast", + "xml", + "html", + "entity", + "encode", + "decode", + "ncr", + "security", + "performance" + ], + "author": "Amit Gupta (https://solothought.com)", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "jest": "^29.7.0" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/nodable" + } + ], + "jest": { + "testMatch": [ + "**/?(*.)+(spec|test).[jt]s?(x)", + "**/*_spec.[jt]s?(x)" + ] + } +} \ No newline at end of file diff --git a/node_modules/@nodable/entities/src/EntityDecoder.js b/node_modules/@nodable/entities/src/EntityDecoder.js new file mode 100644 index 0000000..c2aa270 --- /dev/null +++ b/node_modules/@nodable/entities/src/EntityDecoder.js @@ -0,0 +1,543 @@ +// --------------------------------------------------------------------------- +// Built-in named entity map (name → replacement string) +// No regex, no {regex,val} objects — just flat key/value pairs. +// --------------------------------------------------------------------------- + +import { XML as DEFAULT_XML_ENTITIES } from "./entities.js" + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +const SPECIAL_CHARS = new Set('!?\\\\/[]$%{}^&*()<>|+'); + +/** + * Validate that an entity name contains no dangerous characters. + * @param {string} name + * @returns {string} the name, unchanged + * @throws {Error} on invalid characters + */ +function validateEntityName(name) { + if (name[0] === '#') { + throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${name}"`); + } + for (const ch of name) { + if (SPECIAL_CHARS.has(ch)) { + throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: "${name}"`); + } + } + return name; +} + +/** + * Merge one or more entity maps into a flat name→string map. + * Accepts either: + * - plain string values: { amp: '&' } + * - legacy {regex,val} / {regx,val}: { lt: { regex: /.../, val: '<' } } + * + * Values containing '&' are skipped (recursive expansion risk). + * + * @param {...object} maps + * @returns {Record} + */ +function mergeEntityMaps(...maps) { + const out = Object.create(null); + for (const map of maps) { + if (!map) continue; + for (const key of Object.keys(map)) { + const raw = map[key]; + if (typeof raw === 'string') { + out[key] = raw; + } else if (raw && typeof raw === 'object' && raw.val !== undefined) { + // Legacy {regex,val} or {regx,val} — extract the string val only + const val = raw.val; + if (typeof val === 'string') { + out[key] = val; + } + // function vals are not supported in the scanner — skip + } + } + } + return out; +} + +// --------------------------------------------------------------------------- +// applyLimitsTo helpers +// --------------------------------------------------------------------------- + +const LIMIT_TIER_EXTERNAL = 'external'; // input/runtime + persistent external maps +const LIMIT_TIER_BASE = 'base'; // DEFAULT_XML_ENTITIES + namedEntities (system) maps +const LIMIT_TIER_ALL = 'all'; // every entity regardless of tier + +/** + * Resolve `applyLimitsTo` option into a normalised Set of tier strings. + * Accepted values: 'external' | 'base' | 'all' | string[] + * Default: 'external' (only untrusted injected entities are counted). + * @param {string|string[]|undefined} raw + * @returns {Set} + */ +function parseLimitTiers(raw) { + if (!raw || raw === LIMIT_TIER_EXTERNAL) return new Set([LIMIT_TIER_EXTERNAL]); + if (raw === LIMIT_TIER_ALL) return new Set([LIMIT_TIER_ALL]); + if (raw === LIMIT_TIER_BASE) return new Set([LIMIT_TIER_BASE]); + if (Array.isArray(raw)) return new Set(raw); + return new Set([LIMIT_TIER_EXTERNAL]); // safe default for unrecognised values +} + +// --------------------------------------------------------------------------- +// NCR (Numeric Character Reference) classification +// --------------------------------------------------------------------------- + +// Severity order — higher number = stricter action. +// Used to enforce minimum action levels for specific codepoint ranges. +const NCR_LEVEL = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 }); + +// XML 1.0 §2.2: allowed chars are #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] +// Restricted C0: U+0001–U+001F excluding U+0009, U+000A, U+000D +const XML10_ALLOWED_C0 = new Set([0x09, 0x0A, 0x0D]); + +/** + * Parse the `ncr` constructor option into flat, hot-path-friendly fields. + * @param {object|undefined} ncr + * @returns {{ xmlVersion: number, onLevel: number, nullLevel: number }} + */ +function parseNCRConfig(ncr) { + if (!ncr) { + return { xmlVersion: 1.0, onLevel: NCR_LEVEL.allow, nullLevel: NCR_LEVEL.remove }; + } + const xmlVersion = ncr.xmlVersion === 1.1 ? 1.1 : 1.0; + const onLevel = NCR_LEVEL[ncr.onNCR] ?? NCR_LEVEL.allow; + const nullLevel = NCR_LEVEL[ncr.nullNCR] ?? NCR_LEVEL.remove; + // 'allow' is not meaningful for null — clamp to at least 'remove' + const clampedNull = Math.max(nullLevel, NCR_LEVEL.remove); + return { xmlVersion, onLevel, nullLevel: clampedNull }; +} + +// --------------------------------------------------------------------------- +// EntityReplacer +// --------------------------------------------------------------------------- + +/** + * Single-pass, zero-regex entity replacer for XML/HTML content. + * + * Algorithm: scan the string once for '&', read to ';', resolve via map + * or direct codepoint conversion, build output chunks, join once at the end. + * + * Entity lookup priority (highest → lowest): + * 1. input / runtime (DOCTYPE entities for current document) + * 2. persistent external (survive across documents) + * 3. base named map (DEFAULT_XML_ENTITIES + user-supplied namedEntities) + * + * Both input and external resolve as the 'external' tier for limit purposes. + * Base map entities resolve as the 'base' tier. + * + * Numeric / hex references (&#NNN; / &#xHH;) are resolved directly via + * String.fromCodePoint() — no map needed. They count as 'base' tier. + * + * @example + * const replacer = new EntityReplacer({ namedEntities: COMMON_HTML }); + * replacer.setExternalEntities({ brand: 'Acme' }); + * + * const instance = replacer.reset(); + * instance.addInputEntities({ version: '1.0' }); + * instance.encode('&brand; v&version; <'); // 'Acme v1.0 <' + */ +export default class EntityDecoder { + /** + * @param {object} [options] + * @param {object|null} [options.namedEntities] — extra named entities merged into base map + * @param {object} [options.limit] — security limits + * @param {number} [options.limit.maxTotalExpansions=0] — 0 = unlimited + * @param {number} [options.limit.maxExpandedLength=0] — 0 = unlimited + * @param {'external'|'base'|'all'|string[]} [options.limit.applyLimitsTo='external'] + * Which entity tiers count against the security limits: + * - 'external' (default) — only input/runtime + persistent external entities + * - 'base' — only DEFAULT_XML_ENTITIES + namedEntities + * - 'all' — every entity regardless of tier + * - string[] — explicit combination, e.g. ['external', 'base'] + * @param {((resolved: string, original: string) => string)|null} [options.postCheck=null] + * @param {string[]} [options.remove=[]] — entity names (e.g. ['nbsp', '#13']) to delete (replace with empty string) + * @param {string[]} [options.leave=[]] — entity names to keep as literal (unchanged in output) + * @param {object} [options.ncr] — Numeric Character Reference controls + * @param {1.0|1.1} [options.ncr.xmlVersion=1.0] + * XML version governing which codepoint ranges are restricted: + * - 1.0 — C0 controls U+0001–U+001F (except U+0009/000A/000D) are prohibited + * - 1.1 — C0 controls are allowed when written as NCRs; C1 (U+007F–U+009F) decoded as-is + * @param {'allow'|'leave'|'remove'|'throw'} [options.ncr.onNCR='allow'] + * Base action for numeric references. Severity order: allow < leave < remove < throw. + * For codepoint ranges that carry a minimum level (surrogates → remove, XML 1.0 C0 → remove), + * the effective action is max(onNCR, rangeMinimum). + * @param {'remove'|'throw'} [options.ncr.nullNCR='remove'] + * Action for U+0000 (null). 'allow' and 'leave' are clamped to 'remove' since null is never safe. + */ + constructor(options = {}) { + this._limit = options.limit || {}; + this._maxTotalExpansions = this._limit.maxTotalExpansions || 0; + this._maxExpandedLength = this._limit.maxExpandedLength || 0; + this._postCheck = typeof options.postCheck === 'function' ? options.postCheck : r => r; + this._limitTiers = parseLimitTiers(this._limit.applyLimitsTo ?? LIMIT_TIER_EXTERNAL); + this._numericAllowed = options.numericAllowed ?? true; + // Base map: DEFAULT_XML_ENTITIES + user-supplied extras. Immutable after construction. + this._baseMap = mergeEntityMaps(DEFAULT_XML_ENTITIES, options.namedEntities || null); + + // Persistent external entities — survive across documents. + // Stored as a separate map so reset() never touches them. + /** @type {Record} */ + this._externalMap = Object.create(null); + + // Input / runtime entities — current document only, wiped on reset(). + /** @type {Record} */ + this._inputMap = Object.create(null); + + // Per-document counters + this._totalExpansions = 0; + this._expandedLength = 0; + + // --- New: remove / leave sets --- + /** @type {Set} */ + this._removeSet = new Set(options.remove && Array.isArray(options.remove) ? options.remove : []); + /** @type {Set} */ + this._leaveSet = new Set(options.leave && Array.isArray(options.leave) ? options.leave : []); + + // --- NCR config (parsed into flat fields for hot-path speed) --- + const ncrCfg = parseNCRConfig(options.ncr); + this._ncrXmlVersion = ncrCfg.xmlVersion; + this._ncrOnLevel = ncrCfg.onLevel; + this._ncrNullLevel = ncrCfg.nullLevel; + } + + // ------------------------------------------------------------------------- + // Persistent external entity registration + // ------------------------------------------------------------------------- + + /** + * Replace the full set of persistent external entities. + * All keys are validated — throws on invalid characters. + * @param {Record} map + */ + setExternalEntities(map) { + if (map) { + for (const key of Object.keys(map)) { + validateEntityName(key); + } + } + this._externalMap = mergeEntityMaps(map); + } + + /** + * Add a single persistent external entity. + * @param {string} key + * @param {string} value + */ + addExternalEntity(key, value) { + validateEntityName(key); + if (typeof value === 'string' && value.indexOf('&') === -1) { + this._externalMap[key] = value; + } + } + + // ------------------------------------------------------------------------- + // Input / runtime entity registration (per document) + // ------------------------------------------------------------------------- + + /** + * Inject DOCTYPE entities for the current document. + * Also resets per-document expansion counters. + * @param {Record} map + */ + addInputEntities(map) { + this._totalExpansions = 0; + this._expandedLength = 0; + this._inputMap = mergeEntityMaps(map); + } + + // ------------------------------------------------------------------------- + // Per-document reset + // ------------------------------------------------------------------------- + + /** + * Wipe input/runtime entities and reset counters. + * Call this before processing each new document. + * @returns {this} + */ + reset() { + this._inputMap = Object.create(null); + this._totalExpansions = 0; + this._expandedLength = 0; + return this; + } + + // ------------------------------------------------------------------------- + // XML version (can be set after construction, e.g. once parser reads ) + // ------------------------------------------------------------------------- + + /** + * Update the XML version used for NCR classification. + * Call this as soon as the document's `` declaration is parsed. + * @param {1.0|1.1|number} version + */ + setXmlVersion(version) { + this._ncrXmlVersion = version === 1.1 ? 1.1 : 1.0; + } + + // ------------------------------------------------------------------------- + // Primary API + // ------------------------------------------------------------------------- + + /** + * Replace all entity references in `str` in a single pass. + * + * @param {string} str + * @returns {string} + */ + decode(str) { + if (typeof str !== 'string' || str.length === 0) return str; + //TODO: check if needed + //if (str.indexOf('&') === -1) return str; // fast path — no entities at all + + const original = str; + const chunks = []; + const len = str.length; + let last = 0; // start of next unprocessed literal chunk + let i = 0; + + const limitExpansions = this._maxTotalExpansions > 0; + const limitLength = this._maxExpandedLength > 0; + const checkLimits = limitExpansions || limitLength; + + while (i < len) { + // Scan forward to next '&' + if (str.charCodeAt(i) !== 38 /* '&' */) { i++; continue; } + + // --- Found '&' at position i --- + + // Scan forward to ';' + let j = i + 1; + while (j < len && str.charCodeAt(j) !== 59 /* ';' */ && (j - i) <= 32) j++; + + if (j >= len || str.charCodeAt(j) !== 59) { + // No closing ';' within window — treat '&' as literal + i++; + continue; + } + + // Raw token between '&' and ';' (exclusive) + const token = str.slice(i + 1, j); + if (token.length === 0) { i++; continue; } + + let replacement; + let tier; // which limit tier this entity belongs to + + if (this._removeSet.has(token)) { + // Remove entity: replace with empty string + replacement = ''; + // If entity was unknown (replacement undefined), we still need a tier for limits. + // Treat as external tier because it's user-directed removal of an unknown reference. + if (tier === undefined) { + tier = LIMIT_TIER_EXTERNAL; + } + } else if (this._leaveSet.has(token)) { + // Do not replace — keep original &token; as literal + i++; + continue; + } else if (token.charCodeAt(0) === 35 /* '#' */) { + // ---- Numeric / NCR reference ---- + // NCR classification always runs first — prohibited codepoints must be + // caught regardless of numericAllowed. + const ncrResult = this._resolveNCR(token); + if (ncrResult === undefined) { + // 'leave' action — keep original &token; as-is + i++; + continue; + } + replacement = ncrResult; // '' for remove, char string for allow + tier = LIMIT_TIER_BASE; + } else { + // ---- Named reference ---- + const resolved = this._resolveName(token); + replacement = resolved?.value; + tier = resolved?.tier; + } + + if (replacement === undefined) { + // Unknown entity — leave as-is, advance past '&' only + i++; + continue; + } + + // Flush literal chunk before this entity + if (i > last) chunks.push(str.slice(last, i)); + chunks.push(replacement); + last = j + 1; // skip past ';' + i = last; + + // Apply expansion limits only if this tier is being tracked + if (checkLimits && this._tierCounts(tier)) { + if (limitExpansions) { + this._totalExpansions++; + if (this._totalExpansions > this._maxTotalExpansions) { + throw new Error( + `[EntityReplacer] Entity expansion count limit exceeded: ` + + `${this._totalExpansions} > ${this._maxTotalExpansions}` + ); + } + } + if (limitLength) { + // delta: replacement.length minus the raw &token; length (token.length + 2 for '&' and ';') + const delta = replacement.length - (token.length + 2); + if (delta > 0) { + this._expandedLength += delta; + if (this._expandedLength > this._maxExpandedLength) { + throw new Error( + `[EntityReplacer] Expanded content length limit exceeded: ` + + `${this._expandedLength} > ${this._maxExpandedLength}` + ); + } + } + } + } + } + + // Flush trailing literal + if (last < len) chunks.push(str.slice(last)); + + // If nothing was replaced, chunks is empty — return original + const result = chunks.length === 0 ? str : chunks.join(''); + + return this._postCheck(result, original); + } + + // ------------------------------------------------------------------------- + // Private: limit tier check + // ------------------------------------------------------------------------- + + /** + * Returns true if a resolved entity of the given tier should count + * against the expansion/length limits. + * @param {string} tier — LIMIT_TIER_EXTERNAL | LIMIT_TIER_BASE + * @returns {boolean} + */ + _tierCounts(tier) { + if (this._limitTiers.has(LIMIT_TIER_ALL)) return true; + return this._limitTiers.has(tier); + } + + // ------------------------------------------------------------------------- + // Private: entity resolution + // ------------------------------------------------------------------------- + + /** + * Resolve a named entity token (without & and ;). + * Priority: inputMap > externalMap > baseMap + * Returns the resolved value tagged with its limit tier. + * + * @param {string} name + * @returns {{ value: string, tier: string }|undefined} + */ + _resolveName(name) { + // input and external both count as 'external' tier for limit purposes — + // they are injected at runtime and are the untrusted surface. + if (name in this._inputMap) return { value: this._inputMap[name], tier: LIMIT_TIER_EXTERNAL }; + if (name in this._externalMap) return { value: this._externalMap[name], tier: LIMIT_TIER_EXTERNAL }; + if (name in this._baseMap) return { value: this._baseMap[name], tier: LIMIT_TIER_BASE }; + return undefined; + } + + /** + * Classify a codepoint and return the minimum action level that must be applied. + * Returns -1 when no minimum is imposed (normal allow path). + * + * Ranges checked (in priority order): + * 1. U+0000 — null, governed by nullNCR (always ≥ remove) + * 2. U+D800–U+DFFF — surrogates, always prohibited (min: remove) + * 3. U+0001–U+001F \ {0x09,0x0A,0x0D} — XML 1.0 restricted C0 (min: remove) + * (skipped in XML 1.1 — C0 controls are allowed when written as NCRs) + * + * @param {number} cp — codepoint + * @returns {number} — minimum NCR_LEVEL value, or -1 for no restriction + */ + _classifyNCR(cp) { + // 1. Null + if (cp === 0) return this._ncrNullLevel; + + // 2. Surrogates — always prohibited, minimum 'remove' + if (cp >= 0xD800 && cp <= 0xDFFF) return NCR_LEVEL.remove; + + // 3. XML 1.0 restricted C0 controls + if (this._ncrXmlVersion === 1.0) { + if (cp >= 0x01 && cp <= 0x1F && !XML10_ALLOWED_C0.has(cp)) return NCR_LEVEL.remove; + } + + return -1; // no restriction + } + + /** + * Execute a resolved NCR action. + * + * @param {number} action — NCR_LEVEL value + * @param {string} token — raw token (e.g. '#38') for error messages + * @param {number} cp — codepoint, used only for error messages + * @returns {string|undefined} + * - decoded character string → 'allow' + * - '' → 'remove' + * - undefined → 'leave' (caller must skip past '&' only) + * - throws Error → 'throw' + */ + _applyNCRAction(action, token, cp) { + switch (action) { + case NCR_LEVEL.allow: return String.fromCodePoint(cp); + case NCR_LEVEL.remove: return ''; + case NCR_LEVEL.leave: return undefined; // signal: keep literal + case NCR_LEVEL.throw: + throw new Error( + `[EntityDecoder] Prohibited numeric character reference ` + + `&${token}; (U+${cp.toString(16).toUpperCase().padStart(4, '0')})` + ); + default: return String.fromCodePoint(cp); + } + } + + /** + * Full NCR resolution pipeline for a numeric token. + * + * Steps: + * 1. Parse the codepoint (decimal or hex). + * 2. Validate the raw codepoint range (NaN, <0, >0x10FFFF). + * 3. If numericAllowed is false and no minimum restriction applies → leave as-is. + * 4. Classify the codepoint to find the minimum required action level. + * 5. Resolve effective action = max(onNCR, minimum). + * 6. Apply and return. + * + * @param {string} token — e.g. '#38', '#x26', '#X26' + * @returns {string|undefined} + * - string (incl. '') — replacement ('' = remove) + * - undefined — leave original &token; as-is + */ + _resolveNCR(token) { + // Step 1: parse codepoint + const second = token.charCodeAt(1); + let cp; + if (second === 120 /* x */ || second === 88 /* X */) { + cp = parseInt(token.slice(2), 16); + } else { + cp = parseInt(token.slice(1), 10); + } + + // Step 2: out-of-range → leave as-is unconditionally + if (Number.isNaN(cp) || cp < 0 || cp > 0x10FFFF) return undefined; + + // Step 3: classify to get minimum action level + const minimum = this._classifyNCR(cp); + + // Step 4: if numericAllowed is false and no hard minimum → leave + if (!this._numericAllowed && minimum < NCR_LEVEL.remove) return undefined; + + // Step 5: effective action = max(configured onNCR, range minimum) + const effective = minimum === -1 + ? this._ncrOnLevel + : Math.max(this._ncrOnLevel, minimum); + + // Step 6: apply + return this._applyNCRAction(effective, token, cp); + } +} \ No newline at end of file diff --git a/node_modules/@nodable/entities/src/EntityEncoder.js b/node_modules/@nodable/entities/src/EntityEncoder.js new file mode 100644 index 0000000..a53f5a3 --- /dev/null +++ b/node_modules/@nodable/entities/src/EntityEncoder.js @@ -0,0 +1,194 @@ +// EntityDecoder.js +import { trie1, trie2, trie3 } from './entityTries.js'; + +// Replacement strings indexed by char code — direct array access, no hashing +const XML_UNSAFE_REPLACEMENT = new Array(128); +XML_UNSAFE_REPLACEMENT[38] = '&'; // & +XML_UNSAFE_REPLACEMENT[60] = '<'; // < +XML_UNSAFE_REPLACEMENT[62] = '>'; // > +XML_UNSAFE_REPLACEMENT[34] = '"'; // " +XML_UNSAFE_REPLACEMENT[39] = '''; // ' + +// Typed bitmask for O(1) "is this ASCII code XML-unsafe?" check +const IS_XML_UNSAFE = new Uint8Array(128); +IS_XML_UNSAFE[38] = 1; +IS_XML_UNSAFE[60] = 1; +IS_XML_UNSAFE[62] = 1; +IS_XML_UNSAFE[34] = 1; +IS_XML_UNSAFE[39] = 1; + +// Fast pre-scan: bail out immediately if nothing needs encoding +const NEEDS_PROCESSING = /[&<>"'\u0080-\uFFFF]/; + +export default class EntityEncoder { + constructor(options = {}) { + this.encodeXmlSafe = options.encodeXmlSafe !== false; + this.encodeAllNamed = options.encodeAllNamed !== false; + this.maxReplacements = options.maxReplacements || 0; + this.replacementsCount = 0; + } + + encode(str) { + if (typeof str !== 'string' || str.length === 0) return str; + if (!NEEDS_PROCESSING.test(str)) return str; + + const maxRep = this.maxReplacements; + if (maxRep > 0 && this.replacementsCount >= maxRep) return str; + + // Hoist to locals — avoids `this` property lookup inside the hot loop + const encodeXmlSafe = this.encodeXmlSafe; + const encodeAllNamed = this.encodeAllNamed; + + const len = str.length; + + let result = ''; + let last = 0; + let i = 0; + let limitReached = false; + + // ── Main loop: runs to len-2 so trie3 never needs a bounds check ──────── + // The last 2 characters are handled by the tail block below. + const mainEnd = len - 2; // i <= mainEnd guarantees i+1 and i+2 are valid + + while (i <= mainEnd && !limitReached) { + const c0 = str.charCodeAt(i); + + // ── ASCII branch ─────────────────────────────────────────────────── + if (c0 < 128) { + if (encodeXmlSafe && IS_XML_UNSAFE[c0] === 1) { + result += str.substring(last, i) + XML_UNSAFE_REPLACEMENT[c0]; + last = ++i; + if (maxRep > 0) { + this.replacementsCount++; + if (this.replacementsCount >= maxRep) { + limitReached = true; + break; + } + } + } else { + // Bulk-skip: advance to the next interesting position without + // touching the outer loop overhead on every safe character + i++; + while (i <= mainEnd && !limitReached) { + const c = str.charCodeAt(i); + if (c >= 128 || (encodeXmlSafe && IS_XML_UNSAFE[c] === 1)) break; + i++; + } + } + continue; + } + + // ── Non-ASCII: integer-keyed trie lookup ─────────────────────────── + // No bounds checks needed for c1/c2 because i <= mainEnd guarantees + // i+1 and i+2 are both within the string. + let matchedEntity = null; + let advance = 1; + + // Try 3-char match first (longest wins) + const mid3 = trie3.get(c0); + if (mid3 !== undefined) { + const c1 = str.charCodeAt(i + 1); + const inner3 = mid3.get(c1); + if (inner3 !== undefined) { + const c2 = str.charCodeAt(i + 2); + const candidate = inner3.get(c2); + if (candidate !== undefined) { matchedEntity = candidate; advance = 3; } + } + } + + // Try 2-char match + if (matchedEntity === null) { + const inner2 = trie2.get(c0); + if (inner2 !== undefined) { + const c1 = str.charCodeAt(i + 1); + const candidate = inner2.get(c1); + if (candidate !== undefined) { matchedEntity = candidate; advance = 2; } + } + } + + // Try 1-char match + if (matchedEntity === null && encodeAllNamed) { + const candidate = trie1.get(c0); + if (candidate !== undefined) { matchedEntity = candidate; } + } + + if (matchedEntity !== null) { + result += str.substring(last, i) + matchedEntity; + i += advance; + last = i; + if (maxRep > 0) { + this.replacementsCount++; + if (this.replacementsCount >= maxRep) { + limitReached = true; + break; + } + } + } else { + i++; + } + } + + // ── Tail: handle the last 1-2 characters (no 3-char match possible) ──── + while (i < len && !limitReached) { + const c0 = str.charCodeAt(i); + + if (c0 < 128) { + if (encodeXmlSafe && IS_XML_UNSAFE[c0] === 1) { + result += str.substring(last, i) + XML_UNSAFE_REPLACEMENT[c0]; + last = ++i; + if (maxRep > 0) { + this.replacementsCount++; + if (this.replacementsCount >= maxRep) { + limitReached = true; + break; + } + } + } else { + i++; + } + continue; + } + + // Non-ASCII tail — only 2-char and 1-char matches are possible here + let matchedEntity = null; + let advance = 1; + + if (i + 1 < len) { + const inner2 = trie2.get(c0); + if (inner2 !== undefined) { + const c1 = str.charCodeAt(i + 1); + const candidate = inner2.get(c1); + if (candidate !== undefined) { matchedEntity = candidate; advance = 2; } + } + } + + if (matchedEntity === null && encodeAllNamed) { + const candidate = trie1.get(c0); + if (candidate !== undefined) { matchedEntity = candidate; } + } + + if (matchedEntity !== null) { + result += str.substring(last, i) + matchedEntity; + i += advance; + last = i; + if (maxRep > 0) { + this.replacementsCount++; + if (this.replacementsCount >= maxRep) { + limitReached = true; + break; + } + } + } else { + i++; + } + } + + // ── Flush any remaining literal suffix ──────────────────────────────── + if (last < len) result += str.substring(last); + return result; + } + + reset() { + this.replacementsCount = 0; + } +} \ No newline at end of file diff --git a/node_modules/@nodable/entities/src/entities.js b/node_modules/@nodable/entities/src/entities.js new file mode 100644 index 0000000..46e8a88 --- /dev/null +++ b/node_modules/@nodable/entities/src/entities.js @@ -0,0 +1,1177 @@ +// --------------------------------------------------------------------------- +// Complete HTML5 named entity reference +// Organized by logical categories for easy maintenance and selective importing +// --------------------------------------------------------------------------- + +/** + * Basic Latin & Special Characters + * @type {Record} + */ +export const BASIC_LATIN = { + amp: '&', + AMP: '&', + lt: '<', + LT: '<', + gt: '>', + GT: '>', + quot: '"', + QUOT: '"', + apos: "'", + lsquo: '‘', + rsquo: '’', + ldquo: '“', + rdquo: '”', + lsquor: '‚', + rsquor: '’', + ldquor: '„', + bdquo: '„', + comma: ',', + period: '.', + colon: ':', + semi: ';', + excl: '!', + quest: '?', + num: '#', + dollar: '$', + percent: '%', + amp: '&', + ast: '*', + commat: '@', + lowbar: '_', + verbar: '|', + vert: '|', + sol: '/', + bsol: '\\', + lbrace: '{', + rbrace: '}', + lbrack: '[', + rbrack: ']', + lpar: '(', + rpar: ')', + nbsp: '\u00a0', + iexcl: '¡', + cent: '¢', + pound: '£', + curren: '¤', + yen: '¥', + brvbar: '¦', + sect: '§', + uml: '¨', + copy: '©', + COPY: '©', + ordf: 'ª', + laquo: '«', + not: '¬', + shy: '\u00ad', + reg: '®', + REG: '®', + macr: '¯', + deg: '°', + plusmn: '±', + sup2: '²', + sup3: '³', + acute: '´', + micro: 'µ', + para: '¶', + middot: '·', + cedil: '¸', + sup1: '¹', + ordm: 'º', + raquo: '»', + frac14: '¼', + frac12: '½', + half: '½', + frac34: '¾', + iquest: '¿', + times: '×', + div: '÷', + divide: '÷', +}; + +/** + * Latin Extended & Accented Letters (A-Z) + * @type {Record} + */ +export const LATIN_ACCENTS = { + Agrave: 'À', + agrave: 'à', + Aacute: 'Á', + aacute: 'á', + Acirc: 'Â', + acirc: 'â', + Atilde: 'Ã', + atilde: 'ã', + Auml: 'Ä', + auml: 'ä', + Aring: 'Å', + aring: 'å', + AElig: 'Æ', + aelig: 'æ', + Ccedil: 'Ç', + ccedil: 'ç', + Egrave: 'È', + egrave: 'è', + Eacute: 'É', + eacute: 'é', + Ecirc: 'Ê', + ecirc: 'ê', + Euml: 'Ë', + euml: 'ë', + Igrave: 'Ì', + igrave: 'ì', + Iacute: 'Í', + iacute: 'í', + Icirc: 'Î', + icirc: 'î', + Iuml: 'Ï', + iuml: 'ï', + ETH: 'Ð', + eth: 'ð', + Ntilde: 'Ñ', + ntilde: 'ñ', + Ograve: 'Ò', + ograve: 'ò', + Oacute: 'Ó', + oacute: 'ó', + Ocirc: 'Ô', + ocirc: 'ô', + Otilde: 'Õ', + otilde: 'õ', + Ouml: 'Ö', + ouml: 'ö', + Oslash: 'Ø', + oslash: 'ø', + Ugrave: 'Ù', + ugrave: 'ù', + Uacute: 'Ú', + uacute: 'ú', + Ucirc: 'Û', + ucirc: 'û', + Uuml: 'Ü', + uuml: 'ü', + Yacute: 'Ý', + yacute: 'ý', + THORN: 'Þ', + thorn: 'þ', + szlig: 'ß', + yuml: 'ÿ', + Yuml: 'Ÿ', +}; + +/** + * Latin Extended (Letters with diacritics) + * @type {Record} + */ +export const LATIN_EXTENDED = { + Amacr: 'Ā', + amacr: 'ā', + Abreve: 'Ă', + abreve: 'ă', + Aogon: 'Ą', + aogon: 'ą', + Cacute: 'Ć', + cacute: 'ć', + Ccirc: 'Ĉ', + ccirc: 'ĉ', + Cdot: 'Ċ', + cdot: 'ċ', + Ccaron: 'Č', + ccaron: 'č', + Dcaron: 'Ď', + dcaron: 'ď', + Dstrok: 'Đ', + dstrok: 'đ', + Emacr: 'Ē', + emacr: 'ē', + Ecaron: 'Ě', + ecaron: 'ě', + Edot: 'Ė', + edot: 'ė', + Eogon: 'Ę', + eogon: 'ę', + Gcirc: 'Ĝ', + gcirc: 'ĝ', + Gbreve: 'Ğ', + gbreve: 'ğ', + Gdot: 'Ġ', + gdot: 'ġ', + Gcedil: 'Ģ', + Hcirc: 'Ĥ', + hcirc: 'ĥ', + Hstrok: 'Ħ', + hstrok: 'ħ', + Itilde: 'Ĩ', + itilde: 'ĩ', + Imacr: 'Ī', + imacr: 'ī', + Iogon: 'Į', + iogon: 'į', + Idot: 'İ', + IJlig: 'IJ', + ijlig: 'ij', + Jcirc: 'Ĵ', + jcirc: 'ĵ', + Kcedil: 'Ķ', + kcedil: 'ķ', + kgreen: 'ĸ', + Lacute: 'Ĺ', + lacute: 'ĺ', + Lcedil: 'Ļ', + lcedil: 'ļ', + Lcaron: 'Ľ', + lcaron: 'ľ', + Lmidot: 'Ŀ', + lmidot: 'ŀ', + Lstrok: 'Ł', + lstrok: 'ł', + Nacute: 'Ń', + nacute: 'ń', + Ncaron: 'Ň', + ncaron: 'ň', + Ncedil: 'Ņ', + ncedil: 'ņ', + ENG: 'Ŋ', + eng: 'ŋ', + Omacr: 'Ō', + omacr: 'ō', + Odblac: 'Ő', + odblac: 'ő', + OElig: 'Œ', + oelig: 'œ', + Racute: 'Ŕ', + racute: 'ŕ', + Rcaron: 'Ř', + rcaron: 'ř', + Rcedil: 'Ŗ', + rcedil: 'ŗ', + Sacute: 'Ś', + sacute: 'ś', + Scirc: 'Ŝ', + scirc: 'ŝ', + Scedil: 'Ş', + scedil: 'ş', + Scaron: 'Š', + scaron: 'š', + Tcedil: 'Ţ', + tcedil: 'ţ', + Tcaron: 'Ť', + tcaron: 'ť', + Tstrok: 'Ŧ', + tstrok: 'ŧ', + Utilde: 'Ũ', + utilde: 'ũ', + Umacr: 'Ū', + umacr: 'ū', + Ubreve: 'Ŭ', + ubreve: 'ŭ', + Uring: 'Ů', + uring: 'ů', + Udblac: 'Ű', + udblac: 'ű', + Uogon: 'Ų', + uogon: 'ų', + Wcirc: 'Ŵ', + wcirc: 'ŵ', + Ycirc: 'Ŷ', + ycirc: 'ŷ', + Zacute: 'Ź', + zacute: 'ź', + Zdot: 'Ż', + zdot: 'ż', + Zcaron: 'Ž', + zcaron: 'ž', +}; + +/** + * Greek Letters + * @type {Record} + */ +export const GREEK = { + Alpha: 'Α', + alpha: 'α', + Beta: 'Β', + beta: 'β', + Gamma: 'Γ', + gamma: 'γ', + Delta: 'Δ', + delta: 'δ', + Epsilon: 'Ε', + epsilon: 'ε', + epsiv: 'ϵ', + varepsilon: 'ϵ', + Zeta: 'Ζ', + zeta: 'ζ', + Eta: 'Η', + eta: 'η', + Theta: 'Θ', + theta: 'θ', + thetasym: 'ϑ', + vartheta: 'ϑ', + Iota: 'Ι', + iota: 'ι', + Kappa: 'Κ', + kappa: 'κ', + kappav: 'ϰ', + varkappa: 'ϰ', + Lambda: 'Λ', + lambda: 'λ', + Mu: 'Μ', + mu: 'μ', + Nu: 'Ν', + nu: 'ν', + Xi: 'Ξ', + xi: 'ξ', + Omicron: 'Ο', + omicron: 'ο', + Pi: 'Π', + pi: 'π', + piv: 'ϖ', + varpi: 'ϖ', + Rho: 'Ρ', + rho: 'ρ', + rhov: 'ϱ', + varrho: 'ϱ', + Sigma: 'Σ', + sigma: 'σ', + sigmaf: 'ς', + sigmav: 'ς', + varsigma: 'ς', + Tau: 'Τ', + tau: 'τ', + Upsilon: 'Υ', + upsilon: 'υ', + upsi: 'υ', + Upsi: 'ϒ', + upsih: 'ϒ', + Phi: 'Φ', + phi: 'φ', + phiv: 'ϕ', + varphi: 'ϕ', + Chi: 'Χ', + chi: 'χ', + Psi: 'Ψ', + psi: 'ψ', + Omega: 'Ω', + omega: 'ω', + ohm: 'Ω', + Gammad: 'Ϝ', + gammad: 'ϝ', + digamma: 'ϝ', +}; + +/** + * Cyrillic Letters + * @type {Record} + */ +export const CYRILLIC = { + Afr: '𝔄', + afr: '𝔞', + Acy: 'А', + acy: 'а', + Bcy: 'Б', + bcy: 'б', + Vcy: 'В', + vcy: 'в', + Gcy: 'Г', + gcy: 'г', + Dcy: 'Д', + dcy: 'д', + IEcy: 'Е', + iecy: 'е', + IOcy: 'Ё', + iocy: 'ё', + ZHcy: 'Ж', + zhcy: 'ж', + Zcy: 'З', + zcy: 'з', + Icy: 'И', + icy: 'и', + Jcy: 'Й', + jcy: 'й', + Kcy: 'К', + kcy: 'к', + Lcy: 'Л', + lcy: 'л', + Mcy: 'М', + mcy: 'м', + Ncy: 'Н', + ncy: 'н', + Ocy: 'О', + ocy: 'о', + Pcy: 'П', + pcy: 'п', + Rcy: 'Р', + rcy: 'р', + Scy: 'С', + scy: 'с', + Tcy: 'Т', + tcy: 'т', + Ucy: 'У', + ucy: 'у', + Fcy: 'Ф', + fcy: 'ф', + KHcy: 'Х', + khcy: 'х', + TScy: 'Ц', + tscy: 'ц', + CHcy: 'Ч', + chcy: 'ч', + SHcy: 'Ш', + shcy: 'ш', + SHCHcy: 'Щ', + shchcy: 'щ', + HARDcy: 'Ъ', + hardcy: 'ъ', + Ycy: 'Ы', + ycy: 'ы', + SOFTcy: 'Ь', + softcy: 'ь', + Ecy: 'Э', + ecy: 'э', + YUcy: 'Ю', + yucy: 'ю', + YAcy: 'Я', + yacy: 'я', + DJcy: 'Ђ', + djcy: 'ђ', + GJcy: 'Ѓ', + gjcy: 'ѓ', + Jukcy: 'Є', + jukcy: 'є', + DScy: 'Ѕ', + dscy: 'ѕ', + Iukcy: 'І', + iukcy: 'і', + YIcy: 'Ї', + yicy: 'ї', + Jsercy: 'Ј', + jsercy: 'ј', + LJcy: 'Љ', + ljcy: 'љ', + NJcy: 'Њ', + njcy: 'њ', + TSHcy: 'Ћ', + tshcy: 'ћ', + KJcy: 'Ќ', + kjcy: 'ќ', + Ubrcy: 'Ў', + ubrcy: 'ў', + DZcy: 'Џ', + dzcy: 'џ', +}; + +/** + * Mathematical Operators & Relations + * @type {Record} + */ +export const MATH = { + plus: '+', + minus: '−', + mnplus: '∓', + mp: '∓', + pm: '±', + times: '×', + div: '÷', + divide: '÷', + sdot: '⋅', + star: '☆', + starf: '★', + bigstar: '★', + lowast: '∗', + ast: '*', + midast: '*', + compfn: '∘', + smallcircle: '∘', + bullet: '•', + bull: '•', + nbsp: '\u00a0', + hellip: '…', + mldr: '…', + prime: '′', + Prime: '″', + tprime: '‴', + bprime: '‵', + backprime: '‵', + minus: '−', + minusd: '∸', + dotminus: '∸', + plusdo: '∔', + dotplus: '∔', + plusmn: '±', + minusplus: '∓', + mnplus: '∓', + mp: '∓', + setminus: '∖', + smallsetminus: '∖', + Backslash: '∖', + setmn: '∖', + ssetmn: '∖', + lowbar: '_', + verbar: '|', + vert: '|', + VerticalLine: '|', + colon: ':', + Colon: '∷', + Proportion: '∷', + ratio: '∶', + equals: '=', + ne: '≠', + nequiv: '≢', + equiv: '≡', + Congruent: '≡', + sim: '∼', + thicksim: '∼', + thksim: '∼', + sime: '≃', + simeq: '≃', + TildeEqual: '≃', + asymp: '≈', + approx: '≈', + thickapprox: '≈', + thkap: '≈', + TildeTilde: '≈', + ncong: '≇', + cong: '≅', + TildeFullEqual: '≅', + asympeq: '≍', + CupCap: '≍', + bump: '≎', + Bumpeq: '≎', + HumpDownHump: '≎', + bumpe: '≏', + bumpeq: '≏', + HumpEqual: '≏', + dotminus: '∸', + minusd: '∸', + plusdo: '∔', + dotplus: '∔', + le: '≤', + LessEqual: '≤', + ge: '≥', + GreaterEqual: '≥', + lesseqgtr: '⋚', + lesseqqgtr: '⪋', + greater: '>', + less: '<', +}; + +/** + * Mathematical Operators (Advanced) + * @type {Record} + */ +export const MATH_ADVANCED = { + alefsym: 'ℵ', + aleph: 'ℵ', + beth: 'ℶ', + gimel: 'ℷ', + daleth: 'ℸ', + forall: '∀', + ForAll: '∀', + part: '∂', + PartialD: '∂', + exist: '∃', + Exists: '∃', + nexist: '∄', + nexists: '∄', + empty: '∅', + emptyset: '∅', + emptyv: '∅', + varnothing: '∅', + nabla: '∇', + Del: '∇', + isin: '∈', + isinv: '∈', + in: '∈', + Element: '∈', + notin: '∉', + notinva: '∉', + ni: '∋', + niv: '∋', + SuchThat: '∋', + ReverseElement: '∋', + notni: '∌', + notniva: '∌', + prod: '∏', + Product: '∏', + coprod: '∐', + Coproduct: '∐', + sum: '∑', + Sum: '∑', + minus: '−', + mp: '∓', + plusdo: '∔', + dotplus: '∔', + setminus: '∖', + lowast: '∗', + radic: '√', + Sqrt: '√', + prop: '∝', + propto: '∝', + Proportional: '∝', + varpropto: '∝', + infin: '∞', + infintie: '⧝', + ang: '∠', + angle: '∠', + angmsd: '∡', + measuredangle: '∡', + angsph: '∢', + mid: '∣', + VerticalBar: '∣', + nmid: '∤', + nsmid: '∤', + npar: '∦', + parallel: '∥', + spar: '∥', + nparallel: '∦', + nspar: '∦', + and: '∧', + wedge: '∧', + or: '∨', + vee: '∨', + cap: '∩', + cup: '∪', + int: '∫', + Integral: '∫', + conint: '∮', + ContourIntegral: '∮', + Conint: '∯', + DoubleContourIntegral: '∯', + Cconint: '∰', + there4: '∴', + therefore: '∴', + Therefore: '∴', + becaus: '∵', + because: '∵', + Because: '∵', + ratio: '∶', + Proportion: '∷', + minusd: '∸', + dotminus: '∸', + mDDot: '∺', + homtht: '∻', + sim: '∼', + bsimg: '∽', + backsim: '∽', + ac: '∾', + mstpos: '∾', + acd: '∿', + VerticalTilde: '≀', + wr: '≀', + wreath: '≀', + nsime: '≄', + nsimeq: '≄', + nsimeq: '≄', + ncong: '≇', + simne: '≆', + ncongdot: '⩭̸', + ngsim: '≵', + nsim: '≁', + napprox: '≉', + nap: '≉', + ngeq: '≱', + nge: '≱', + nleq: '≰', + nle: '≰', + ngtr: '≯', + ngt: '≯', + nless: '≮', + nlt: '≮', + nprec: '⊀', + npr: '⊀', + nsucc: '⊁', + nsc: '⊁', +}; + +/** + * Arrows + * @type {Record} + */ +export const ARROWS = { + larr: '←', + leftarrow: '←', + LeftArrow: '←', + uarr: '↑', + uparrow: '↑', + UpArrow: '↑', + rarr: '→', + rightarrow: '→', + RightArrow: '→', + darr: '↓', + downarrow: '↓', + DownArrow: '↓', + harr: '↔', + leftrightarrow: '↔', + LeftRightArrow: '↔', + varr: '↕', + updownarrow: '↕', + UpDownArrow: '↕', + nwarr: '↖', + nwarrow: '↖', + UpperLeftArrow: '↖', + nearr: '↗', + nearrow: '↗', + UpperRightArrow: '↗', + searr: '↘', + searrow: '↘', + LowerRightArrow: '↘', + swarr: '↙', + swarrow: '↙', + LowerLeftArrow: '↙', + lArr: '⇐', + Leftarrow: '⇐', + uArr: '⇑', + Uparrow: '⇑', + rArr: '⇒', + Rightarrow: '⇒', + dArr: '⇓', + Downarrow: '⇓', + hArr: '⇔', + Leftrightarrow: '⇔', + iff: '⇔', + vArr: '⇕', + Updownarrow: '⇕', + lAarr: '⇚', + Lleftarrow: '⇚', + rAarr: '⇛', + Rrightarrow: '⇛', + lrarr: '⇆', + leftrightarrows: '⇆', + rlarr: '⇄', + rightleftarrows: '⇄', + lrhar: '⇋', + leftrightharpoons: '⇋', + ReverseEquilibrium: '⇋', + rlhar: '⇌', + rightleftharpoons: '⇌', + Equilibrium: '⇌', + udarr: '⇅', + UpArrowDownArrow: '⇅', + duarr: '⇵', + DownArrowUpArrow: '⇵', + llarr: '⇇', + leftleftarrows: '⇇', + rrarr: '⇉', + rightrightarrows: '⇉', + ddarr: '⇊', + downdownarrows: '⇊', + har: '↽', + lhard: '↽', + leftharpoondown: '↽', + lharu: '↼', + leftharpoonup: '↼', + rhard: '⇁', + rightharpoondown: '⇁', + rharu: '⇀', + rightharpoonup: '⇀', + lsh: '↰', + Lsh: '↰', + rsh: '↱', + Rsh: '↱', + ldsh: '↲', + rdsh: '↳', + hookleftarrow: '↩', + hookrightarrow: '↪', + mapstoleft: '↤', + mapstoup: '↥', + map: '↦', + mapsto: '↦', + mapstodown: '↧', + crarr: '↵', + nwarrow: '↖', + nearrow: '↗', + searrow: '↘', + swarrow: '↙', + nleftarrow: '↚', + nleftrightarrow: '↮', + nrightarrow: '↛', + nrarr: '↛', + larrtl: '↢', + rarrtl: '↣', + leftarrowtail: '↢', + rightarrowtail: '↣', + twoheadleftarrow: '↞', + twoheadrightarrow: '↠', + Larr: '↞', + Rarr: '↠', + larrhk: '↩', + rarrhk: '↪', + larrlp: '↫', + looparrowleft: '↫', + rarrlp: '↬', + looparrowright: '↬', + harrw: '↭', + leftrightsquigarrow: '↭', + nrarrw: '↝̸', + rarrw: '↝', + rightsquigarrow: '↝', + larrbfs: '⤟', + rarrbfs: '⤠', + nvHarr: '⤄', + nvlArr: '⤂', + nvrArr: '⤃', + larrfs: '⤝', + rarrfs: '⤞', + Map: '⤅', + larrsim: '⥳', + rarrsim: '⥴', + harrcir: '⥈', + Uarrocir: '⥉', + lurdshar: '⥊', + ldrdhar: '⥧', + ldrushar: '⥋', + rdldhar: '⥩', + lrhard: '⥭', + rlhar: '⇌', + uharr: '↾', + uharl: '↿', + dharr: '⇂', + dharl: '⇃', + Uarr: '↟', + Darr: '↡', + zigrarr: '⇝', + nwArr: '⇖', + neArr: '⇗', + seArr: '⇘', + swArr: '⇙', + nharr: '↮', + nhArr: '⇎', + nlarr: '↚', + nlArr: '⇍', + nrarr: '↛', + nrArr: '⇏', + larrb: '⇤', + LeftArrowBar: '⇤', + rarrb: '⇥', + RightArrowBar: '⇥', +}; + +/** + * Geometric Shapes + * @type {Record} + */ +export const SHAPES = { + square: '□', + Square: '□', + squ: '□', + squf: '▪', + squarf: '▪', + blacksquar: '▪', + blacksquare: '▪', + FilledVerySmallSquare: '▪', + blk34: '▓', + blk12: '▒', + blk14: '░', + block: '█', + srect: '▭', + rect: '▭', + sdot: '⋅', + sdotb: '⊡', + dotsquare: '⊡', + triangle: '▵', + tri: '▵', + trine: '▵', + utri: '▵', + triangledown: '▿', + dtri: '▿', + tridown: '▿', + triangleleft: '◃', + ltri: '◃', + triangleright: '▹', + rtri: '▹', + blacktriangle: '▴', + utrif: '▴', + blacktriangledown: '▾', + dtrif: '▾', + blacktriangleleft: '◂', + ltrif: '◂', + blacktriangleright: '▸', + rtrif: '▸', + loz: '◊', + lozenge: '◊', + blacklozenge: '⧫', + lozf: '⧫', + bigcirc: '◯', + xcirc: '◯', + circ: 'ˆ', + Circle: '○', + cir: '○', + o: '○', + bullet: '•', + bull: '•', + hellip: '…', + mldr: '…', + nldr: '‥', + boxh: '─', + HorizontalLine: '─', + boxv: '│', + boxdr: '┌', + boxdl: '┐', + boxur: '└', + boxul: '┘', + boxvr: '├', + boxvl: '┤', + boxhd: '┬', + boxhu: '┴', + boxvh: '┼', + boxH: '═', + boxV: '║', + boxdR: '╒', + boxDr: '╓', + boxDR: '╔', + boxDl: '╕', + boxdL: '╖', + boxDL: '╗', + boxuR: '╘', + boxUr: '╙', + boxUR: '╚', + boxUl: '╜', + boxuL: '╛', + boxUL: '╝', + boxvR: '╞', + boxVr: '╟', + boxVR: '╠', + boxVl: '╢', + boxvL: '╡', + boxVL: '╣', + boxHd: '╤', + boxhD: '╥', + boxHD: '╦', + boxHu: '╧', + boxhU: '╨', + boxHU: '╩', + boxvH: '╪', + boxVh: '╫', + boxVH: '╬', +}; + +/** + * Punctuation & Diacritics + * @type {Record} + */ +export const PUNCTUATION = { + excl: '!', + iexcl: '¡', + brvbar: '¦', + sect: '§', + uml: '¨', + copy: '©', + ordf: 'ª', + laquo: '«', + not: '¬', + shy: '\u00ad', + reg: '®', + macr: '¯', + deg: '°', + plusmn: '±', + sup2: '²', + sup3: '³', + acute: '´', + micro: 'µ', + para: '¶', + middot: '·', + cedil: '¸', + sup1: '¹', + ordm: 'º', + raquo: '»', + frac14: '¼', + frac12: '½', + frac34: '¾', + iquest: '¿', + nbsp: '\u00a0', + comma: ',', + period: '.', + colon: ':', + semi: ';', + vert: '|', + Verbar: '‖', + verbar: '|', + dblac: '˝', + circ: 'ˆ', + caron: 'ˇ', + breve: '˘', + dot: '˙', + ring: '˚', + ogon: '˛', + tilde: '˜', + DiacriticalGrave: '`', + DiacriticalAcute: '´', + DiacriticalTilde: '˜', + DiacriticalDot: '˙', + DiacriticalDoubleAcute: '˝', + grave: '`', + acute: '´', +}; + +/** + * Currency Symbols + * @type {Record} + */ +export const CURRENCY = { + cent: '¢', + pound: '£', + curren: '¤', + yen: '¥', + euro: '€', + dollar: '$', + euro: '€', + fnof: 'ƒ', + inr: '₹', + af: '؋', + birr: 'ብር', + peso: '₱', + rub: '₽', + won: '₩', + yuan: '¥', + cedil: '¸', +}; + +/** + * Fractions + * @type {Record} + */ +export const FRACTIONS = { + frac12: '½', + half: '½', + frac13: '⅓', + frac14: '¼', + frac15: '⅕', + frac16: '⅙', + frac18: '⅛', + frac23: '⅔', + frac25: '⅖', + frac34: '¾', + frac35: '⅗', + frac38: '⅜', + frac45: '⅘', + frac56: '⅚', + frac58: '⅝', + frac78: '⅞', + frasl: '⁄', +}; + +/** + * Miscellaneous Symbols + * @type {Record} + */ +export const MISC_SYMBOLS = { + trade: '™', + TRADE: '™', + telrec: '⌕', + target: '⌖', + ulcorn: '⌜', + ulcorner: '⌜', + urcorn: '⌝', + urcorner: '⌝', + dlcorn: '⌞', + llcorner: '⌞', + drcorn: '⌟', + lrcorner: '⌟', + intercal: '⊺', + intcal: '⊺', + oplus: '⊕', + CirclePlus: '⊕', + ominus: '⊖', + CircleMinus: '⊖', + otimes: '⊗', + CircleTimes: '⊗', + osol: '⊘', + odot: '⊙', + CircleDot: '⊙', + oast: '⊛', + circledast: '⊛', + odash: '⊝', + circleddash: '⊝', + ocirc: '⊚', + circledcirc: '⊚', + boxplus: '⊞', + plusb: '⊞', + boxminus: '⊟', + minusb: '⊟', + boxtimes: '⊠', + timesb: '⊠', + boxdot: '⊡', + sdotb: '⊡', + veebar: '⊻', + vee: '∨', + barvee: '⊽', + and: '∧', + wedge: '∧', + Cap: '⋒', + Cup: '⋓', + Fork: '⋔', + pitchfork: '⋔', + epar: '⋕', + ltlarr: '⥶', + nvap: '≍⃒', + nvsim: '∼⃒', + nvge: '≥⃒', + nvle: '≤⃒', + nvlt: '<⃒', + nvgt: '>⃒', + nvltrie: '⊴⃒', + nvrtrie: '⊵⃒', + Vdash: '⊩', + dashv: '⊣', + vDash: '⊨', + Vdash: '⊩', + Vvdash: '⊪', + nvdash: '⊬', + nvDash: '⊭', + nVdash: '⊮', + nVDash: '⊯', +}; + +/** + * All entities combined (if you need everything) + * @type {Record} + */ +export const ALL_ENTITIES = { + ...BASIC_LATIN, + ...LATIN_ACCENTS, + ...LATIN_EXTENDED, + ...GREEK, + ...CYRILLIC, + ...MATH, + ...MATH_ADVANCED, + ...ARROWS, + ...SHAPES, + ...PUNCTUATION, + ...CURRENCY, + ...FRACTIONS, + ...MISC_SYMBOLS, +}; + +export const XML = { + amp: "&", + apos: "'", + gt: ">", + lt: "<", + quot: "\"" +} +export const COMMON_HTML = { + nbsp: '\u00a0', + copy: '\u00a9', + reg: '\u00ae', + trade: '\u2122', + mdash: '\u2014', + ndash: '\u2013', + hellip: '\u2026', + laquo: '\u00ab', + raquo: '\u00bb', + lsquo: '\u2018', + rsquo: '\u2019', + ldquo: '\u201c', + rdquo: '\u201d', + bull: '\u2022', + para: '\u00b6', + sect: '\u00a7', + deg: '\u00b0', + frac12: '\u00bd', + frac14: '\u00bc', + frac34: '\u00be', +} +// --------------------------------------------------------------------------- +// Note: NUMERIC_ENTITIES (&#NNN; / &#xHH;) are handled by the scanner directly +// via String.fromCodePoint() without any map lookup. +// --------------------------------------------------------------------------- \ No newline at end of file diff --git a/node_modules/@nodable/entities/src/entityTries.js b/node_modules/@nodable/entities/src/entityTries.js new file mode 100644 index 0000000..9565ebd --- /dev/null +++ b/node_modules/@nodable/entities/src/entityTries.js @@ -0,0 +1,49 @@ +// entityTries.js +// Builds integer-keyed tries so the decoder never allocates a string object +// during lookup — every key is a plain charCode number. +// +// trie1: Map +// trie2: Map> +// trie3: Map>> + +import { ALL_ENTITIES } from './entities.js'; + +// Reverse map: character sequence → "&name;" +const CHAR_TO_ENTITY = new Map(); +for (const [name, chars] of Object.entries(ALL_ENTITIES)) { + CHAR_TO_ENTITY.set(chars, `&${name};`); +} + +export const trie1 = new Map(); // code0 → entity string +export const trie2 = new Map(); // code0 → Map → entity string +export const trie3 = new Map(); // code0 → Map → Map → entity string + +for (const [chars, entity] of CHAR_TO_ENTITY) { + const len = chars.length; + + if (len === 1) { + const c0 = chars.charCodeAt(0); + // Keep shortest match only if no longer match already claimed this code + // (longer matches are inserted in the same pass so we just overwrite — + // trie1 is only consulted after trie2/trie3 both miss, so no conflict) + trie1.set(c0, entity); + + } else if (len === 2) { + const c0 = chars.charCodeAt(0); + const c1 = chars.charCodeAt(1); + let inner = trie2.get(c0); + if (inner === undefined) { inner = new Map(); trie2.set(c0, inner); } + inner.set(c1, entity); + + } else if (len === 3) { + const c0 = chars.charCodeAt(0); + const c1 = chars.charCodeAt(1); + const c2 = chars.charCodeAt(2); + let mid = trie3.get(c0); + if (mid === undefined) { mid = new Map(); trie3.set(c0, mid); } + let inner = mid.get(c1); + if (inner === undefined) { inner = new Map(); mid.set(c1, inner); } + inner.set(c2, entity); + } + // HTML5 has no named entity whose character sequence is longer than 3 chars +} \ No newline at end of file diff --git a/node_modules/@nodable/entities/src/index.d.ts b/node_modules/@nodable/entities/src/index.d.ts new file mode 100644 index 0000000..5528d44 --- /dev/null +++ b/node_modules/@nodable/entities/src/index.d.ts @@ -0,0 +1,264 @@ +// --------------------------------------------------------------------------- +// @nodable/entities — TypeScript declarations +// --------------------------------------------------------------------------- + +/** A function-based entity replacement value (used for numeric refs). */ +export type EntityValFn = (match: string, captured: string, ...rest: unknown[]) => string; + +// --------------------------------------------------------------------------- +// Encoder options +// --------------------------------------------------------------------------- + +export interface EntityEncoderOptions { + /** + * Whether to encode XML unsafe characters: `&`, `<`, `>`, `"`, `'`. + * @default true + */ + encodeXmlSafe?: boolean; + + /** + * Whether to encode non‑ASCII characters (e.g. `é` → `é`) using the + * built‑in named entity trie. + * @default true + */ + encodeAllNamed?: boolean; + + /** + * Maximum number of replacements performed **cumulatively** across all + * `encode()` calls. `0` means unlimited. + * + * Use `reset()` to reset the internal counter. + * @default 0 + */ + maxReplacements?: number; +} + +// --------------------------------------------------------------------------- +// EntityEncoder class +// --------------------------------------------------------------------------- + +/** + * High‑performance encoder that replaces characters with XML/HTML entities. + * + * - Escapes XML unsafe characters (`&`, `<`, `>`, `"`, `'`) when `encodeXmlSafe` is true. + * - Replaces non‑ASCII characters (e.g. `é`, `©`) with named entities using + * a compact trie‑based lookup when `encodeAllNamed` is true. + * - Supports a cumulative replacement limit (`maxReplacements`) that persists + * across multiple `encode()` calls until `reset()` is called. + * + * @example + * const encoder = new EntityEncoder({ encodeXmlSafe: true, encodeAllNamed: true }); + * encoder.encode(''); // "<foo>" + * encoder.encode('© 2025'); // "© 2025" + * + * // With limit + * const limited = new EntityEncoder({ maxReplacements: 2 }); + * limited.encode('<>&'); // "<>&" (third replacement omitted) + * limited.reset(); // reset counter + */ +export class EntityEncoder { + constructor(options?: EntityEncoderOptions); + + /** + * Encode a string by replacing XML‑unsafe characters and (optionally) + * non‑ASCII characters with named entities. + * + * If `maxReplacements` is set and the cumulative limit has been reached, + * the input string is returned unchanged. + * + * @returns Encoded string (may be identical to input if no replacements needed + * or the limit has been exhausted). + */ + encode(str: string): string; + + /** + * Reset the internal replacement counter. + * Does **not** change `encodeXmlSafe`, `encodeAllNamed`, or `maxReplacements`. + */ + reset(): void; +} + +// --------------------------------------------------------------------------- +// Constructor options for EntityDecoder (existing) +// --------------------------------------------------------------------------- + +/** + * Controls which entity categories count toward the expansion limits. + * + * - `'external'` — only untrusted / injected entities (default) + * - `'base'` — only built‑in XML entities + user‑supplied `namedEntities` + * - `'all'` — all entities regardless of tier + * - `string[]` — explicit combination, e.g. `['external', 'base']` + */ +export type ApplyLimitsTo = 'external' | 'base' | 'all' | Array<'external' | 'base'>; + +export interface EntityDecoderLimitOptions { + /** + * Maximum number of entity references expanded **per document**. + * `0` means unlimited. + * @default 0 + */ + maxTotalExpansions?: number; + + /** + * Maximum number of characters **added** by entity expansion per document. + * `0` means unlimited. + * @default 0 + */ + maxExpandedLength?: number; + + /** + * Which entity tiers count toward the expansion limits. + * + * - `'external'` (default) – only input/runtime + persistent external entities + * - `'base'` – only built‑in XML + `namedEntities` + * - `'all'` – every entity regardless of tier + * - `string[]` – explicit combination, e.g. `['external', 'base']` + * + * @default 'external' + */ + applyLimitsTo?: ApplyLimitsTo; +} + +export interface EntityDecoderNCROptions { + /** + * XML version used for NCR classification. + * @default 1.0 + */ + xmlVersion?: 1.0 | 1.1; + + /** + * Base action for all numeric references. + * @default 'allow' + */ + onNCR?: 'allow' | 'leave' | 'remove' | 'throw'; + + /** + * Action for null NCR (U+0000). + * @default 'remove' + */ + nullNCR?: 'remove' | 'throw'; +} + +export interface EntityDecoderOptions { + /** + * Extra named entities merged into the **base map** (trusted, counts as `'base'` tier). + * These are combined with the built‑in XML entities (`lt`, `gt`, `quot`, `apos`). + * Values containing `&` are silently skipped to prevent recursive expansion. + * + * @default null + */ + namedEntities?: Record | null; + + + /** + * Hook called once on the fully decoded string (after all replacements). + * + * - Receives `(resolved, original)` and **must return a string**. + * - To reject expansion, return `original`. + * - To sanitize, return a cleaned version of `resolved`. + * + * @example + * postCheck: (resolved, original) => + * /<[a-z]/i.test(resolved) ? original : resolved + */ + postCheck?: ((resolved: string, original: string) => string) | null; + + /** + * Whether numeric character references (`&#NNN;`, `&#xHH;`) are allowed. + * @default true + */ + numericAllowed?: boolean; + + /** + * Array of entity names or numeric references to leave unexpanded. + * @default [] + */ + leave?: string[]; + + /** + * Array of entity names or numeric references to remove. + * @default [] + */ + remove?: string[]; + + /** + * Security limits for entity expansion. + */ + limit?: EntityDecoderLimitOptions; + + /** + * Numeric Character Reference (NCR) policy. + */ + ncr?: EntityDecoderNCROptions; +} + +// --------------------------------------------------------------------------- +// EntityDecoder class (default export) +// --------------------------------------------------------------------------- + +/** + * Single‑pass, zero‑regex entity decoder for XML/HTML content. + * + * ## Entity lookup priority (highest → lowest) + * 1. **input / runtime** – injected via `addInputEntities()` (DOCTYPE per document) + * 2. **persistent external** – set via `setExternalEntities()` / `addExternalEntity()` + * 3. **base map** – built‑in XML entities + user‑supplied `namedEntities` + * + * Numeric references (`&#NNN;`, `&#xHH;`) are resolved directly and count as the `'base'` tier. + * + * @example + * const decoder = new EntityDecoder({ + * namedEntities: COMMON_HTML, + * maxTotalExpansions: 100 + * }); + * decoder.setExternalEntities({ brand: 'Acme' }); + * + * decoder.addInputEntities({ version: '1.0' }); + * decoder.decode('&brand; v&version; <'); // 'Acme v1.0 <' + * + * decoder.reset(); // clears input entities + counters, keeps external entities + */ +export default class EntityDecoder { + constructor(options?: EntityDecoderOptions); + + setExternalEntities( + map: Record + ): void; + + addExternalEntity(key: string, value: string): void; + + addInputEntities( + map: Record< + string, + | string + | { regx: RegExp; val: string | EntityValFn } + | { regex: RegExp; val: string | EntityValFn } + > + ): void; + + reset(): this; + + decode(str: string): string; +} + +// --------------------------------------------------------------------------- +// Named entity group exports (for use with `namedEntities` option) +// --------------------------------------------------------------------------- + +export const COMMON_HTML: Record; +export const ALL_ENTITIES: Record; +export const XML: Record; +export const BASIC_LATIN: Record; +export const LATIN_ACCENTS: Record; +export const LATIN_EXTENDED: Record; +export const GREEK: Record; +export const CYRILLIC: Record; +export const MATH: Record; +export const MATH_ADVANCED: Record; +export const ARROWS: Record; +export const SHAPES: Record; +export const PUNCTUATION: Record; +export const CURRENCY: Record; +export const FRACTIONS: Record; +export const MISC_SYMBOLS: Record; \ No newline at end of file diff --git a/node_modules/@nodable/entities/src/index.js b/node_modules/@nodable/entities/src/index.js new file mode 100644 index 0000000..2db6c14 --- /dev/null +++ b/node_modules/@nodable/entities/src/index.js @@ -0,0 +1,29 @@ +/** + * @nodable/entities + * + * Standalone, zero-dependency XML/HTML entity replacement. + * + + */ + +export { default as EntityDecoder } from './EntityDecoder.js'; +export { + COMMON_HTML, + XML, + ALL_ENTITIES, + ARROWS, + BASIC_LATIN, + CURRENCY, + MATH, + MATH_ADVANCED, + CYRILLIC, + FRACTIONS, + GREEK, + LATIN_ACCENTS, + LATIN_EXTENDED, + MISC_SYMBOLS, + PUNCTUATION, + SHAPES, +} from './entities.js'; + +export { default as EntityEncoder } from './EntityEncoder.js'; \ No newline at end of file diff --git a/node_modules/@tsconfig/node10/LICENSE b/node_modules/@tsconfig/node10/LICENSE new file mode 100644 index 0000000..48ea661 --- /dev/null +++ b/node_modules/@tsconfig/node10/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/node_modules/@tsconfig/node10/README.md b/node_modules/@tsconfig/node10/README.md new file mode 100644 index 0000000..1d7df8a --- /dev/null +++ b/node_modules/@tsconfig/node10/README.md @@ -0,0 +1,38 @@ +### A base TSConfig for working with Node 10. + +Add the package to your `"devDependencies"`: + +```sh +npm install --save-dev @tsconfig/node10 +yarn add --dev @tsconfig/node10 +``` + +Add to your `tsconfig.json`: + +```json +"extends": "@tsconfig/node10/tsconfig.json" +``` + +--- + +The `tsconfig.json`: + +```jsonc +{ + "$schema": "https://www.schemastore.org/tsconfig", + + "compilerOptions": { + "lib": ["es2018"], + "module": "commonjs", + "target": "es2018", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "moduleResolution": "node" + } +} + +``` + +You can find the [code here](https://github.com/tsconfig/bases/blob/master/bases/node10.json). diff --git a/node_modules/@tsconfig/node10/package.json b/node_modules/@tsconfig/node10/package.json new file mode 100644 index 0000000..7a7729e --- /dev/null +++ b/node_modules/@tsconfig/node10/package.json @@ -0,0 +1,15 @@ +{ + "name": "@tsconfig/node10", + "repository": { + "type": "git", + "url": "https://github.com/tsconfig/bases.git", + "directory": "bases" + }, + "license": "MIT", + "description": "A base TSConfig for working with Node 10.", + "keywords": [ + "tsconfig", + "node10" + ], + "version": "1.0.12" +} \ No newline at end of file diff --git a/node_modules/@tsconfig/node10/tsconfig.json b/node_modules/@tsconfig/node10/tsconfig.json new file mode 100644 index 0000000..ec3fba3 --- /dev/null +++ b/node_modules/@tsconfig/node10/tsconfig.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://www.schemastore.org/tsconfig", + + "compilerOptions": { + "lib": ["es2018"], + "module": "commonjs", + "target": "es2018", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "moduleResolution": "node" + } +} diff --git a/node_modules/@tsconfig/node12/LICENSE b/node_modules/@tsconfig/node12/LICENSE new file mode 100644 index 0000000..48ea661 --- /dev/null +++ b/node_modules/@tsconfig/node12/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/node_modules/@tsconfig/node12/README.md b/node_modules/@tsconfig/node12/README.md new file mode 100644 index 0000000..6352ccd --- /dev/null +++ b/node_modules/@tsconfig/node12/README.md @@ -0,0 +1,40 @@ +### A base TSConfig for working with Node 12. + +Add the package to your `"devDependencies"`: + +```sh +npm install --save-dev @tsconfig/node12 +yarn add --dev @tsconfig/node12 +``` + +Add to your `tsconfig.json`: + +```json +"extends": "@tsconfig/node12/tsconfig.json" +``` + +--- + +The `tsconfig.json`: + +```jsonc +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Node 12", + + "compilerOptions": { + "lib": ["es2019", "es2020.promise", "es2020.bigint", "es2020.string"], + "module": "commonjs", + "target": "es2019", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node" + } +} + +``` + +You can find the [code here](https://github.com/tsconfig/bases/blob/master/bases/node12.json). diff --git a/node_modules/@tsconfig/node12/package.json b/node_modules/@tsconfig/node12/package.json new file mode 100644 index 0000000..56aad61 --- /dev/null +++ b/node_modules/@tsconfig/node12/package.json @@ -0,0 +1 @@ +{"name":"@tsconfig/node12","repository":{"type":"git","url":"https://github.com/tsconfig/bases.git","directory":"bases"},"license":"MIT","description":"A base TSConfig for working with Node 12.","keywords":["tsconfig","node12"],"version":"1.0.11"} \ No newline at end of file diff --git a/node_modules/@tsconfig/node12/tsconfig.json b/node_modules/@tsconfig/node12/tsconfig.json new file mode 100644 index 0000000..eeaf944 --- /dev/null +++ b/node_modules/@tsconfig/node12/tsconfig.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Node 12", + + "compilerOptions": { + "lib": ["es2019", "es2020.promise", "es2020.bigint", "es2020.string"], + "module": "commonjs", + "target": "es2019", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node" + } +} diff --git a/node_modules/@tsconfig/node14/LICENSE b/node_modules/@tsconfig/node14/LICENSE new file mode 100644 index 0000000..48ea661 --- /dev/null +++ b/node_modules/@tsconfig/node14/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/node_modules/@tsconfig/node14/README.md b/node_modules/@tsconfig/node14/README.md new file mode 100644 index 0000000..dad7f02 --- /dev/null +++ b/node_modules/@tsconfig/node14/README.md @@ -0,0 +1,40 @@ +### A base TSConfig for working with Node 14. + +Add the package to your `"devDependencies"`: + +```sh +npm install --save-dev @tsconfig/node14 +yarn add --dev @tsconfig/node14 +``` + +Add to your `tsconfig.json`: + +```json +"extends": "@tsconfig/node14/tsconfig.json" +``` + +--- + +The `tsconfig.json`: + +```jsonc +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Node 14", + + "compilerOptions": { + "lib": ["es2020"], + "module": "commonjs", + "target": "es2020", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node" + } +} + +``` + +You can find the [code here](https://github.com/tsconfig/bases/blob/master/bases/node14.json). diff --git a/node_modules/@tsconfig/node14/package.json b/node_modules/@tsconfig/node14/package.json new file mode 100644 index 0000000..742f97b --- /dev/null +++ b/node_modules/@tsconfig/node14/package.json @@ -0,0 +1 @@ +{"name":"@tsconfig/node14","repository":{"type":"git","url":"https://github.com/tsconfig/bases.git","directory":"bases"},"license":"MIT","description":"A base TSConfig for working with Node 14.","keywords":["tsconfig","node14"],"version":"1.0.3"} \ No newline at end of file diff --git a/node_modules/@tsconfig/node14/tsconfig.json b/node_modules/@tsconfig/node14/tsconfig.json new file mode 100644 index 0000000..d1d7551 --- /dev/null +++ b/node_modules/@tsconfig/node14/tsconfig.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Node 14", + + "compilerOptions": { + "lib": ["es2020"], + "module": "commonjs", + "target": "es2020", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node" + } +} diff --git a/node_modules/@tsconfig/node16/LICENSE b/node_modules/@tsconfig/node16/LICENSE new file mode 100644 index 0000000..48ea661 --- /dev/null +++ b/node_modules/@tsconfig/node16/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/node_modules/@tsconfig/node16/README.md b/node_modules/@tsconfig/node16/README.md new file mode 100644 index 0000000..2946b2f --- /dev/null +++ b/node_modules/@tsconfig/node16/README.md @@ -0,0 +1,40 @@ +### A base TSConfig for working with Node 16. + +Add the package to your `"devDependencies"`: + +```sh +npm install --save-dev @tsconfig/node16 +yarn add --dev @tsconfig/node16 +``` + +Add to your `tsconfig.json`: + +```json +"extends": "@tsconfig/node16/tsconfig.json" +``` + +--- + +The `tsconfig.json`: + +```jsonc +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Node 16", + + "compilerOptions": { + "lib": ["es2021"], + "module": "Node16", + "target": "es2021", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node" + } +} + +``` + +You can find the [code here](https://github.com/tsconfig/bases/blob/master/bases/node16.json). diff --git a/node_modules/@tsconfig/node16/package.json b/node_modules/@tsconfig/node16/package.json new file mode 100644 index 0000000..8ccc97f --- /dev/null +++ b/node_modules/@tsconfig/node16/package.json @@ -0,0 +1,15 @@ +{ + "name": "@tsconfig/node16", + "repository": { + "type": "git", + "url": "https://github.com/tsconfig/bases.git", + "directory": "bases" + }, + "license": "MIT", + "description": "A base TSConfig for working with Node 16.", + "keywords": [ + "tsconfig", + "node16" + ], + "version": "1.0.4" +} \ No newline at end of file diff --git a/node_modules/@tsconfig/node16/tsconfig.json b/node_modules/@tsconfig/node16/tsconfig.json new file mode 100644 index 0000000..2671912 --- /dev/null +++ b/node_modules/@tsconfig/node16/tsconfig.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Node 16", + + "compilerOptions": { + "lib": ["es2021"], + "module": "Node16", + "target": "es2021", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node" + } +} diff --git a/node_modules/@types/minio/LICENSE b/node_modules/@types/minio/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/minio/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/minio/README.md b/node_modules/@types/minio/README.md new file mode 100644 index 0000000..4a3394f --- /dev/null +++ b/node_modules/@types/minio/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/minio` + +# Summary +This package contains type definitions for minio (https://github.com/minio/minio-js#readme). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/minio. + +### Additional Details + * Last updated: Mon, 22 May 2023 19:32:54 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + * Global values: none + +# Credits +These definitions were written by [Barin Britva](https://github.com/barinbritva), [Lubomir Kaplan](https://github.com/castorw), [Panagiotis Kapros](https://github.com/loremaps), [Ben Watkins](https://github.com/OutdatedVersion), [Seohyun Yoon](https://github.com/seohyun0120), and [Trim21](https://github.com/trim21). diff --git a/node_modules/@types/minio/index.d.ts b/node_modules/@types/minio/index.d.ts new file mode 100644 index 0000000..07bf9cc --- /dev/null +++ b/node_modules/@types/minio/index.d.ts @@ -0,0 +1,772 @@ +// Type definitions for minio 7.1 +// Project: https://github.com/minio/minio-js#readme +// Definitions by: Barin Britva +// Lubomir Kaplan +// Panagiotis Kapros +// Ben Watkins +// Seohyun Yoon +// Trim21 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +// Import from dependencies +import { Readable as ReadableStream } from 'stream'; +import { EventEmitter } from 'events'; +import { RequestOptions } from 'https'; + +// Exports only from typings +export type Region = + | 'us-east-1' + | 'us-west-1' + | 'us-west-2' + | 'eu-west-1' + | 'eu-central-1' + | 'ap-southeast-1' + | 'ap-northeast-1' + | 'ap-southeast-2' + | 'sa-east-1' + | 'cn-north-1' + | string; +export type NotificationEvent = + | 's3:ObjectCreated:*' + | 's3:ObjectCreated:Put' + | 's3:ObjectCreated:Post' + | 's3:ObjectCreated:Copy' + | 's3:ObjectCreated:CompleteMultipartUpload' + | 's3:ObjectRemoved:*' + | 's3:ObjectRemoved:Delete' + | 's3:ObjectRemoved:DeleteMarkerCreated' + | 's3:ReducedRedundancyLostObject' + | 's3:TestEvent' + | 's3:ObjectRestore:Post' + | 's3:ObjectRestore:Completed' + | 's3:Replication:OperationFailedReplication' + | 's3:Replication:OperationMissedThreshold' + | 's3:Replication:OperationReplicatedAfterThreshold' + | 's3:Replication:OperationNotTracked' + | string; +export type Mode = 'COMPLIANCE' | 'GOVERNANCE'; +export type LockUnit = 'Days' | 'Years'; +export type LegalHoldStatus = 'ON' | 'OFF'; +export type NoResultCallback = (error: Error | null) => void; +export type ResultCallback = (error: Error | null, result: T) => void; +export type VersioningConfig = Record; +export type TagList = Record; +export type EmptyObject = Record; +export type VersionIdentificator = Pick; +export type Lifecycle = LifecycleConfig | null | ''; +export type Lock = LockConfig | EmptyObject; +export type Encryption = EncryptionConfig | EmptyObject; +export type Retention = RetentionOptions | EmptyObject; +export type IsoDate = string; + +export interface ClientOptions { + endPoint: string; + accessKey: string; + secretKey: string; + useSSL?: boolean | undefined; + port?: number | undefined; + region?: Region | undefined; + transport?: any; + sessionToken?: string | undefined; + partSize?: number | undefined; + pathStyle?: boolean | undefined; +} + +export interface BucketItemFromList { + name: string; + creationDate: Date; +} + +export interface BucketItemCopy { + etag: string; + lastModified: Date; +} + +export interface BucketItem { + name: string; + prefix: string; + size: number; + etag: string; + lastModified: Date; +} + +export interface BucketItemWithMetadata extends BucketItem { + metadata: ItemBucketMetadata | ItemBucketMetadataList; +} + +export interface BucketItemStat { + size: number; + etag: string; + lastModified: Date; + metaData: ItemBucketMetadata; +} + +export interface IncompleteUploadedBucketItem { + key: string; + uploadId: string; + size: number; +} + +export interface BucketStream extends ReadableStream { + on(event: 'data', listener: (item: T) => void): this; + on(event: 'end' | 'pause' | 'readable' | 'resume' | 'close', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; +} + +export interface PostPolicyResult { + postURL: string; + formData: { + [key: string]: any; + }; +} + +export interface MetadataItem { + Key: string; + Value: string; +} + +export interface ItemBucketMetadataList { + Items: MetadataItem[]; +} + +export interface ItemBucketMetadata { + [key: string]: any; +} + +export interface UploadedObjectInfo { + etag: string; + versionId: string | null; +} + +export interface Tag { + Key: string; + Value: string; +} + +export interface LifecycleConfig { + Rule: LifecycleRule[]; +} + +export interface LifecycleRule { + [key: string]: any; +} + +export interface LockConfig { + mode: Mode; + unit: LockUnit; + validity: number; +} + +export interface EncryptionConfig { + Rule: EncryptionRule[]; +} + +export interface EncryptionRule { + [key: string]: any; +} + +export interface ReplicationConfig { + role: string; + rules: []; +} + +export interface ReplicationConfig { + [key: string]: any; +} + +export interface RetentionOptions { + versionId: string; + mode?: Mode; + retainUntilDate?: IsoDate; + governanceBypass?: boolean; +} + +export interface LegalHoldOptions { + versionId: string; + status: LegalHoldStatus; +} + +export interface InputSerialization { + CompressionType?: 'NONE' | 'GZIP' | 'BZIP2'; + CSV?: { + AllowQuotedRecordDelimiter?: boolean; + Comments?: string; + FieldDelimiter?: string; + FileHeaderInfo?: 'NONE' | 'IGNORE' | 'USE'; + QuoteCharacter?: string; + QuoteEscapeCharacter?: string; + RecordDelimiter?: string; + }; + JSON?: { + Type: 'DOCUMENT' | 'LINES'; + }; + Parquet?: EmptyObject; +} + +export interface OutputSerialization { + CSV?: { + FieldDelimiter?: string; + QuoteCharacter?: string; + QuoteEscapeCharacter?: string; + QuoteFields?: string; + RecordDelimiter?: string; + }; + JSON?: { + RecordDelimiter?: string; + }; +} + +export interface SelectOptions { + expression: string; + expressionType?: string; + inputSerialization: InputSerialization; + outputSerialization: OutputSerialization; + requestProgress?: { Enabled: boolean }; + scanRange?: { Start: number; End: number }; +} + +export interface SourceObjectStats { + size: number; + metaData: string; + lastModicied: Date; + versionId: string; + etag: string; +} + +// No need to export this. But without it - linter error. +export class TargetConfig { + setId(id: any): void; + addEvent(newEvent: any): void; + addFilterSuffix(suffix: any): void; + addFilterPrefix(prefix: any): void; +} + +export interface MakeBucketOpt { + ObjectLocking: boolean; +} + +export interface RemoveOptions { + versionId?: string; + governanceBypass?: boolean; +} + +// Exports from library +export class Client { + constructor(options: ClientOptions); + + // Bucket operations + makeBucket(bucketName: string, region: Region, makeOpts: MakeBucketOpt, callback: NoResultCallback): void; + makeBucket(bucketName: string, region: Region, callback: NoResultCallback): void; + makeBucket(bucketName: string, callback: NoResultCallback): void; + makeBucket(bucketName: string, region?: Region, makeOpts?: MakeBucketOpt): Promise; + + listBuckets(callback: ResultCallback): void; + listBuckets(): Promise; + + bucketExists(bucketName: string, callback: ResultCallback): void; + bucketExists(bucketName: string): Promise; + + removeBucket(bucketName: string, callback: NoResultCallback): void; + removeBucket(bucketName: string): Promise; + + listObjects(bucketName: string, prefix?: string, recursive?: boolean): BucketStream; + + listObjectsV2( + bucketName: string, + prefix?: string, + recursive?: boolean, + startAfter?: string, + ): BucketStream; + + listIncompleteUploads( + bucketName: string, + prefix?: string, + recursive?: boolean, + ): BucketStream; + + getBucketVersioning(bucketName: string, callback: ResultCallback): void; + getBucketVersioning(bucketName: string): Promise; + + setBucketVersioning(bucketName: string, versioningConfig: any, callback: NoResultCallback): void; + setBucketVersioning(bucketName: string, versioningConfig: any): Promise; + + getBucketTagging(bucketName: string, callback: ResultCallback): void; + getBucketTagging(bucketName: string): Promise; + + setBucketTagging(bucketName: string, tags: TagList, callback: NoResultCallback): void; + setBucketTagging(bucketName: string, tags: TagList): Promise; + + removeBucketTagging(bucketName: string, callback: NoResultCallback): void; + removeBucketTagging(bucketName: string): Promise; + + setBucketLifecycle(bucketName: string, lifecycleConfig: Lifecycle, callback: NoResultCallback): void; + setBucketLifecycle(bucketName: string, lifecycleConfig: Lifecycle): Promise; + + getBucketLifecycle(bucketName: string, callback: ResultCallback): void; + getBucketLifecycle(bucketName: string): Promise; + + removeBucketLifecycle(bucketName: string, callback: NoResultCallback): void; + removeBucketLifecycle(bucketName: string): Promise; + + setObjectLockConfig(bucketName: string, callback: NoResultCallback): void; + setObjectLockConfig(bucketName: string, lockConfig: Lock, callback: NoResultCallback): void; + setObjectLockConfig(bucketName: string, lockConfig?: Lock): Promise; + + getObjectLockConfig(bucketName: string, callback: ResultCallback): void; + getObjectLockConfig(bucketName: string): Promise; + + getBucketEncryption(bucketName: string, callback: ResultCallback): void; + getBucketEncryption(bucketName: string): Promise; + + setBucketEncryption(bucketName: string, encryptionConfig: Encryption, callback: NoResultCallback): void; + setBucketEncryption(bucketName: string, encryptionConfig: Encryption): Promise; + + removeBucketEncryption(bucketName: string, callback: NoResultCallback): void; + removeBucketEncryption(bucketName: string): Promise; + + setBucketReplication(bucketName: string, replicationConfig: ReplicationConfig, callback: NoResultCallback): void; + setBucketReplication(bucketName: string, replicationConfig: ReplicationConfig): Promise; + + getBucketReplication(bucketName: string, callback: ResultCallback): void; + getBucketReplication(bucketName: string): Promise; + + removeBucketReplication(bucketName: string, callback: NoResultCallback): void; + removeBucketReplication(bucketName: string): Promise; + + // Object operations + getObject(bucketName: string, objectName: string, callback: ResultCallback): void; + getObject(bucketName: string, objectName: string): Promise; + + getPartialObject( + bucketName: string, + objectName: string, + offset: number, + callback: ResultCallback, + ): void; + getPartialObject( + bucketName: string, + objectName: string, + offset: number, + length: number, + callback: ResultCallback, + ): void; + getPartialObject(bucketName: string, objectName: string, offset: number, length?: number): Promise; + + fGetObject(bucketName: string, objectName: string, filePath: string, callback: NoResultCallback): void; + fGetObject(bucketName: string, objectName: string, filePath: string): Promise; + + putObject( + bucketName: string, + objectName: string, + stream: ReadableStream | Buffer | string, + callback: ResultCallback, + ): void; + putObject( + bucketName: string, + objectName: string, + stream: ReadableStream | Buffer | string, + size: number, + callback: ResultCallback, + ): void; + putObject( + bucketName: string, + objectName: string, + stream: ReadableStream | Buffer | string, + size: number, + metaData: ItemBucketMetadata, + callback: ResultCallback, + ): void; + putObject( + bucketName: string, + objectName: string, + stream: ReadableStream | Buffer | string, + size?: number, + metaData?: ItemBucketMetadata, + ): Promise; + putObject( + bucketName: string, + objectName: string, + stream: ReadableStream | Buffer | string, + metaData?: ItemBucketMetadata, + ): Promise; + + fPutObject( + bucketName: string, + objectName: string, + filePath: string, + metaData: ItemBucketMetadata, + callback: ResultCallback, + ): void; + fPutObject( + bucketName: string, + objectName: string, + filePath: string, + metaData?: ItemBucketMetadata, + ): Promise; + + copyObject( + bucketName: string, + objectName: string, + sourceObject: string, + conditions: CopyConditions, + callback: ResultCallback, + ): void; + copyObject( + bucketName: string, + objectName: string, + sourceObject: string, + conditions: CopyConditions, + ): Promise; + + statObject(bucketName: string, objectName: string, callback: ResultCallback): void; + statObject(bucketName: string, objectName: string): Promise; + + removeObject(bucketName: string, objectName: string, removeOpts: RemoveOptions, callback: NoResultCallback): void; + removeObject(bucketName: string, objectName: string, callback: NoResultCallback): void; + removeObject(bucketName: string, objectName: string, removeOpts?: RemoveOptions): Promise; + + removeObjects(bucketName: string, objectsList: string[], callback: NoResultCallback): void; + removeObjects(bucketName: string, objectsList: string[]): Promise; + + removeIncompleteUpload(bucketName: string, objectName: string, callback: NoResultCallback): void; + removeIncompleteUpload(bucketName: string, objectName: string): Promise; + + putObjectRetention(bucketName: string, objectName: string, callback: NoResultCallback): void; + putObjectRetention( + bucketName: string, + objectName: string, + retentionOptions: Retention, + callback: NoResultCallback, + ): void; + putObjectRetention(bucketName: string, objectName: string, retentionOptions?: Retention): Promise; + + getObjectRetention( + bucketName: string, + objectName: string, + options: VersionIdentificator, + callback: ResultCallback, + ): void; + getObjectRetention(bucketName: string, objectName: string, options: VersionIdentificator): Promise; + + // It seems, putObjectTagging is deprecated in favor or setObjectTagging - there is no such a method in the library source code + /** + * @deprecated Use setObjectTagging instead. + */ + putObjectTagging(bucketName: string, objectName: string, tags: TagList, callback: NoResultCallback): void; + /** + * @deprecated Use setObjectTagging instead. + */ + putObjectTagging( + bucketName: string, + objectName: string, + tags: TagList, + putOptions: VersionIdentificator, + callback: NoResultCallback, + ): void; + /** + * @deprecated Use setObjectTagging instead. + */ + putObjectTagging( + bucketName: string, + objectName: string, + tags: TagList, + putOptions?: VersionIdentificator, + ): Promise; + + setObjectTagging(bucketName: string, objectName: string, tags: TagList, callback: NoResultCallback): void; + setObjectTagging( + bucketName: string, + objectName: string, + tags: TagList, + putOptions: VersionIdentificator, + callback: NoResultCallback, + ): void; + setObjectTagging( + bucketName: string, + objectName: string, + tags: TagList, + putOptions?: VersionIdentificator, + ): Promise; + + removeObjectTagging(bucketName: string, objectName: string, callback: NoResultCallback): void; + removeObjectTagging( + bucketName: string, + objectName: string, + removeOptions: VersionIdentificator, + callback: NoResultCallback, + ): void; + removeObjectTagging(bucketName: string, objectName: string, removeOptions?: VersionIdentificator): Promise; + + getObjectTagging(bucketName: string, objectName: string, callback: ResultCallback): void; + getObjectTagging( + bucketName: string, + objectName: string, + getOptions: VersionIdentificator, + callback: ResultCallback, + ): void; + getObjectTagging(bucketName: string, objectName: string, getOptions?: VersionIdentificator): Promise; + + getObjectLegalHold(bucketName: string, objectName: string, callback: ResultCallback): void; + getObjectLegalHold( + bucketName: string, + objectName: string, + getOptions: VersionIdentificator, + callback: ResultCallback, + ): void; + getObjectLegalHold( + bucketName: string, + objectName: string, + getOptions?: VersionIdentificator, + ): Promise; + + setObjectLegalHold(bucketName: string, objectName: string, callback: NoResultCallback): void; + setObjectLegalHold( + bucketName: string, + objectName: string, + setOptions: LegalHoldOptions, + callback: NoResultCallback, + ): void; + setObjectLegalHold(bucketName: string, objectName: string, setOptions?: LegalHoldOptions): Promise; + + composeObject( + destObjConfig: CopyDestinationOptions, + sourceObjList: CopySourceOptions[], + callback: ResultCallback, + ): void; + composeObject( + destObjConfig: CopyDestinationOptions, + sourceObjList: CopySourceOptions[], + ): Promise; + + selectObjectContent( + bucketName: string, + objectName: string, + selectOpts: SelectOptions, + callback: NoResultCallback, + ): void; + selectObjectContent(bucketName: string, objectName: string, selectOpts: SelectOptions): Promise; + + // Presigned operations + presignedUrl(httpMethod: string, bucketName: string, objectName: string, callback: ResultCallback): void; + presignedUrl( + httpMethod: string, + bucketName: string, + objectName: string, + expiry: number, + callback: ResultCallback, + ): void; + presignedUrl( + httpMethod: string, + bucketName: string, + objectName: string, + expiry: number, + reqParams: { [key: string]: any }, + callback: ResultCallback, + ): void; + presignedUrl( + httpMethod: string, + bucketName: string, + objectName: string, + expiry: number, + reqParams: { [key: string]: any }, + requestDate: Date, + callback: ResultCallback, + ): void; + presignedUrl( + httpMethod: string, + bucketName: string, + objectName: string, + expiry?: number, + reqParams?: { [key: string]: any }, + requestDate?: Date, + ): Promise; + + presignedGetObject(bucketName: string, objectName: string, callback: ResultCallback): void; + presignedGetObject(bucketName: string, objectName: string, expiry: number, callback: ResultCallback): void; + presignedGetObject( + bucketName: string, + objectName: string, + expiry: number, + respHeaders: { [key: string]: any }, + callback: ResultCallback, + ): void; + presignedGetObject( + bucketName: string, + objectName: string, + expiry: number, + respHeaders: { [key: string]: any }, + requestDate: Date, + callback: ResultCallback, + ): void; + presignedGetObject( + bucketName: string, + objectName: string, + expiry?: number, + respHeaders?: { [key: string]: any }, + requestDate?: Date, + ): Promise; + + presignedPutObject(bucketName: string, objectName: string, callback: ResultCallback): void; + presignedPutObject(bucketName: string, objectName: string, expiry: number, callback: ResultCallback): void; + presignedPutObject(bucketName: string, objectName: string, expiry?: number): Promise; + + presignedPostPolicy(policy: PostPolicy, callback: ResultCallback): void; + presignedPostPolicy(policy: PostPolicy): Promise; + + // Bucket Policy & Notification operations + getBucketNotification(bucketName: string, callback: ResultCallback): void; + getBucketNotification(bucketName: string): Promise; + + setBucketNotification( + bucketName: string, + bucketNotificationConfig: NotificationConfig, + callback: NoResultCallback, + ): void; + setBucketNotification(bucketName: string, bucketNotificationConfig: NotificationConfig): Promise; + + removeAllBucketNotification(bucketName: string, callback: NoResultCallback): void; + removeAllBucketNotification(bucketName: string): Promise; + + getBucketPolicy(bucketName: string, callback: ResultCallback): void; + getBucketPolicy(bucketName: string): Promise; + + setBucketPolicy(bucketName: string, bucketPolicy: string, callback: NoResultCallback): void; + setBucketPolicy(bucketName: string, bucketPolicy: string): Promise; + + listenBucketNotification( + bucketName: string, + prefix: string, + suffix: string, + events: NotificationEvent[], + ): NotificationPoller; + + // Custom Settings + setS3TransferAccelerate(endpoint: string): void; + + // Other + newPostPolicy(): PostPolicy; + setRequestOptions(options: RequestOptions): void; + + // Minio extensions that aren't necessary present for Amazon S3 compatible storage servers + extensions: { + listObjectsV2WithMetadata( + bucketName: string, + prefix?: string, + recursive?: boolean, + startAfter?: string, + ): BucketStream; + }; +} + +export namespace Policy { + const NONE: 'none'; + const READONLY: 'readonly'; + const WRITEONLY: 'writeonly'; + const READWRITE: 'readwrite'; +} + +export class CopyConditions { + setModified(date: Date): void; + setUnmodified(date: Date): void; + setMatchETag(etag: string): void; + setMatchETagExcept(etag: string): void; +} + +export class PostPolicy { + setExpires(date: Date): void; + setKey(objectName: string): void; + setKeyStartsWith(prefix: string): void; + setBucket(bucketName: string): void; + setContentType(type: string): void; + setContentTypeStartsWith(prefix: string): void; + setContentLengthRange(min: number, max: number): void; + setContentDisposition(disposition: string): void; + setUserMetaData(metadata: Record): void; +} + +export class NotificationPoller extends EventEmitter { + stop(): void; + start(): void; + // must to be public? + checkForChanges(): void; +} + +export class NotificationConfig { + add(target: TopicConfig | QueueConfig | CloudFunctionConfig): void; +} + +export class TopicConfig extends TargetConfig { + constructor(arn: string); +} + +export class QueueConfig extends TargetConfig { + constructor(arn: string); +} + +export class CloudFunctionConfig extends TargetConfig { + constructor(arn: string); +} + +export class CopySourceOptions { + constructor(options: { + Bucket: string; + Object: string; + VersionID?: string; + MatchETag?: string; + NoMatchETag?: string; + MatchModifiedSince?: string; + MatchUnmodifiedSince?: string; + MatchRange?: boolean; + Start?: number; + End?: number; + Encryption?: { + type: string; + SSEAlgorithm?: string; + KMSMasterKeyID?: string; + }; + }); + + getHeaders(): Record; + validate(): boolean; +} + +export class CopyDestinationOptions { + constructor(options: { + Bucket: string; + Object: string; + Encryption?: { + type: string; + SSEAlgorithm?: string; + KMSMasterKeyID?: string; + }; + UserMetadata?: Record; + UserTags?: Record | string; + LegalHold?: LegalHoldStatus; + RetainUntilDate?: string; + Mode?: Mode; + }); + + getHeaders(): Record; + validate(): boolean; +} + +export function buildARN( + partition: string, + service: string, + region: string, + accountId: string, + resource: string, +): string; + +export const ObjectCreatedAll: NotificationEvent; // s3:ObjectCreated:*' +export const ObjectCreatedPut: NotificationEvent; // s3:ObjectCreated:Put +export const ObjectCreatedPost: NotificationEvent; // s3:ObjectCreated:Post +export const ObjectCreatedCopy: NotificationEvent; // s3:ObjectCreated:Copy +export const ObjectCreatedCompleteMultipartUpload: NotificationEvent; // s3:ObjectCreated:CompleteMultipartUpload +export const ObjectRemovedAll: NotificationEvent; // s3:ObjectRemoved:* +export const ObjectRemovedDelete: NotificationEvent; // s3:ObjectRemoved:Delete +export const ObjectRemovedDeleteMarkerCreated: NotificationEvent; // s3:ObjectRemoved:DeleteMarkerCreated +export const ObjectReducedRedundancyLostObject: NotificationEvent; // s3:ReducedRedundancyLostObject diff --git a/node_modules/@types/minio/package.json b/node_modules/@types/minio/package.json new file mode 100644 index 0000000..5a62af1 --- /dev/null +++ b/node_modules/@types/minio/package.json @@ -0,0 +1,52 @@ +{ + "name": "@types/minio", + "version": "7.1.0", + "description": "TypeScript definitions for minio", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/minio", + "license": "MIT", + "contributors": [ + { + "name": "Barin Britva", + "url": "https://github.com/barinbritva", + "githubUsername": "barinbritva" + }, + { + "name": "Lubomir Kaplan", + "url": "https://github.com/castorw", + "githubUsername": "castorw" + }, + { + "name": "Panagiotis Kapros", + "url": "https://github.com/loremaps", + "githubUsername": "loremaps" + }, + { + "name": "Ben Watkins", + "url": "https://github.com/OutdatedVersion", + "githubUsername": "OutdatedVersion" + }, + { + "name": "Seohyun Yoon", + "url": "https://github.com/seohyun0120", + "githubUsername": "seohyun0120" + }, + { + "name": "Trim21", + "url": "https://github.com/trim21", + "githubUsername": "trim21" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/minio" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*" + }, + "typesPublisherContentHash": "946994b096be4d21329eab0e7d791ac920a0173d9d3e0723ba6f55c560a2fe41", + "typeScriptVersion": "4.3" +} \ No newline at end of file diff --git a/node_modules/@types/node/LICENSE b/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/node/README.md b/node_modules/@types/node/README.md new file mode 100644 index 0000000..83c5c7b --- /dev/null +++ b/node_modules/@types/node/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for node (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Fri, 10 Apr 2026 03:39:58 GMT + * Dependencies: [undici-types](https://npmjs.com/package/undici-types) + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), [René](https://github.com/Renegade334), and [Yagiz Nizipli](https://github.com/anonrig). diff --git a/node_modules/@types/node/assert.d.ts b/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000..c4cc77e --- /dev/null +++ b/node_modules/@types/node/assert.d.ts @@ -0,0 +1,950 @@ +declare module "node:assert" { + import strict = require("node:assert/strict"); + /** + * An alias of {@link assert.ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + const kOptions: unique symbol; + namespace assert { + type AssertMethodNames = + | "deepEqual" + | "deepStrictEqual" + | "doesNotMatch" + | "doesNotReject" + | "doesNotThrow" + | "equal" + | "fail" + | "ifError" + | "match" + | "notDeepEqual" + | "notDeepStrictEqual" + | "notEqual" + | "notStrictEqual" + | "ok" + | "partialDeepStrictEqual" + | "rejects" + | "strictEqual" + | "throws"; + interface AssertOptions { + /** + * If set to `'full'`, shows the full diff in assertion errors. + * @default 'simple' + */ + diff?: "simple" | "full" | undefined; + /** + * If set to `true`, non-strict methods behave like their + * corresponding strict methods. + * @default true + */ + strict?: boolean | undefined; + /** + * If set to `true`, skips prototype and constructor + * comparison in deep equality checks. + * @since v24.9.0 + * @default false + */ + skipPrototype?: boolean | undefined; + } + interface Assert extends Pick { + readonly [kOptions]: AssertOptions & { strict: false }; + } + interface AssertStrict extends Pick { + readonly [kOptions]: AssertOptions & { strict: true }; + } + /** + * The `Assert` class allows creating independent assertion instances with custom options. + * @since v24.6.0 + */ + var Assert: { + /** + * Creates a new assertion instance. The `diff` option controls the verbosity of diffs in assertion error messages. + * + * ```js + * const { Assert } = require('node:assert'); + * const assertInstance = new Assert({ diff: 'full' }); + * assertInstance.deepStrictEqual({ a: 1 }, { a: 2 }); + * // Shows a full diff in the error message. + * ``` + * + * **Important**: When destructuring assertion methods from an `Assert` instance, + * the methods lose their connection to the instance's configuration options (such + * as `diff`, `strict`, and `skipPrototype` settings). + * The destructured methods will fall back to default behavior instead. + * + * ```js + * const myAssert = new Assert({ diff: 'full' }); + * + * // This works as expected - uses 'full' diff + * myAssert.strictEqual({ a: 1 }, { b: { c: 1 } }); + * + * // This loses the 'full' diff setting - falls back to default 'simple' diff + * const { strictEqual } = myAssert; + * strictEqual({ a: 1 }, { b: { c: 1 } }); + * ``` + * + * The `skipPrototype` option affects all deep equality methods: + * + * ```js + * class Foo { + * constructor(a) { + * this.a = a; + * } + * } + * + * class Bar { + * constructor(a) { + * this.a = a; + * } + * } + * + * const foo = new Foo(1); + * const bar = new Bar(1); + * + * // Default behavior - fails due to different constructors + * const assert1 = new Assert(); + * assert1.deepStrictEqual(foo, bar); // AssertionError + * + * // Skip prototype comparison - passes if properties are equal + * const assert2 = new Assert({ skipPrototype: true }); + * assert2.deepStrictEqual(foo, bar); // OK + * ``` + * + * When destructured, methods lose access to the instance's `this` context and revert to default assertion behavior + * (diff: 'simple', non-strict mode). + * To maintain custom options when using destructured methods, avoid + * destructuring and call methods directly on the instance. + * @since v24.6.0 + */ + new( + options?: AssertOptions & { strict?: true | undefined }, + ): AssertStrict; + new( + options: AssertOptions, + ): Assert; + }; + interface AssertionErrorOptions { + /** + * If provided, the error message is set to this value. + */ + message?: string | undefined; + /** + * The `actual` property on the error instance. + */ + actual?: unknown; + /** + * The `expected` property on the error instance. + */ + expected?: unknown; + /** + * The `operator` property on the error instance. + */ + operator?: string | undefined; + /** + * If provided, the generated stack trace omits frames before this function. + */ + stackStartFn?: Function | undefined; + /** + * If set to `'full'`, shows the full diff in assertion errors. + * @default 'simple' + */ + diff?: "simple" | "full" | undefined; + } + /** + * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + constructor(options: AssertionErrorOptions); + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ + actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ + expected: unknown; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ + generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ + code: "ERR_ASSERTION"; + /** + * Set to the passed in operator value. + */ + operator: string; + } + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** + * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * // Using `assert()` works the same: + * assert(2 + 2 > 5);; + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(2 + 2 > 5) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error + * message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'node:assert'; + * + * const obj1 = { + * a: { + * b: 1, + * }, + * }; + * const obj2 = { + * a: { + * b: 2, + * }, + * }; + * const obj3 = { + * a: { + * b: 1, + * }, + * }; + * const obj4 = { __proto__: obj1 }; + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'node:assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text', + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text', + * }, + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * }, + * ); + * + * // Using regular expressions to validate error properties: + * assert.throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text', + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i, + * }, + * ); + * + * // Fails due to the different `message` and `name` properties: + * assert.throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err, + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error, + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/, + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error', + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'node:assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn` function. + * + * If an error is thrown and it is the same type as that specified by the `error` parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError, + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops', + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for `ifError()` itself. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v25.x/api/errors.html#err_invalid_return_value) + * error. In both cases the error handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and `name` properties. + * + * If specified, `message` will be the message provided by the `{@link AssertionError}` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error, + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to + * be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v25.x/api/errors.html#err_invalid_return_value) error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Tests for partial deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. "Partial" equality means + * that only properties that exist on the `expected` parameter are going to be + * compared. + * + * This method always passes the same test cases as `assert.deepStrictEqual()`, + * behaving as a super set of it. + * @since v22.13.0 + */ + function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + } + namespace assert { + export { strict }; + } + export = assert; +} +declare module "assert" { + import assert = require("node:assert"); + export = assert; +} diff --git a/node_modules/@types/node/assert/strict.d.ts b/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000..7a9dcf5 --- /dev/null +++ b/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,59 @@ +declare module "node:assert/strict" { + import { + Assert, + AssertionError, + AssertionErrorOptions, + AssertOptions, + AssertPredicate, + AssertStrict, + deepStrictEqual, + doesNotMatch, + doesNotReject, + doesNotThrow, + fail, + ifError, + match, + notDeepStrictEqual, + notStrictEqual, + ok, + partialDeepStrictEqual, + rejects, + strictEqual, + throws, + } from "node:assert"; + function strict(value: unknown, message?: string | Error): asserts value; + namespace strict { + export { + Assert, + AssertionError, + AssertionErrorOptions, + AssertOptions, + AssertPredicate, + AssertStrict, + deepStrictEqual, + deepStrictEqual as deepEqual, + doesNotMatch, + doesNotReject, + doesNotThrow, + fail, + ifError, + match, + notDeepStrictEqual, + notDeepStrictEqual as notDeepEqual, + notStrictEqual, + notStrictEqual as notEqual, + ok, + partialDeepStrictEqual, + rejects, + strict, + strictEqual, + strictEqual as equal, + throws, + }; + } + export = strict; +} +declare module "assert/strict" { + import strict = require("node:assert/strict"); + export = strict; +} diff --git a/node_modules/@types/node/async_hooks.d.ts b/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000..bb82b8a --- /dev/null +++ b/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,603 @@ +declare module "node:async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * const path = '.'; + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on [promise execution tracking](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#promise-execution-tracking). + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'node:http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook, + * } from 'node:async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * }, + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on [promise execution tracking](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#promise-execution-tracking). + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * The [`init` callback](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#initasyncid-type-triggerasyncid-resource). + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * The [`before` callback](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#beforeasyncid). + */ + before?(asyncId: number): void; + /** + * The [`after` callback](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#afterasyncid). + */ + after?(asyncId: number): void; + /** + * The [`promiseResolve` callback](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#promiseresolveasyncid). + */ + promiseResolve?(asyncId: number): void; + /** + * The [`destroy` callback](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#destroyasyncid). + */ + destroy?(asyncId: number): void; + /** + * Whether the hook should track `Promise`s. Cannot be `false` if + * `promiseResolve` is set. + * @default true + */ + trackPromises?: boolean | undefined; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the + * [Hook Callbacks](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#hook-callbacks) section. + * + * ```js + * import { createHook } from 'node:async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { }, + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and + * `destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param options The [Hook Callbacks](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#hook-callbacks) to register + * @returns Instance used for disabling and enabling hooks + */ + function createHook(options: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + interface AsyncLocalStorageOptions { + /** + * The default value to be used when no store is provided. + */ + defaultValue?: any; + /** + * A name for the `AsyncLocalStorage` value. + */ + name?: string | undefined; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * safe implementation that involves significant optimizations that are non-obvious + * to implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 0: finish + * // 1: start + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Creates a new instance of `AsyncLocalStorage`. Store is only provided within a + * `run()` call or after an `enterWith()` call. + */ + constructor(options?: AsyncLocalStorageOptions); + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the `asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * The name of the `AsyncLocalStorage` instance if provided. + * @since v24.0.0 + */ + readonly name: string; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: () => R): R; + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()` call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } + /** + * @since v17.2.0, v16.14.0 + * @return A map of provider types to the corresponding numeric id. + * This map contains all the event types that might be emitted by the `async_hooks.init()` event. + */ + namespace asyncWrapProviders { + const NONE: number; + const DIRHANDLE: number; + const DNSCHANNEL: number; + const ELDHISTOGRAM: number; + const FILEHANDLE: number; + const FILEHANDLECLOSEREQ: number; + const FIXEDSIZEBLOBCOPY: number; + const FSEVENTWRAP: number; + const FSREQCALLBACK: number; + const FSREQPROMISE: number; + const GETADDRINFOREQWRAP: number; + const GETNAMEINFOREQWRAP: number; + const HEAPSNAPSHOT: number; + const HTTP2SESSION: number; + const HTTP2STREAM: number; + const HTTP2PING: number; + const HTTP2SETTINGS: number; + const HTTPINCOMINGMESSAGE: number; + const HTTPCLIENTREQUEST: number; + const JSSTREAM: number; + const JSUDPWRAP: number; + const MESSAGEPORT: number; + const PIPECONNECTWRAP: number; + const PIPESERVERWRAP: number; + const PIPEWRAP: number; + const PROCESSWRAP: number; + const PROMISE: number; + const QUERYWRAP: number; + const SHUTDOWNWRAP: number; + const SIGNALWRAP: number; + const STATWATCHER: number; + const STREAMPIPE: number; + const TCPCONNECTWRAP: number; + const TCPSERVERWRAP: number; + const TCPWRAP: number; + const TTYWRAP: number; + const UDPSENDWRAP: number; + const UDPWRAP: number; + const SIGINTWATCHDOG: number; + const WORKER: number; + const WORKERHEAPSNAPSHOT: number; + const WRITEWRAP: number; + const ZLIB: number; + const CHECKPRIMEREQUEST: number; + const PBKDF2REQUEST: number; + const KEYPAIRGENREQUEST: number; + const KEYGENREQUEST: number; + const KEYEXPORTREQUEST: number; + const CIPHERREQUEST: number; + const DERIVEBITSREQUEST: number; + const HASHREQUEST: number; + const RANDOMBYTESREQUEST: number; + const RANDOMPRIMEREQUEST: number; + const SCRYPTREQUEST: number; + const SIGNREQUEST: number; + const TLSWRAP: number; + const VERIFYREQUEST: number; + } +} +declare module "async_hooks" { + export * from "node:async_hooks"; +} diff --git a/node_modules/@types/node/buffer.buffer.d.ts b/node_modules/@types/node/buffer.buffer.d.ts new file mode 100644 index 0000000..a6c4b25 --- /dev/null +++ b/node_modules/@types/node/buffer.buffer.d.ts @@ -0,0 +1,466 @@ +declare module "node:buffer" { + type ImplicitArrayBuffer> = T extends + { valueOf(): infer V extends ArrayBufferLike } ? V : T; + global { + interface BufferConstructor { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: TArrayBuffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from>( + arrayBuffer: TArrayBuffer, + byteOffset?: number, + length?: number, + ): Buffer>; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it must be an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. If the combined length of the `Buffer`s in `list` is + * less than `totalLength`, the remaining space is filled with zeros. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + // TODO: remove globals in future version + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBuffer = Buffer; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type AllowSharedBuffer = Buffer; + } +} diff --git a/node_modules/@types/node/buffer.d.ts b/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000..7cff31f --- /dev/null +++ b/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,1765 @@ +declare module "node:buffer" { + import { ReadableStream } from "node:stream/web"; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: ArrayBuffer | NodeJS.TypedArray): boolean; + export let INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "latin1" + | "binary"; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'node:buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode( + source: Uint8Array, + fromEnc: TranscodeEncoding, + toEnc: TranscodeEncoding, + ): NonSharedBuffer; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { type AllowSharedBuffer, Buffer, type NonSharedBuffer }; + /** @deprecated This alias will be removed in a future version. Use the canonical `BlobPropertyBag` instead. */ + // TODO: remove in future major + export interface BlobOptions extends BlobPropertyBag {} + /** @deprecated This alias will be removed in a future version. Use the canonical `FilePropertyBag` instead. */ + export interface FileOptions extends FilePropertyBag {} + export type WithImplicitCoercion = + | T + | { valueOf(): T } + | (T extends string ? { [Symbol.toPrimitive](hint: "string"): T } : never); + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength( + string: string | NodeJS.ArrayBufferView | ArrayBufferLike, + encoding?: BufferEncoding, + ): number; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of `Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` arguments can be used to limit the comparison to specific ranges within `target` and `buf` respectively. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`, `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): this; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): this; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): this; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + fill(value: string | Uint8Array | number, offset: number, encoding: BufferEncoding): this; + fill(value: string | Uint8Array | number, encoding: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in `encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + indexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + includes(value: string | number | Buffer, encoding: BufferEncoding): boolean; + } + var Buffer: BufferConstructor; + } + // #region web types + export type BlobPart = NodeJS.BufferSource | Blob | string; + export interface BlobPropertyBag { + endings?: "native" | "transparent"; + type?: string; + } + export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; + } + export interface Blob { + readonly size: number; + readonly type: string; + arrayBuffer(): Promise; + bytes(): Promise; + slice(start?: number, end?: number, contentType?: string): Blob; + stream(): ReadableStream; + text(): Promise; + } + export var Blob: { + prototype: Blob; + new(blobParts?: BlobPart[], options?: BlobPropertyBag): Blob; + }; + export interface File extends Blob { + readonly lastModified: number; + readonly name: string; + readonly webkitRelativePath: string; + } + export var File: { + prototype: File; + new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File; + }; + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + // #endregion +} +declare module "buffer" { + export * from "node:buffer"; +} diff --git a/node_modules/@types/node/child_process.d.ts b/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000..e3964ab --- /dev/null +++ b/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1366 @@ +declare module "node:child_process" { + import { NonSharedBuffer } from "node:buffer"; + import * as dgram from "node:dgram"; + import { Abortable, EventEmitter, InternalEventEmitter } from "node:events"; + import * as net from "node:net"; + import { Readable, Stream, Writable } from "node:stream"; + import { URL } from "node:url"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server | dgram.Socket | undefined; + interface ChildProcessEventMap { + "close": [code: number | null, signal: NodeJS.Signals | null]; + "disconnect": []; + "error": [err: Error]; + "exit": [code: number | null, signal: NodeJS.Signals | null]; + "message": [message: Serializable, sendHandle: SendHandle]; + "spawn": []; + } + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess implements EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Control | null; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and `subprocess.stdio[2]` are also available as `subprocess.stdin`, `subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * import assert from 'node:assert'; + * import fs from 'node:fs'; + * import child_process from 'node:child_process'; + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ], + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + * + * When the child process is terminated by a signal, `subprocess.exitCode` will be + * `null` and `subprocess.signalCode` will be set. To get the corresponding + * POSIX exit code, use + * `util.convertProcessSignalToExitCode(subprocess.signalCode)`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to `'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'], + * }, + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * Calls {@link ChildProcess.kill} with `'SIGTERM'`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * import cp from 'node:child_process'; + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the `'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for `'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received and buffered in + * the socket will not be sent to the child. Sending IPC sockets is not supported on Windows. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an `'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const subprocess = fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `node:net` module, `node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using `server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v25.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v25.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v25.x/api/dgram.html#class-dgramsocket) object. + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the `subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + } + interface ChildProcess extends InternalEventEmitter {} + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio + extends ChildProcess + { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface Control extends EventEmitter { + ref(): void; + unref(): void; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = IOType | Array; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default false + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given `command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env, + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * import { spawn } from 'node:child_process'; + * import { once } from 'node:events'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * const [code] = await once(ls, 'close'); + * console.log(`child process exited with code ${code}`); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * import { spawn } from 'node:child_process'; + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so `process.argv[0]` in a Node.js child process will not match the `argv0` parameter passed to `spawn` from the parent. Retrieve + * it with the `process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: readonly string[], + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + encoding?: string | null | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: "buffer" | null; // specify `null`. + } + // TODO: Just Plain Wrong™ (see also nodejs/node#57392) + interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: NodeJS.Signals; + stdout?: string; + stderr?: string; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * import { exec } from 'node:child_process'; + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0` indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * import { exec } from 'node:child_process'; + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const exec = util.promisify(child_process.exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { exec } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: ExecOptionsWithBufferEncoding, + callback?: (error: ExecException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptionsWithStringEncoding, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ExecOptions | undefined | null, + callback?: ( + error: ExecException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void, + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + encoding?: string | null | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + /** @deprecated Use `ExecFileOptions` instead. */ + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {} + // TODO: execFile exceptions can take many forms... this accurately describes none of them + type ExecFileException = + & Omit + & Omit + & { code?: string | number | null }; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * import { execFile } from 'node:child_process'; + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const execFile = util.promisify(child_process.execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { execFile } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + // no `options` definitely means stdout/stderr are `string`. + function execFile( + file: string, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ExecFileOptions | undefined | null, + callback: + | (( + error: ExecFileException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + callback: + | (( + error: ExecFileException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the `options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by `child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * import { fork } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string | URL, options?: ForkOptions): ChildProcess; + function fork(modulePath: string | URL, args?: readonly string[], options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args?: readonly string[], + options?: SpawnSyncOptions, + ): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): NonSharedBuffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): NonSharedBuffer; + function execSync(command: string, options?: ExecSyncOptions): string | NonSharedBuffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null | undefined; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): NonSharedBuffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): NonSharedBuffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | NonSharedBuffer; + function execFileSync(file: string, args: readonly string[]): NonSharedBuffer; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithBufferEncoding, + ): NonSharedBuffer; + function execFileSync( + file: string, + args?: readonly string[], + options?: ExecFileSyncOptions, + ): string | NonSharedBuffer; +} +declare module "child_process" { + export * from "node:child_process"; +} diff --git a/node_modules/@types/node/cluster.d.ts b/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000..80f55ae --- /dev/null +++ b/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,432 @@ +declare module "node:cluster" { + import * as child_process from "node:child_process"; + import { EventEmitter, InternalEventEmitter } from "node:events"; + class Worker implements EventEmitter { + constructor(options?: cluster.WorkerOptions); + /** + * Each new worker is given its own unique id, this id is stored in the `id`. + * + * While a worker is alive, this is the key that indexes it in `cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object + * from this function is stored as `.process`. In a worker, the global `process` is stored. + * + * See: [Child Process module](https://nodejs.org/docs/latest-v25.x/api/child_process.html#child_processforkmodulepath-args-options). + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child_process.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback). + * + * In a worker, this sends a message to the primary. It is identical to `process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. + */ + send(message: child_process.Serializable, callback?: (error: Error | null) => void): boolean; + send( + message: child_process.Serializable, + sendHandle: child_process.SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: child_process.Serializable, + sendHandle: child_process.SendHandle, + options?: child_process.MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is [`kill()`](https://nodejs.org/docs/latest-v25.x/api/process.html#processkillpid-signal). + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * import net from 'node:net'; + * + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): this; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + } + interface Worker extends InternalEventEmitter {} + type _Worker = Worker; + namespace cluster { + interface Worker extends _Worker {} + interface WorkerOptions { + id?: number | undefined; + process?: child_process.ChildProcess | undefined; + state?: string | undefined; + } + interface WorkerEventMap { + "disconnect": []; + "error": [error: Error]; + "exit": [code: number, signal: string]; + "listening": [address: Address]; + "message": [message: any, handle: child_process.SendHandle]; + "online": []; + } + interface ClusterSettings { + /** + * List of string arguments passed to the Node.js executable. + * @default process.execArgv + */ + execArgv?: string[] | undefined; + /** + * File path to worker file. + * @default process.argv[1] + */ + exec?: string | undefined; + /** + * String arguments passed to worker. + * @default process.argv.slice(2) + */ + args?: readonly string[] | undefined; + /** + * Whether or not to send output to parent's stdio. + * @default false + */ + silent?: boolean | undefined; + /** + * Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must + * contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#child_processspawncommand-args-options)'s + * [`stdio`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#optionsstdio). + */ + stdio?: any[] | undefined; + /** + * Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).) + */ + uid?: number | undefined; + /** + * Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).) + */ + gid?: number | undefined; + /** + * Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. + * By default each worker gets its own port, incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. + * See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#advanced-serialization) for more details. + * @default false + */ + serialization?: "json" | "advanced" | undefined; + /** + * Current working directory of the worker process. + * @default undefined (inherits from parent process) + */ + cwd?: string | undefined; + /** + * Hide the forked processes console window that would normally be created on Windows systems. + * @default false + */ + windowsHide?: boolean | undefined; + } + interface Address { + address: string; + port: number; + /** + * The `addressType` is one of: + * + * * `4` (TCPv4) + * * `6` (TCPv6) + * * `-1` (Unix domain socket) + * * `'udp4'` or `'udp6'` (UDPv4 or UDPv6) + */ + addressType: 4 | 6 | -1 | "udp4" | "udp6"; + } + interface ClusterEventMap { + "disconnect": [worker: Worker]; + "exit": [worker: Worker, code: number, signal: string]; + "fork": [worker: Worker]; + "listening": [worker: Worker, address: Address]; + "message": [worker: Worker, message: any, handle: child_process.SendHandle]; + "online": [worker: Worker]; + "setup": [settings: ClusterSettings]; + } + interface Cluster extends InternalEventEmitter { + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + Worker: typeof Worker; + disconnect(callback?: () => void): void; + /** + * Spawn a new worker process. + * + * This can only be called from the primary process. + * @param env Key/value pairs to add to worker process environment. + * @since v0.6.0 + */ + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + /** + * True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` + * is undefined, then `isPrimary` is `true`. + * @since v16.0.0 + */ + readonly isPrimary: boolean; + /** + * True if the process is not a primary (it is the negation of `cluster.isPrimary`). + * @since v0.6.0 + */ + readonly isWorker: boolean; + /** + * The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a + * global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clustersetupprimarysettings) + * is called, whichever comes first. + * + * `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute + * IOCP handles without incurring a large performance hit. + * + * `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`. + * @since v0.11.2 + */ + schedulingPolicy: number; + /** + * After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clustersetupprimarysettings) + * (or [`.fork()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clusterforkenv)) this settings object will contain + * the settings, including the default values. + * + * This object is not intended to be changed or set manually. + * @since v0.7.1 + */ + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clustersetupprimarysettings) instead. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`. + * + * Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clusterforkenv) + * and have no effect on workers that are already running. + * + * The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to + * [`.fork()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clusterforkenv). + * + * The defaults above apply to the first call only; the defaults for later calls are the current values at the time of + * `cluster.setupPrimary()` is called. + * + * ```js + * import cluster from 'node:cluster'; + * + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'https'], + * silent: true, + * }); + * cluster.fork(); // https worker + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'http'], + * }); + * cluster.fork(); // http worker + * ``` + * + * This can only be called from the primary process. + * @since v16.0.0 + */ + setupPrimary(settings?: ClusterSettings): void; + /** + * A reference to the current worker object. Not available in the primary process. + * + * ```js + * import cluster from 'node:cluster'; + * + * if (cluster.isPrimary) { + * console.log('I am primary'); + * cluster.fork(); + * cluster.fork(); + * } else if (cluster.isWorker) { + * console.log(`I am worker #${cluster.worker.id}`); + * } + * ``` + * @since v0.7.0 + */ + readonly worker?: Worker; + /** + * A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process. + * + * A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it + * is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted. + * + * ```js + * import cluster from 'node:cluster'; + * + * for (const worker of Object.values(cluster.workers)) { + * worker.send('big announcement to all workers'); + * } + * ``` + * @since v0.7.0 + */ + readonly workers?: NodeJS.Dict; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + } + } + var cluster: cluster.Cluster; + export = cluster; +} +declare module "cluster" { + import cluster = require("node:cluster"); + export = cluster; +} diff --git a/node_modules/@types/node/compatibility/iterators.d.ts b/node_modules/@types/node/compatibility/iterators.d.ts new file mode 100644 index 0000000..156e785 --- /dev/null +++ b/node_modules/@types/node/compatibility/iterators.d.ts @@ -0,0 +1,21 @@ +// Backwards-compatible iterator interfaces, augmented with iterator helper methods by lib.esnext.iterator in TypeScript 5.6. +// The IterableIterator interface does not contain these methods, which creates assignability issues in places where IteratorObjects +// are expected (eg. DOM-compatible APIs) if lib.esnext.iterator is loaded. +// Also ensures that iterators returned by the Node API, which inherit from Iterator.prototype, correctly expose the iterator helper methods +// if lib.esnext.iterator is loaded. +// TODO: remove once this package no longer supports TS 5.5, and replace NodeJS.BuiltinIteratorReturn with BuiltinIteratorReturn. + +// Placeholders for TS <5.6 +interface IteratorObject {} +interface AsyncIteratorObject {} + +declare namespace NodeJS { + // Populate iterator methods for TS <5.6 + interface Iterator extends globalThis.Iterator {} + interface AsyncIterator extends globalThis.AsyncIterator {} + + // Polyfill for TS 5.6's instrinsic BuiltinIteratorReturn type, required for DOM-compatible iterators + type BuiltinIteratorReturn = ReturnType extends + globalThis.Iterator ? TReturn + : any; +} diff --git a/node_modules/@types/node/console.d.ts b/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000..b7f8833 --- /dev/null +++ b/node_modules/@types/node/console.d.ts @@ -0,0 +1,93 @@ +declare module "node:console" { + import { InspectOptions } from "node:util"; + namespace console { + interface ConsoleOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + /** + * Ignore errors when writing to the underlying streams. + * @default true + */ + ignoreErrors?: boolean | undefined; + /** + * Set color support for this `Console` instance. Setting to true enables coloring while inspecting + * values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color + * support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the + * respective stream. This option can not be used, if `inspectOptions.colors` is set as well. + * @default 'auto' + */ + colorMode?: boolean | "auto" | undefined; + /** + * Specifies options that are passed along to + * [`util.inspect()`](https://nodejs.org/docs/latest-v25.x/api/util.html#utilinspectobject-options). + */ + inspectOptions?: InspectOptions | ReadonlyMap | undefined; + /** + * Set group indentation. + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface Console { + readonly Console: { + prototype: Console; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleOptions): Console; + }; + assert(condition?: unknown, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: InspectOptions): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + trace(...data: any[]): void; + warn(...data: any[]): void; + /** + * This method does not display anything unless used in the inspector. The `console.profile()` + * method starts a JavaScript CPU profile with an optional label until {@link profileEnd} + * is called. The profile is then added to the Profile panel of the inspector. + * + * ```js + * console.profile('MyLabel'); + * // Some code + * console.profileEnd('MyLabel'); + * // Adds the profile 'MyLabel' to the Profiles panel of the inspector. + * ``` + * @since v8.0.0 + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. Stops the current + * JavaScript CPU profiling session if one has been started and prints the report to the + * Profiles panel of the inspector. See {@link profile} for an example. + * + * If this method is called without a label, the most recently started profile is stopped. + * @since v8.0.0 + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. The `console.timeStamp()` + * method adds an event with the label `'label'` to the Timeline panel of the inspector. + * @since v8.0.0 + */ + timeStamp(label?: string): void; + } + } + var console: console.Console; + export = console; +} +declare module "console" { + import console = require("node:console"); + export = console; +} diff --git a/node_modules/@types/node/constants.d.ts b/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000..a271f9a --- /dev/null +++ b/node_modules/@types/node/constants.d.ts @@ -0,0 +1,14 @@ +declare module "node:constants" { + const constants: + & typeof import("node:os").constants.dlopen + & typeof import("node:os").constants.errno + & typeof import("node:os").constants.priority + & typeof import("node:os").constants.signals + & typeof import("node:fs").constants + & typeof import("node:crypto").constants; + export = constants; +} +declare module "constants" { + import constants = require("node:constants"); + export = constants; +} diff --git a/node_modules/@types/node/crypto.d.ts b/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000..3ebfec6 --- /dev/null +++ b/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,4047 @@ +declare module "node:crypto" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { PeerCertificate } from "node:tls"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of HTML5's `keygen` element. + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `node:crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): NonSharedBuffer; + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): NonSharedBuffer; + /** + * ```js + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): NonSharedBuffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): NonSharedBuffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v25.x/docs/api/crypto.html#crypto-constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */ + const SSL_OP_ALLOW_NO_DHE_KEX: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + /** Instructs OpenSSL to disable encrypt-then-MAC. */ + const SSL_OP_NO_ENCRYPT_THEN_MAC: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to disable renegotiation. */ + const SSL_OP_NO_RENEGOTIATION: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + /** Instructs OpenSSL to turn off SSL v2 */ + const SSL_OP_NO_SSLv2: number; + /** Instructs OpenSSL to turn off SSL v3 */ + const SSL_OP_NO_SSLv3: number; + /** Instructs OpenSSL to disable use of RFC4507bis tickets. */ + const SSL_OP_NO_TICKET: number; + /** Instructs OpenSSL to turn off TLS v1 */ + const SSL_OP_NO_TLSv1: number; + /** Instructs OpenSSL to turn off TLS v1.1 */ + const SSL_OP_NO_TLSv1_1: number; + /** Instructs OpenSSL to turn off TLS v1.2 */ + const SSL_OP_NO_TLSv1_2: number; + /** Instructs OpenSSL to turn off TLS v1.3 */ + const SSL_OP_NO_TLSv1_3: number; + /** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */ + const SSL_OP_PRIORITIZE_CHACHA: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHash, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: HashOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): NonSharedBuffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): NonSharedBuffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyFormat = "pem" | "der" | "jwk"; + type KeyObjectType = "secret" | "public" | "private"; + type PublicKeyExportType = "pkcs1" | "spki"; + type PrivateKeyExportType = "pkcs1" | "pkcs8" | "sec1"; + type KeyExportOptions = + | SymmetricKeyExportOptions + | PublicKeyExportOptions + | PrivateKeyExportOptions + | JwkKeyExportOptions; + interface SymmetricKeyExportOptions { + format?: "buffer" | undefined; + } + interface PublicKeyExportOptions { + type: T; + format: Exclude; + } + interface PrivateKeyExportOptions { + type: T; + format: Exclude; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface KeyPairExportOptions< + TPublic extends PublicKeyExportType = PublicKeyExportType, + TPrivate extends PrivateKeyExportType = PrivateKeyExportType, + > { + publicKeyEncoding?: PublicKeyExportOptions | JwkKeyExportOptions | undefined; + privateKeyEncoding?: PrivateKeyExportOptions | JwkKeyExportOptions | undefined; + } + type KeyExportResult = T extends { format: infer F extends KeyFormat } + ? { der: NonSharedBuffer; jwk: webcrypto.JsonWebKey; pem: string }[F] + : Default; + interface KeyPairExportResult { + publicKey: KeyExportResult; + privateKey: KeyExportResult; + } + type KeyPairExportCallback = ( + err: Error | null, + publicKey: KeyExportResult, + privateKey: KeyExportResult, + ) => void; + type MLDSAKeyType = `ml-dsa-${44 | 65 | 87}`; + type MLKEMKeyType = `ml-kem-${1024 | 512 | 768}`; + type SLHDSAKeyType = `slh-dsa-${"sha2" | "shake"}-${128 | 192 | 256}${"f" | "s"}`; + type AsymmetricKeyType = + | "dh" + | "dsa" + | "ec" + | "ed25519" + | "ed448" + | MLDSAKeyType + | MLKEMKeyType + | "rsa-pss" + | "rsa" + | SLHDSAKeyType + | "x25519" + | "x448"; + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number; + /** + * Name of the curve (EC). + */ + namedCurve?: string; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256, + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. See the + * supported [asymmetric key types](https://nodejs.org/docs/latest-v25.x/api/crypto.html#asymmetric-key-types). + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: AsymmetricKeyType; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options?: T): KeyExportResult; + /** + * Returns `true` or `false` depending on whether the keys have exactly the same + * type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack). + * @since v17.7.0, v16.15.0 + * @param otherKeyObject A `KeyObject` with which to compare `keyObject`. + */ + equals(otherKeyObject: KeyObject): boolean; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number; + /** + * Converts a `KeyObject` instance to a `CryptoKey`. + * @since 22.10.0 + */ + toCryptoKey( + algorithm: + | webcrypto.AlgorithmIdentifier + | webcrypto.RsaHashedImportParams + | webcrypto.EcKeyImportParams + | webcrypto.HmacImportParams, + extractable: boolean, + keyUsages: readonly webcrypto.KeyUsage[], + ): webcrypto.CryptoKey; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type CipherChaCha20Poly1305Types = "chacha20-poly1305"; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherChaCha20Poly1305Options extends stream.TransformOptions { + /** @default 16 */ + authTagLength?: number | undefined; + } + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): CipherChaCha20Poly1305; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipheriv; + /** + * Instances of the `Cipheriv` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipheriv} method is + * used to create `Cipheriv` instances. `Cipheriv` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipheriv` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipheriv` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * + * import { + * pipeline, + * } from 'node:stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipheriv extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or `DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): NonSharedBuffer; + update(data: string, inputEncoding: Encoding): NonSharedBuffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipheriv` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): NonSharedBuffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipheriv` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherGCM extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherOCB extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherChaCha20Poly1305 extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + /** + * Creates and returns a `Decipheriv` object that uses the given `algorithm`, `key` and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength` option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): DecipherChaCha20Poly1305; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipheriv; + /** + * Instances of the `Decipheriv` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipheriv} method is + * used to create `Decipheriv` instances. `Decipheriv` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipheriv` objects as streams: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * let chunk; + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipheriv` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipheriv extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data` argument is a string using the specified encoding. If the `inputEncoding` argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding` is specified, a string using the specified encoding is returned. If no `outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): NonSharedBuffer; + update(data: string, inputEncoding: Encoding): NonSharedBuffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipheriv` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): NonSharedBuffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling `decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherChaCha20Poly1305 extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: PrivateKeyExportType | undefined; + passphrase?: string | Buffer | undefined; + encoding?: string | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: PublicKeyExportType | undefined; + encoding?: string | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey, + * } = await import('node:crypto'); + * + * generateKey('hmac', { length: 512 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync, + * } = await import('node:crypto'); + * + * const key = generateKeySync('hmac', { length: 512 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: webcrypto.JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + // TODO: signing algorithm type + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @see crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + context?: ArrayBuffer | NodeJS.ArrayBufferView | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface SignJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1', + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput): NonSharedBuffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances. `Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if `object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If `generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createDiffieHellman, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values unless they have been + * generated or computed already, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, + * once a private key has been generated or set, calling this function only updates + * the public key but does not generate a new private key. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): NonSharedBuffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding?: null, + outputEncoding?: null, + ): NonSharedBuffer; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding?: null, + ): NonSharedBuffer; + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): NonSharedBuffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): NonSharedBuffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): NonSharedBuffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): NonSharedBuffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided, `publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * + * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be + * used to manually provide the public key or to automatically derive it. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `node:constants` module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman, + * } = await import('node:crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2, + * } = await import('node:crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync, + * } = await import('node:crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): NonSharedBuffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): NonSharedBuffer; + function randomBytes(size: number, callback: (err: Error | null, buf: NonSharedBuffer) => void): void; + function pseudoRandomBytes(size: number): NonSharedBuffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: NonSharedBuffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 2**48. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as `buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`. `err` is an exception object when key derivation fails, otherwise `err` is `null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt, + * } = await import('node:crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync, + * } = await import('node:crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options?: ScryptOptions, + ): NonSharedBuffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt( + privateKey: RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt( + privateKey: RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * ```js + * const { + * getCiphers, + * } = await import('node:crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves, + * } = await import('node:crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes, + * } = await import('node:crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createECDH, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'` format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH, + * } = await import('node:crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): NonSharedBuffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): NonSharedBuffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey` lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): NonSharedBuffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): NonSharedBuffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): NonSharedBuffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(encoding?: null, format?: ECDHKeyFormat): NonSharedBuffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function compares the underlying bytes that represent the given `ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * **When both of the inputs are `Float32Array`s or `Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor `Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + interface DHKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> { + /** + * The prime parameter + */ + prime?: Buffer | undefined; + /** + * Prime length in bits + */ + primeLength?: number | undefined; + /** + * Custom generator + * @default 2 + */ + generator?: number | undefined; + /** + * Diffie-Hellman group name + * @see {@link getDiffieHellman} + */ + groupName?: string | undefined; + } + interface DSAKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface ECKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8" | "sec1"> { + /** + * Name of the curve to use + */ + namedCurve: string; + /** + * Must be `'named'` or `'explicit'` + * @default 'named' + */ + paramEncoding?: "explicit" | "named" | undefined; + } + interface ED25519KeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + interface ED448KeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + interface MLDSAKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + interface MLKEMKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + interface RSAPSSKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes + */ + saltLength?: string | undefined; + } + interface RSAKeyPairOptions extends KeyPairExportOptions<"pkcs1" | "spki", "pkcs1" | "pkcs8"> { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface SLHDSAKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + interface X25519KeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + interface X448KeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + /** + * Generates a new asymmetric key pair of the given `type`. See the + * supported [asymmetric key types](https://nodejs.org/docs/latest-v25.x/api/crypto.html#asymmetric-key-types). + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync, + * } = await import('node:crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type The asymmetric key type to generate. See the + * supported [asymmetric key types](https://nodejs.org/docs/latest-v25.x/api/crypto.html#asymmetric-key-types). + */ + function generateKeyPairSync( + type: "dh", + options: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "dsa", + options: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "ec", + options: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "ed25519", + options?: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "ed448", + options?: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: MLDSAKeyType, + options?: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: MLKEMKeyType, + options?: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "rsa-pss", + options: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "rsa", + options: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: SLHDSAKeyType, + options?: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "x25519", + options?: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "x448", + options?: T, + ): KeyPairExportResult; + /** + * Generates a new asymmetric key pair of the given `type`. See the + * supported [asymmetric key types](https://nodejs.org/docs/latest-v25.x/api/crypto.html#asymmetric-key-types). + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair, + * } = await import('node:crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and `publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type The asymmetric key type to generate. See the + * supported [asymmetric key types](https://nodejs.org/docs/latest-v25.x/api/crypto.html#asymmetric-key-types). + */ + function generateKeyPair( + type: "dh", + options: T, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "dsa", + options: T, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "ec", + options: T, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "ed25519", + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "ed448", + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: MLDSAKeyType, + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: MLKEMKeyType, + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: T, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "rsa", + options: T, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: SLHDSAKeyType, + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "x25519", + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "x448", + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "dh", + options: T, + ): Promise>; + function __promisify__( + type: "dsa", + options: T, + ): Promise>; + function __promisify__( + type: "ec", + options: T, + ): Promise>; + function __promisify__( + type: "ed25519", + options?: T, + ): Promise>; + function __promisify__( + type: "ed448", + options?: T, + ): Promise>; + function __promisify__( + type: MLDSAKeyType, + options?: T, + ): Promise>; + function __promisify__( + type: MLKEMKeyType, + options?: T, + ): Promise>; + function __promisify__( + type: "rsa-pss", + options: T, + ): Promise>; + function __promisify__( + type: "rsa", + options: T, + ): Promise>; + function __promisify__( + type: SLHDSAKeyType, + options?: T, + ): Promise>; + function __promisify__( + type: "x25519", + options?: T, + ): Promise>; + function __promisify__( + type: "x448", + options?: T, + ): Promise>; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type. + * + * `algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, and + * ML-DSA. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + ): NonSharedBuffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + callback: (error: Error | null, data: NonSharedBuffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If + * `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type. + * + * `algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, and + * ML-DSA. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void, + ): void; + /** + * Key decapsulation using a KEM algorithm with a private key. + * + * Supported key types and their KEM algorithms are: + * + * * `'rsa'` RSA Secret Value Encapsulation + * * `'ec'` DHKEM(P-256, HKDF-SHA256), DHKEM(P-384, HKDF-SHA256), DHKEM(P-521, HKDF-SHA256) + * * `'x25519'` DHKEM(X25519, HKDF-SHA256) + * * `'x448'` DHKEM(X448, HKDF-SHA512) + * * `'ml-kem-512'` ML-KEM + * * `'ml-kem-768'` ML-KEM + * * `'ml-kem-1024'` ML-KEM + * + * If `key` is not a {@link KeyObject}, this function behaves as if `key` had been + * passed to `crypto.createPrivateKey()`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v24.7.0 + */ + function decapsulate( + key: KeyLike | PrivateKeyInput | JsonWebKeyInput, + ciphertext: ArrayBuffer | NodeJS.ArrayBufferView, + ): NonSharedBuffer; + function decapsulate( + key: KeyLike | PrivateKeyInput | JsonWebKeyInput, + ciphertext: ArrayBuffer | NodeJS.ArrayBufferView, + callback: (err: Error, sharedKey: NonSharedBuffer) => void, + ): void; + /** + * Computes the Diffie-Hellman shared secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType` and must support either the DH or + * ECDH operation. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): NonSharedBuffer; + function diffieHellman( + options: { privateKey: KeyObject; publicKey: KeyObject }, + callback: (err: Error | null, secret: NonSharedBuffer) => void, + ): void; + /** + * Key encapsulation using a KEM algorithm with a public key. + * + * Supported key types and their KEM algorithms are: + * + * * `'rsa'` RSA Secret Value Encapsulation + * * `'ec'` DHKEM(P-256, HKDF-SHA256), DHKEM(P-384, HKDF-SHA256), DHKEM(P-521, HKDF-SHA256) + * * `'x25519'` DHKEM(X25519, HKDF-SHA256) + * * `'x448'` DHKEM(X448, HKDF-SHA512) + * * `'ml-kem-512'` ML-KEM + * * `'ml-kem-768'` ML-KEM + * * `'ml-kem-1024'` ML-KEM + * + * If `key` is not a {@link KeyObject}, this function behaves as if `key` had been + * passed to `crypto.createPublicKey()`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v24.7.0 + */ + function encapsulate( + key: KeyLike | PublicKeyInput | JsonWebKeyInput, + ): { sharedKey: NonSharedBuffer; ciphertext: NonSharedBuffer }; + function encapsulate( + key: KeyLike | PublicKeyInput | JsonWebKeyInput, + callback: (err: Error, result: { sharedKey: NonSharedBuffer; ciphertext: NonSharedBuffer }) => void, + ): void; + interface OneShotDigestOptions { + /** + * Encoding used to encode the returned digest. + * @default 'hex' + */ + outputEncoding?: BinaryToTextEncoding | "buffer" | undefined; + /** + * For XOF hash functions such as 'shake256', the outputLength option + * can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + interface OneShotDigestOptionsWithStringEncoding extends OneShotDigestOptions { + outputEncoding?: BinaryToTextEncoding | undefined; + } + interface OneShotDigestOptionsWithBufferEncoding extends OneShotDigestOptions { + outputEncoding: "buffer"; + } + /** + * A utility for creating one-shot hash digests of data. It can be faster than + * the object-based `crypto.createHash()` when hashing a smaller amount of data + * (<= 5MB) that's readily available. If the data can be big or if it is streamed, + * it's still recommended to use `crypto.createHash()` instead. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * If `options` is a string, then it specifies the `outputEncoding`. + * + * Example: + * + * ```js + * import crypto from 'node:crypto'; + * import { Buffer } from 'node:buffer'; + * + * // Hashing a string and return the result as a hex-encoded string. + * const string = 'Node.js'; + * // 10b3493287f831e81a438811a1ffba01f8cec4b7 + * console.log(crypto.hash('sha1', string)); + * + * // Encode a base64-encoded string into a Buffer, hash it and return + * // the result as a buffer. + * const base64 = 'Tm9kZS5qcw=='; + * // + * console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer')); + * ``` + * @since v21.7.0, v20.12.0 + * @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different + * input encoding is desired for a string input, user could encode the string + * into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing + * the encoded `TypedArray` into this API instead. + */ + function hash( + algorithm: string, + data: BinaryLike, + options?: OneShotDigestOptionsWithStringEncoding | BinaryToTextEncoding, + ): string; + function hash( + algorithm: string, + data: BinaryLike, + options: OneShotDigestOptionsWithBufferEncoding | "buffer", + ): NonSharedBuffer; + function hash( + algorithm: string, + data: BinaryLike, + options: OneShotDigestOptions | BinaryToTextEncoding | "buffer", + ): string | NonSharedBuffer; + type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdf, + * } = await import('node:crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdfSync, + * } = await import('node:crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + type UUID = `${string}-${string}-${string}-${string}-${string}`; + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): UUID; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: "always" | "default" | "never" | undefined; + /** + * @default true + */ + wildcards?: boolean | undefined; + /** + * @default true + */ + partialWildcards?: boolean | undefined; + /** + * @default false + */ + multiLabelWildcards?: boolean | undefined; + /** + * @default false + */ + singleLabelSubdomains?: boolean | undefined; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('node:crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: NonSharedBuffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The algorithm used to sign the certificate or `undefined` if the signature algorithm is unknown by OpenSSL. + * @since v24.9.0 + */ + readonly signatureAlgorithm: string | undefined; + /** + * The OID of the algorithm used to sign the certificate. + * @since v24.9.0 + */ + readonly signatureAlgorithmOid: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time from which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validFromDate: Date; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + /** + * The date/time until which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validToDate: Date; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was potentially issued by the given `otherCert` + * by comparing the certificate metadata. + * + * This is useful for pruning a list of possible issuer certificates which have been + * selected using a more rudimentary filtering routine, i.e. just based on subject + * and issuer names. + * + * Finally, to verify that this certificate's signature was produced by a private key + * corresponding to `otherCert`'s public key use `x509.verify(publicKey)` + * with `otherCert`'s public key represented as a `KeyObject` + * like so + * + * ```js + * if (!x509.verify(otherCert.publicKey)) { + * throw new Error('otherCert did not issue x509'); + * } + * ``` + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` + * @since v0.11.11 + * @param flags + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. + * @since v17.4.0 + * @return Returns `typedArray`. + */ + function getRandomValues< + T extends Exclude< + NodeJS.NonSharedTypedArray, + NodeJS.NonSharedFloat16Array | NodeJS.NonSharedFloat32Array | NodeJS.NonSharedFloat64Array + >, + >(typedArray: T): T; + type Argon2Algorithm = "argon2d" | "argon2i" | "argon2id"; + interface Argon2Parameters { + /** + * REQUIRED, this is the password for password hashing applications of Argon2. + */ + message: string | ArrayBuffer | NodeJS.ArrayBufferView; + /** + * REQUIRED, must be at least 8 bytes long. This is the salt for password hashing applications of Argon2. + */ + nonce: string | ArrayBuffer | NodeJS.ArrayBufferView; + /** + * REQUIRED, degree of parallelism determines how many computational chains (lanes) + * can be run. Must be greater than 1 and less than `2**24-1`. + */ + parallelism: number; + /** + * REQUIRED, the length of the key to generate. Must be greater than 4 and + * less than `2**32-1`. + */ + tagLength: number; + /** + * REQUIRED, memory cost in 1KiB blocks. Must be greater than + * `8 * parallelism` and less than `2**32-1`. The actual number of blocks is rounded + * down to the nearest multiple of `4 * parallelism`. + */ + memory: number; + /** + * REQUIRED, number of passes (iterations). Must be greater than 1 and less + * than `2**32-1`. + */ + passes: number; + /** + * OPTIONAL, Random additional input, + * similar to the salt, that should **NOT** be stored with the derived key. This is known as pepper in + * password hashing applications. If used, must have a length not greater than `2**32-1` bytes. + */ + secret?: string | ArrayBuffer | NodeJS.ArrayBufferView | undefined; + /** + * OPTIONAL, Additional data to + * be added to the hash, functionally equivalent to salt or secret, but meant for + * non-random data. If used, must have a length not greater than `2**32-1` bytes. + */ + associatedData?: string | ArrayBuffer | NodeJS.ArrayBufferView | undefined; + } + /** + * Provides an asynchronous [Argon2](https://www.rfc-editor.org/rfc/rfc9106.html) implementation. Argon2 is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `nonce` should be as unique as possible. It is recommended that a nonce is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `message`, `nonce`, `secret` or `associatedData`, please + * consider [caveats when using strings as inputs to cryptographic APIs](https://nodejs.org/docs/latest-v25.x/api/crypto.html#using-strings-as-inputs-to-cryptographic-apis). + * + * The `callback` function is called with two arguments: `err` and `derivedKey`. + * `err` is an exception object when key derivation fails, otherwise `err` is + * `null`. `derivedKey` is passed to the callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { argon2, randomBytes } = await import('node:crypto'); + * + * const parameters = { + * message: 'password', + * nonce: randomBytes(16), + * parallelism: 4, + * tagLength: 64, + * memory: 65536, + * passes: 3, + * }; + * + * argon2('argon2id', parameters, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // 'af91dad...9520f15' + * }); + * ``` + * @since v24.7.0 + * @param algorithm Variant of Argon2, one of `"argon2d"`, `"argon2i"` or `"argon2id"`. + * @experimental + */ + function argon2( + algorithm: Argon2Algorithm, + parameters: Argon2Parameters, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous [Argon2][] implementation. Argon2 is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `nonce` should be as unique as possible. It is recommended that a nonce is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `message`, `nonce`, `secret` or `associatedData`, please + * consider [caveats when using strings as inputs to cryptographic APIs](https://nodejs.org/docs/latest-v25.x/api/crypto.html#using-strings-as-inputs-to-cryptographic-apis). + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { argon2Sync, randomBytes } = await import('node:crypto'); + * + * const parameters = { + * message: 'password', + * nonce: randomBytes(16), + * parallelism: 4, + * tagLength: 64, + * memory: 65536, + * passes: 3, + * }; + * + * const derivedKey = argon2Sync('argon2id', parameters); + * console.log(derivedKey.toString('hex')); // 'af91dad...9520f15' + * ``` + * @since v24.7.0 + * @experimental + */ + function argon2Sync(algorithm: Argon2Algorithm, parameters: Argon2Parameters): NonSharedBuffer; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type AlgorithmIdentifier = Algorithm | string; + type BigInteger = NodeJS.NonSharedUint8Array; + type KeyFormat = "jwk" | "pkcs8" | "raw" | "raw-public" | "raw-secret" | "raw-seed" | "spki"; + type KeyType = "private" | "public" | "secret"; + type KeyUsage = + | "decapsulateBits" + | "decapsulateKey" + | "decrypt" + | "deriveBits" + | "deriveKey" + | "encapsulateBits" + | "encapsulateKey" + | "encrypt" + | "sign" + | "unwrapKey" + | "verify" + | "wrapKey"; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + interface AeadParams extends Algorithm { + additionalData?: NodeJS.BufferSource; + iv: NodeJS.BufferSource; + tagLength: number; + } + interface AesCbcParams extends Algorithm { + iv: NodeJS.BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: NodeJS.BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface Argon2Params extends Algorithm { + associatedData?: NodeJS.BufferSource; + memory: number; + nonce: NodeJS.BufferSource; + parallelism: number; + passes: number; + secretValue?: NodeJS.BufferSource; + version?: number; + } + interface CShakeParams extends Algorithm { + customization?: NodeJS.BufferSource; + functionName?: NodeJS.BufferSource; + length: number; + } + interface ContextParams extends Algorithm { + context?: NodeJS.BufferSource; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: NodeJS.BufferSource; + salt: NodeJS.BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface KmacImportParams extends Algorithm { + length?: number; + } + interface KmacKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface KmacKeyGenParams extends Algorithm { + length?: number; + } + interface KmacParams extends Algorithm { + customization?: NodeJS.BufferSource; + length: number; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: NodeJS.BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: NodeJS.BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues< + T extends Exclude< + NodeJS.NonSharedTypedArray, + NodeJS.NonSharedFloat16Array | NodeJS.NonSharedFloat32Array | NodeJS.NonSharedFloat64Array + >, + >( + typedArray: T, + ): T; + randomUUID(): UUID; + } + interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: KeyType; + readonly usages: KeyUsage[]; + } + interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; + } + interface EncapsulatedBits { + sharedKey: ArrayBuffer; + ciphertext: ArrayBuffer; + } + interface EncapsulatedKey { + sharedKey: CryptoKey; + ciphertext: ArrayBuffer; + } + interface SubtleCrypto { + decapsulateBits( + decapsulationAlgorithm: AlgorithmIdentifier, + decapsulationKey: CryptoKey, + ciphertext: NodeJS.BufferSource, + ): Promise; + decapsulateKey( + decapsulationAlgorithm: AlgorithmIdentifier, + decapsulationKey: CryptoKey, + ciphertext: NodeJS.BufferSource, + sharedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams | KmacImportParams, + extractable: boolean, + usages: KeyUsage[], + ): Promise; + decrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AeadParams, + key: CryptoKey, + data: NodeJS.BufferSource, + ): Promise; + deriveBits( + algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params | Argon2Params, + baseKey: CryptoKey, + length?: number | null, + ): Promise; + deriveKey( + algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params | Argon2Params, + baseKey: CryptoKey, + derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | KmacImportParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + digest(algorithm: AlgorithmIdentifier | CShakeParams, data: NodeJS.BufferSource): Promise; + encapsulateBits( + encapsulationAlgorithm: AlgorithmIdentifier, + encapsulationKey: CryptoKey, + ): Promise; + encapsulateKey( + encapsulationAlgorithm: AlgorithmIdentifier, + encapsulationKey: CryptoKey, + sharedKeyAlgorithm: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | KmacImportParams, + extractable: boolean, + usages: KeyUsage[], + ): Promise; + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AeadParams, + key: CryptoKey, + data: NodeJS.BufferSource, + ): Promise; + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + exportKey(format: KeyFormat, key: CryptoKey): Promise; + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params | KmacKeyGenParams, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + getPublicKey(key: CryptoKey, keyUsages: KeyUsage[]): Promise; + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm + | KmacImportParams, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + importKey( + format: Exclude, + keyData: NodeJS.BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm + | KmacImportParams, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | ContextParams | KmacParams, + key: CryptoKey, + data: NodeJS.BufferSource, + ): Promise; + unwrapKey( + format: KeyFormat, + wrappedKey: NodeJS.BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AeadParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm + | KmacImportParams, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | ContextParams | KmacParams, + key: CryptoKey, + signature: NodeJS.BufferSource, + data: NodeJS.BufferSource, + ): Promise; + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AeadParams, + ): Promise; + } + } +} +declare module "crypto" { + export * from "node:crypto"; +} diff --git a/node_modules/@types/node/dgram.d.ts b/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000..8665497 --- /dev/null +++ b/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,537 @@ +declare module "node:dgram" { + import { NonSharedBuffer } from "node:buffer"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter, InternalEventEmitter } from "node:events"; + import { AddressInfo, BlockList } from "node:net"; + interface RemoteInfo { + address: string; + family: "IPv4" | "IPv6"; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = "udp4" | "udp6"; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + reusePort?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: + | (( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void) + | undefined; + receiveBlockList?: BlockList | undefined; + sendBlockList?: BlockList | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket; + interface SocketEventMap { + "close": []; + "connect": []; + "error": [err: Error]; + "listening": []; + "message": [msg: NonSharedBuffer, rinfo: RemoteInfo]; + } + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket implements EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family`, and `port` properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of send requests currently in the queue awaiting to be processed. + */ + getSendQueueCount(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer` with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on `localhost`: + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no additional effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given `sourceAddress` and `groupAddress`, using the `multicastInterface` with the `IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + interface Socket extends InternalEventEmitter {} +} +declare module "dgram" { + export * from "node:dgram"; +} diff --git a/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000..fa83612 --- /dev/null +++ b/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,552 @@ +declare module "node:diagnostics_channel" { + import { AsyncLocalStorage } from "node:async_hooks"; + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to publish to a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; + /** + * Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing + * channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channelsByName = diagnostics_channel.tracingChannel('my-channel'); + * + * // or... + * + * const channelsByCollection = diagnostics_channel.tracingChannel({ + * start: diagnostics_channel.channel('tracing:my-channel:start'), + * end: diagnostics_channel.channel('tracing:my-channel:end'), + * asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), + * asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), + * error: diagnostics_channel.channel('tracing:my-channel:error'), + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param nameOrChannels Channel name or object containing all the `TracingChannel Channels` + * @return Collection of channels to trace with + */ + function tracingChannel< + StoreType = unknown, + ContextType extends object = StoreType extends object ? StoreType : object, + >( + nameOrChannels: string | TracingChannelCollection, + ): TracingChannel; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is used to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will trigger + * message handlers synchronously so they will execute within the same context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message', + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + /** + * When `channel.runStores(context, ...)` is called, the given context data + * will be applied to any store bound to the channel. If the store has already been + * bound the previous `transform` function will be replaced with the new one. + * The `transform` function may be omitted to set the given context data as the + * context directly. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (data) => { + * return { data }; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to which to bind the context data + * @param transform Transform context data before setting the store context + */ + bindStore(store: AsyncLocalStorage, transform?: (context: ContextType) => StoreType): void; + /** + * Remove a message handler previously registered to this channel with `channel.bindStore(store)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store); + * channel.unbindStore(store); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to unbind from the channel. + * @return `true` if the store was found, `false` otherwise. + */ + unbindStore(store: AsyncLocalStorage): boolean; + /** + * Applies the given data to any AsyncLocalStorage instances bound to the channel + * for the duration of the given function, then publishes to the channel within + * the scope of that data is applied to the stores. + * + * If a transform function was given to `channel.bindStore(store)` it will be + * applied to transform the message data before it becomes the context value for + * the store. The prior storage context is accessible from within the transform + * function in cases where context linking is required. + * + * The context applied to the store should be accessible in any async code which + * continues from execution which began during the given function, however + * there are some situations in which `context loss` may occur. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (message) => { + * const parent = store.getStore(); + * return new Span(message, parent); + * }); + * channel.runStores({ some: 'message' }, () => { + * store.getStore(); // Span({ some: 'message' }) + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param context Message to send to subscribers and bind to stores + * @param fn Handler to run within the entered storage context + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runStores( + context: ContextType, + fn: (this: ThisArg, ...args: Args) => Result, + thisArg?: ThisArg, + ...args: Args + ): Result; + } + interface TracingChannelSubscribers { + start: (message: ContextType) => void; + end: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncStart: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncEnd: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + error: ( + message: ContextType & { + error: unknown; + }, + ) => void; + } + interface TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + } + /** + * The class `TracingChannel` is a collection of `TracingChannel Channels` which + * together express a single traceable action. It is used to formalize and + * simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a + * single `TracingChannel` at the top-level of the file rather than creating them + * dynamically. + * @since v19.9.0 + * @experimental + */ + class TracingChannel implements TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + /** + * Helper to subscribe a collection of functions to the corresponding channels. + * This is the same as calling `channel.subscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.subscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + */ + subscribe(subscribers: TracingChannelSubscribers): void; + /** + * Helper to unsubscribe a collection of functions from the corresponding channels. + * This is the same as calling `channel.unsubscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.unsubscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + * @return `true` if all handlers were successfully unsubscribed, and `false` otherwise. + */ + unsubscribe(subscribers: TracingChannelSubscribers): void; + /** + * Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error. + * This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceSync(() => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Function to wrap a trace around + * @param context Shared object to correlate events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceSync( + fn: (this: ThisArg, ...args: Args) => Result, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also + * produce an `error event` if the given function throws an error or the + * returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.tracePromise(async () => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Promise-returning function to wrap a trace around + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return Chained from promise returned by the given function + */ + tracePromise( + fn: (this: ThisArg, ...args: Args) => Promise, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Promise; + /** + * Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or + * the returned + * promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * The `position` will be -1 by default to indicate the final argument should + * be used as the callback. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceCallback((arg1, callback) => { + * // Do something + * callback(null, 'result'); + * }, 1, { + * some: 'thing', + * }, thisArg, arg1, callback); + * ``` + * + * The callback will also be run with `channel.runStores(context, ...)` which + * enables context loss recovery in some cases. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * const myStore = new AsyncLocalStorage(); + * + * // The start channel sets the initial store data to something + * // and stores that store data value on the trace context object + * channels.start.bindStore(myStore, (data) => { + * const span = new Span(data); + * data.span = span; + * return span; + * }); + * + * // Then asyncStart can restore from that data it stored previously + * channels.asyncStart.bindStore(myStore, (data) => { + * return data.span; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn callback using function to wrap a trace around + * @param position Zero-indexed argument position of expected callback + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceCallback( + fn: (this: ThisArg, ...args: Args) => Result, + position?: number, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * `true` if any of the individual channels has a subscriber, `false` if not. + * + * This is a helper method available on a {@link TracingChannel} instance to check + * if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers. + * A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise. + * + * ```js + * const diagnostics_channel = require('node:diagnostics_channel'); + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * if (channels.hasSubscribers) { + * // Do something + * } + * ``` + * @since v22.0.0, v20.13.0 + */ + readonly hasSubscribers: boolean; + } +} +declare module "diagnostics_channel" { + export * from "node:diagnostics_channel"; +} diff --git a/node_modules/@types/node/dns.d.ts b/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000..2e0941e --- /dev/null +++ b/node_modules/@types/node/dns.d.ts @@ -0,0 +1,876 @@ +declare module "node:dns" { + // Supported getaddrinfo flags. + /** + * Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are + * only returned if the current system has at least one IPv4 address configured. + */ + const ADDRCONFIG: number; + /** + * If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported + * on some operating systems (e.g. FreeBSD 10.1). + */ + const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + const ALL: number; + interface LookupOptions { + /** + * The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons, `'IPv4'` and `'IPv6'` are interpreted + * as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used + * with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned. + * @default 0 + */ + family?: number | "IPv4" | "IPv6" | undefined; + /** + * One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v25.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be + * passed by bitwise `OR`ing their values. + */ + hints?: number | undefined; + /** + * When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. + * @default false + */ + all?: boolean | undefined; + /** + * When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted + * by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 + * addresses before IPv4 addresses. Default value is configurable using + * {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--dns-result-orderorder). + * @default `verbatim` (addresses are not reordered) + * @since v22.1.0 + */ + order?: "ipv4first" | "ipv6first" | "verbatim" | undefined; + /** + * When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 + * addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, + * `order` has higher precedence. New code should only use `order`. Default value is configurable using {@link setDefaultResultOrder} + * @default true (addresses are not reordered) + * @deprecated Please use `order` option + */ + verbatim?: boolean | undefined; + } + interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + interface LookupAllOptions extends LookupOptions { + all: true; + } + interface LookupAddress { + /** + * A string representation of an IPv4 or IPv6 address. + */ + address: string; + /** + * `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a + * bug in the name resolution service used by the operating system. + */ + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v25.x/api/dns.html#implementation-considerations) + * before using `dns.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v25.x/api/util.html#utilpromisifyoriginal) ed + * version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties. + * @since v0.1.90 + */ + function lookup( + hostname: string, + family: number, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + function lookup( + hostname: string, + options: LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + function lookup( + hostname: string, + options: LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, + ): void; + function lookup( + hostname: string, + options: LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, + ): void; + function lookup( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) object, + * where `err.code` is the error code. + * + * ```js + * import dns from 'node:dns'; + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v25.x/api/util.html#utilpromisifyoriginal) ed + * version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + function lookupService( + address: string, + port: number, + callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, + ): void; + namespace lookupService { + function __promisify__( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + } + interface ResolveOptions { + ttl: boolean; + } + interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + interface RecordWithTtl { + address: string; + ttl: number; + } + interface AnyARecord extends RecordWithTtl { + type: "A"; + } + interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + interface CaaRecord { + critical: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + interface AnyCaaRecord extends CaaRecord { + type: "CAA"; + } + interface MxRecord { + priority: number; + exchange: string; + } + interface AnyMxRecord extends MxRecord { + type: "MX"; + } + interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + interface TlsaRecord { + certUsage: number; + selector: number; + match: number; + data: ArrayBuffer; + } + interface AnyTlsaRecord extends TlsaRecord { + type: "TLSA"; + } + interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + interface AnyNsRecord { + type: "NS"; + value: string; + } + interface AnyPtrRecord { + type: "PTR"; + value: string; + } + interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + type AnyRecord = + | AnyARecord + | AnyAaaaRecord + | AnyCaaRecord + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | AnyTlsaRecord + | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) object, + * where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "ANY", + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "CAA", + callback: (err: NodeJS.ErrnoException | null, address: CaaRecord[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "MX", + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "NAPTR", + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "SOA", + callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, + ): void; + function resolve( + hostname: string, + rrtype: "SRV", + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "TLSA", + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[], + ) => void, + ): void; + namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "CAA"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TLSA"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + function resolve4( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + function resolve4( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + function resolve4( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + function resolve6( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + function resolve6( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + function resolve6( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + function resolveCname( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, + ): void; + namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + function resolveMx( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + function resolveNaptr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + function resolveNs( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + function resolvePtr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + function resolveSoa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, + ): void; + namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + function resolveSrv( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. The `records` argument passed to the `callback` function is an + * array of objects with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v23.9.0, v22.15.0 + */ + function resolveTlsa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + namespace resolveTlsa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + function resolveTxt( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see + * [RFC 8482](https://tools.ietf.org/html/rfc8482). + */ + function resolveAny( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) object, where `err.code` is + * one of the [DNS error codes](https://nodejs.org/docs/latest-v25.x/api/dns.html#error-codes). + * @since v0.1.16 + */ + function reverse( + ip: string, + callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, + ): void; + /** + * Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v25.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `order` defaulting to `ipv4first`. + * * `ipv6first`: for `order` defaulting to `ipv6first`. + * * `verbatim`: for `order` defaulting to `verbatim`. + * @since v18.17.0 + */ + function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve}, `dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + function getServers(): string[]; + /** + * Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v25.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and {@link setDefaultResultOrder} have higher + * priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--dns-result-orderorder). When using + * [worker threads](https://nodejs.org/docs/latest-v25.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main + * thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + const NODATA: "ENODATA"; + const FORMERR: "EFORMERR"; + const SERVFAIL: "ESERVFAIL"; + const NOTFOUND: "ENOTFOUND"; + const NOTIMP: "ENOTIMP"; + const REFUSED: "EREFUSED"; + const BADQUERY: "EBADQUERY"; + const BADNAME: "EBADNAME"; + const BADFAMILY: "EBADFAMILY"; + const BADRESP: "EBADRESP"; + const CONNREFUSED: "ECONNREFUSED"; + const TIMEOUT: "ETIMEOUT"; + const EOF: "EOF"; + const FILE: "EFILE"; + const NOMEM: "ENOMEM"; + const DESTRUCTION: "EDESTRUCTION"; + const BADSTR: "EBADSTR"; + const BADFLAGS: "EBADFLAGS"; + const NONAME: "ENONAME"; + const BADHINTS: "EBADHINTS"; + const NOTINITIALIZED: "ENOTINITIALIZED"; + const LOADIPHLPAPI: "ELOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + const CANCELLED: "ECANCELLED"; + interface ResolverOptions { + /** + * Query timeout in milliseconds, or `-1` to use the default timeout. + */ + timeout?: number | undefined; + /** + * The number of tries the resolver will try contacting each name server before giving up. + * @default 4 + */ + tries?: number | undefined; + /** + * The max retry timeout, in milliseconds. + * @default 0 + */ + maxTimeout?: number | undefined; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v25.x/api/dns.html#dnssetserversservers) does not affect + * other resolvers: + * + * ```js + * import { Resolver } from 'node:dns'; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `node:dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns" { + export * as promises from "node:dns/promises"; +} +declare module "dns" { + export * from "node:dns"; +} diff --git a/node_modules/@types/node/dns/promises.d.ts b/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000..b9e091c --- /dev/null +++ b/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,497 @@ +declare module "node:dns/promises" { + import { + AnyRecord, + CaaRecord, + LookupAddress, + LookupAllOptions, + LookupOneOptions, + LookupOptions, + MxRecord, + NaptrRecord, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + ResolveWithTtlOptions, + SoaRecord, + SrvRecord, + TlsaRecord, + } from "node:dns"; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * + * ```js + * import dnsPromises from 'node:dns'; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TLSA"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve(hostname: string, rrtype: string): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. On success, the `Promise` is resolved with an array of objectsAdd commentMore actions + * with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v23.9.0, v22.15.0 + */ + function resolveTlsa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Set the default value of `order` in `dns.lookup()` and `{@link lookup}`. The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * from the main thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + const NODATA: "ENODATA"; + const FORMERR: "EFORMERR"; + const SERVFAIL: "ESERVFAIL"; + const NOTFOUND: "ENOTFOUND"; + const NOTIMP: "ENOTIMP"; + const REFUSED: "EREFUSED"; + const BADQUERY: "EBADQUERY"; + const BADNAME: "EBADNAME"; + const BADFAMILY: "EBADFAMILY"; + const BADRESP: "EBADRESP"; + const CONNREFUSED: "ECONNREFUSED"; + const TIMEOUT: "ETIMEOUT"; + const EOF: "EOF"; + const FILE: "EFILE"; + const NOMEM: "ENOMEM"; + const DESTRUCTION: "EDESTRUCTION"; + const BADSTR: "EBADSTR"; + const BADFLAGS: "EBADFLAGS"; + const NONAME: "ENONAME"; + const BADHINTS: "EBADHINTS"; + const NOTINITIALIZED: "ENOTINITIALIZED"; + const LOADIPHLPAPI: "ELOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + const CANCELLED: "ECANCELLED"; + + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect + * other resolvers: + * + * ```js + * import { promises } from 'node:dns'; + * const resolver = new promises.Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "dns/promises" { + export * from "node:dns/promises"; +} diff --git a/node_modules/@types/node/domain.d.ts b/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000..8e03a7d --- /dev/null +++ b/node_modules/@types/node/domain.d.ts @@ -0,0 +1,150 @@ +declare module "node:domain" { + import { EventEmitter } from "node:events"; + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of event emitters that have been explicitly added to the domain. + */ + members: EventEmitter[]; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context, `exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and low-level requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * import domain from 'node:domain'; + * import fs from 'node:fs'; + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * If the `EventEmitter` was already bound to a domain, it is removed from that + * one, and bound to this one instead. + * @param emitter emitter to be added to the domain + */ + add(emitter: EventEmitter): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter to be removed from the domain + */ + remove(emitter: EventEmitter): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module "domain" { + export * from "node:domain"; +} diff --git a/node_modules/@types/node/events.d.ts b/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000..b4cd8c3 --- /dev/null +++ b/node_modules/@types/node/events.d.ts @@ -0,0 +1,1011 @@ +declare module "node:events" { + import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; + // #region Event map helpers + type EventMap = Record; + type IfEventMap, True, False> = {} extends Events ? False : True; + type Args, EventName extends string | symbol> = IfEventMap< + Events, + EventName extends keyof Events ? Events[EventName] + : EventName extends keyof EventEmitterEventMap ? EventEmitterEventMap[EventName] + : any[], + any[] + >; + type EventNames, EventName extends string | symbol> = IfEventMap< + Events, + EventName | (keyof Events & (string | symbol)) | keyof EventEmitterEventMap, + string | symbol + >; + type Listener, EventName extends string | symbol> = IfEventMap< + Events, + ( + ...args: EventName extends keyof Events ? Events[EventName] + : EventName extends keyof EventEmitterEventMap ? EventEmitterEventMap[EventName] + : any[] + ) => void, + (...args: any[]) => void + >; + interface EventEmitterEventMap { + newListener: [eventName: string | symbol, listener: (...args: any[]) => void]; + removeListener: [eventName: string | symbol, listener: (...args: any[]) => void]; + } + // #endregion + interface EventEmitterOptions { + /** + * It enables + * [automatic capturing of promise rejection](https://nodejs.org/docs/latest-v25.x/api/events.html#capture-rejections-of-promises). + * @default false + */ + captureRejections?: boolean | undefined; + } + /** + * The `EventEmitter` class is defined and exposed by the `node:events` module: + * + * ```js + * import { EventEmitter } from 'node:events'; + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter = any> { + constructor(options?: EventEmitterOptions); + } + interface EventEmitter = any> extends NodeJS.EventEmitter {} + global { + namespace NodeJS { + interface EventEmitter = any> { + /** + * The `Symbol.for('nodejs.rejection')` method is called in case a + * promise rejection happens when emitting an event and + * `captureRejections` is enabled on the emitter. + * It is possible to use `events.captureRejectionSymbol` in + * place of `Symbol.for('nodejs.rejection')`. + * + * ```js + * import { EventEmitter, captureRejectionSymbol } from 'node:events'; + * + * class MyClass extends EventEmitter { + * constructor() { + * super({ captureRejections: true }); + * } + * + * [captureRejectionSymbol](err, event, ...args) { + * console.log('rejection happened for', event, 'with', err, ...args); + * this.destroy(err); + * } + * + * destroy(err) { + * // Tear the resource down here. + * } + * } + * ``` + * @since v13.4.0, v12.16.0 + */ + [EventEmitter.captureRejectionSymbol]?(error: Error, event: string | symbol, ...args: any[]): void; + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: EventNames, listener: Listener): this; + /** + * Synchronously calls each of the listeners registered for the event named + * `eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: EventNames, ...args: Args): boolean; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): (string | symbol)[]; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to + * `events.defaultMaxListeners`. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns the number of listeners listening for the event named `eventName`. + * If `listener` is provided, it will return how many times the listener is found + * in the list of the listeners of the event. + * @since v3.2.0 + * @param eventName The name of the event being listened for + * @param listener The event handler function + */ + listenerCount( + eventName: EventNames, + listener?: Listener, + ): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: EventNames): Listener[]; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: EventNames, listener: Listener): this; + /** + * Adds the `listener` function to the end of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName` + * and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The + * `emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: EventNames, listener: Listener): this; + /** + * Adds a **one-time** `listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The + * `emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: EventNames, listener: Listener): this; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName` + * and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: EventNames, listener: Listener): this; + /** + * Adds a **one-time** `listener` function for the event named `eventName` to the + * _beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener( + eventName: EventNames, + listener: Listener, + ): this; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: EventNames): Listener[]; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: EventNames): this; + /** + * Removes the specified `listener` from the listener array for the event named + * `eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any + * `removeListener()` or `removeAllListeners()` calls _after_ emitting and + * _before_ the last listener finishes execution will not remove them from + * `emit()` in progress. Subsequent events behave as expected. + * + * ```js + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indexes of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')` + * listener is removed: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: EventNames, listener: Listener): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to + * `Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + } + } + } + namespace EventEmitter { + export { EventEmitter, EventEmitterEventMap, EventEmitterOptions }; + } + namespace EventEmitter { + interface Abortable { + signal?: AbortSignal | undefined; + } + /** + * See how to write a custom [rejection handler](https://nodejs.org/docs/latest-v25.x/api/events.html#emittersymbolfornodejsrejectionerr-eventname-args). + * @since v13.4.0, v12.16.0 + */ + const captureRejectionSymbol: unique symbol; + /** + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 + */ + let captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_ `EventEmitter` instances, the `events.defaultMaxListeners` + * property can be used. If this value is not a positive number, a `RangeError` + * is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_ `EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single + * `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` + * methods can be used to temporarily avoid this warning: + * + * `defaultMaxListeners` has no effect on `AbortSignal` instances. While it is + * still possible to use `emitter.setMaxListeners(n)` to set a warning limit + * for individual `AbortSignal` instances, per default `AbortSignal` instances will not warn. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ + let defaultMaxListeners: number; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` + * events. Listeners installed using this symbol are called before the regular + * `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an + * `'error'` event is emitted. Therefore, the process will still crash if no + * regular `'error'` listener is installed. + * @since v13.6.0, v12.17.0 + */ + const errorMonitor: unique symbol; + /** + * Listens once to the `abort` event on the provided `signal`. + * + * Listening to the `abort` event on abort signals is unsafe and may + * lead to resource leaks since another third party with the signal can + * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change + * this since it would violate the web standard. Additionally, the original + * API makes it easy to forget to remove listeners. + * + * This API allows safely using `AbortSignal`s in Node.js APIs by solving these + * two issues by listening to the event such that `stopImmediatePropagation` does + * not prevent the listener from running. + * + * Returns a disposable so that it may be unsubscribed from more easily. + * + * ```js + * import { addAbortListener } from 'node:events'; + * + * function example(signal) { + * let disposable; + * try { + * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); + * disposable = addAbortListener(signal, (e) => { + * // Do something when signal is aborted. + * }); + * } finally { + * disposable?.[Symbol.dispose](); + * } + * } + * ``` + * @since v20.5.0 + * @return Disposable that removes the `abort` listener. + */ + function addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * import { getEventListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + function getEventListeners(emitter: EventEmitter, name: string | symbol): ((...args: any[]) => void)[]; + function getEventListeners(emitter: EventTarget, name: string): ((...args: any[]) => void)[]; + /** + * Returns the currently set max amount of listeners. + * + * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the max event listeners for the + * event target. If the number of event handlers on a single EventTarget exceeds + * the max set, the EventTarget will print a warning. + * + * ```js + * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * console.log(getMaxListeners(ee)); // 10 + * setMaxListeners(11, ee); + * console.log(getMaxListeners(ee)); // 11 + * } + * { + * const et = new EventTarget(); + * console.log(getMaxListeners(et)); // 10 + * setMaxListeners(11, et); + * console.log(getMaxListeners(et)); // 11 + * } + * ``` + * @since v19.9.0 + */ + function getMaxListeners(emitter: EventEmitter | EventTarget): number; + /** + * Returns the number of registered listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listenerCount` + * on the emitter. + * + * For `EventTarget`s this is the only way to obtain the listener count. This can + * be useful for debugging and diagnostic purposes. + * @since v0.9.12 + */ + function listenerCount(emitter: EventEmitter, eventName: string | symbol): number; + function listenerCount(emitter: EventTarget, eventName: string): number; + interface OnOptions extends Abortable { + /** + * Names of events that will end the iteration. + */ + close?: readonly string[] | undefined; + /** + * The high watermark. The emitter is paused every time the size of events + * being buffered is higher than it. Supported only on emitters implementing + * `pause()` and `resume()` methods. + * @default Number.MAX_SAFE_INTEGER + */ + highWaterMark?: number | undefined; + /** + * The low watermark. The emitter is resumed every time the size of events + * being buffered is lower than it. Supported only on emitters implementing + * `pause()` and `resume()` methods. + * @default 1 + */ + lowWaterMark?: number | undefined; + } + /** + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * @since v13.6.0, v12.16.0 + * @returns `AsyncIterator` that iterates `eventName` events emitted by the `emitter` + */ + function on( + emitter: EventEmitter, + eventName: string | symbol, + options?: OnOptions, + ): NodeJS.AsyncIterator; + function on( + emitter: EventTarget, + eventName: string, + options?: OnOptions, + ): NodeJS.AsyncIterator; + interface OnceOptions extends Abortable {} + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform + * [EventTarget][WHATWG-EventTarget] interface, which has no special + * `'error'` event semantics and does not listen to the `'error'` event. + * + * ```js + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('error happened', err); + * } + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()` + * is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.error('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + function once( + emitter: EventEmitter, + eventName: string | symbol, + options?: OnceOptions, + ): Promise; + function once(emitter: EventTarget, eventName: string, options?: OnceOptions): Promise; + /** + * ```js + * import { setMaxListeners, EventEmitter } from 'node:events'; + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventTargets Zero or more `EventTarget` + * or `EventEmitter` instances. If none are specified, `n` is set as the default + * max for all newly created `EventTarget` and `EventEmitter` objects. + * objects. + */ + function setMaxListeners(n: number, ...eventTargets: ReadonlyArray): void; + /** + * This is the interface from which event-emitting Node.js APIs inherit in the types package. + * **It is not intended for consumer use.** + * + * It provides event-mapped definitions similar to EventEmitter, except that its signatures + * are deliberately permissive: they provide type _hinting_, but not rigid type-checking, + * for compatibility reasons. + * + * Classes that inherit directly from EventEmitter in JavaScript can inherit directly from + * this interface in the type definitions. Classes that are more than one inheritance level + * away from EventEmitter (eg. `net.Socket` > `stream.Duplex` > `EventEmitter`) must instead + * copy these method definitions into the derived class. Search "#region InternalEventEmitter" + * for examples. + * @internal + */ + interface InternalEventEmitter> extends EventEmitter { + addListener(eventName: E, listener: (...args: T[E]) => void): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: T[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount(eventName: E, listener?: (...args: T[E]) => void): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: T[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: T[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: T[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: E, listener: (...args: T[E]) => void): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener(eventName: E, listener: (...args: T[E]) => void): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(eventName: E, listener: (...args: T[E]) => void): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: T[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener(eventName: E, listener: (...args: T[E]) => void): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + interface EventEmitterReferencingAsyncResource extends AsyncResource { + readonly eventEmitter: EventEmitterAsyncResource; + } + interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { + /** + * The type of async event. + * @default new.target.name + */ + name?: string | undefined; + } + /** + * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that + * require manual async tracking. Specifically, all events emitted by instances + * of `events.EventEmitterAsyncResource` will run within its [async context](https://nodejs.org/docs/latest-v25.x/api/async_context.html). + * + * ```js + * import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; + * import { notStrictEqual, strictEqual } from 'node:assert'; + * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; + * + * // Async tracking tooling will identify this as 'Q'. + * const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); + * + * // 'foo' listeners will run in the EventEmitters async context. + * ee1.on('foo', () => { + * strictEqual(executionAsyncId(), ee1.asyncId); + * strictEqual(triggerAsyncId(), ee1.triggerAsyncId); + * }); + * + * const ee2 = new EventEmitter(); + * + * // 'foo' listeners on ordinary EventEmitters that do not track async + * // context, however, run in the same async context as the emit(). + * ee2.on('foo', () => { + * notStrictEqual(executionAsyncId(), ee2.asyncId); + * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); + * }); + * + * Promise.resolve().then(() => { + * ee1.emit('foo'); + * ee2.emit('foo'); + * }); + * ``` + * + * The `EventEmitterAsyncResource` class has the same methods and takes the + * same options as `EventEmitter` and `AsyncResource` themselves. + * @since v17.4.0, v16.14.0 + */ + class EventEmitterAsyncResource extends EventEmitter { + constructor(options?: EventEmitterAsyncResourceOptions); + /** + * The unique `asyncId` assigned to the resource. + */ + readonly asyncId: number; + /** + * The returned `AsyncResource` object has an additional `eventEmitter` property + * that provides a reference to this `EventEmitterAsyncResource`. + */ + readonly asyncResource: EventEmitterReferencingAsyncResource; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + */ + emitDestroy(): void; + /** + * The same `triggerAsyncId` that is passed to the + * `AsyncResource` constructor. + */ + readonly triggerAsyncId: number; + } + /** + * The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` + * that emulates a subset of the `EventEmitter` API. + * @since v14.5.0 + */ + interface NodeEventTarget extends EventTarget { + /** + * Node.js-specific extension to the `EventTarget` class that emulates the + * equivalent `EventEmitter` API. The only difference between `addListener()` and + * `addEventListener()` is that `addListener()` will return a reference to the + * `EventTarget`. + * @since v14.5.0 + */ + addListener(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that dispatches the + * `arg` to the list of handlers for `type`. + * @since v15.2.0 + * @returns `true` if event listeners registered for the `type` exist, + * otherwise `false`. + */ + emit(type: string, arg: any): boolean; + /** + * Node.js-specific extension to the `EventTarget` class that returns an array + * of event `type` names for which event listeners are registered. + * @since 14.5.0 + */ + eventNames(): string[]; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of event listeners registered for the `type`. + * @since v14.5.0 + */ + listenerCount(type: string): number; + /** + * Node.js-specific extension to the `EventTarget` class that sets the number + * of max event listeners as `n`. + * @since v14.5.0 + */ + setMaxListeners(n: number): void; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of max event listeners. + * @since v14.5.0 + */ + getMaxListeners(): number; + /** + * Node.js-specific alias for `eventTarget.removeEventListener()`. + * @since v14.5.0 + */ + off(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + /** + * Node.js-specific alias for `eventTarget.addEventListener()`. + * @since v14.5.0 + */ + on(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that adds a `once` + * listener for the given event `type`. This is equivalent to calling `on` + * with the `once` option set to `true`. + * @since v14.5.0 + */ + once(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class. If `type` is specified, + * removes all registered listeners for `type`, otherwise removes all registered + * listeners. + * @since v14.5.0 + */ + removeAllListeners(type?: string): this; + /** + * Node.js-specific extension to the `EventTarget` class that removes the + * `listener` for the given `type`. The only difference between `removeListener()` + * and `removeEventListener()` is that `removeListener()` will return a reference + * to the `EventTarget`. + * @since v14.5.0 + */ + removeListener(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + } + /** @internal */ + type InternalEventTargetEventProperties = { + [K in keyof T & string as `on${K}`]: ((ev: T[K]) => void) | null; + }; + } + export = EventEmitter; +} +declare module "events" { + import events = require("node:events"); + export = events; +} diff --git a/node_modules/@types/node/fs.d.ts b/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000..b74033c --- /dev/null +++ b/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4658 @@ +declare module "node:fs" { + import { NonSharedBuffer } from "node:buffer"; + import { Abortable, EventEmitter, InternalEventEmitter } from "node:events"; + import { FileHandle } from "node:fs/promises"; + import * as stream from "node:stream"; + import { URL } from "node:url"; + /** + * Valid types for path values in "fs". + */ + type PathLike = string | Buffer | URL; + type PathOrFileDescriptor = PathLike | number; + type TimeLike = string | number | Date; + type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; + interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + type OpenMode = number | string; + type Mode = number | string; + interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + class Stats { + private constructor(); + } + interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + class StatsFs {} + interface BigIntStatsFs extends StatsFsBase {} + interface StatFsOptions { + bigint?: boolean | undefined; + } + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: Name; + /** + * The path to the parent directory of the file this `fs.Dirent` object refers to. + * @since v20.12.0, v18.20.0 + */ + parentPath: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be fulfilled after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null` if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + /** + * Calls `dir.close()` if the directory handle is open, and returns a promise that + * fulfills when disposal is complete. + * @since v24.1.0 + */ + [Symbol.asyncDispose](): Promise; + /** + * Calls `dir.closeSync()` if the directory handle is open, and returns + * `undefined`. + * @since v24.1.0 + */ + [Symbol.dispose](): void; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + interface FSWatcherEventMap { + "change": [eventType: string, filename: string | NonSharedBuffer]; + "close": []; + "error": [error: Error]; + } + interface FSWatcher extends InternalEventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.FSWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.FSWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + interface ReadStreamEventMap extends stream.ReadableEventMap { + "close": []; + "data": [chunk: string | NonSharedBuffer]; + "open": [fd: number]; + "ready": []; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ReadStreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ReadStreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ReadStreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: ReadStreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: ReadStreamEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: ReadStreamEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ReadStreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ReadStreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ReadStreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: ReadStreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ReadStreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface Utf8StreamOptions { + /** + * Appends writes to dest file instead of truncating it. + * @default true + */ + append?: boolean | undefined; + /** + * Which type of data you can send to the write + * function, supported values are `'utf8'` or `'buffer'`. + * @default 'utf8' + */ + contentMode?: "utf8" | "buffer" | undefined; + /** + * A path to a file to be written to (mode controlled by the + * append option). + */ + dest?: string | undefined; + /** + * A file descriptor, something that is returned by `fs.open()` + * or `fs.openSync()`. + */ + fd?: number | undefined; + /** + * An object that has the same API as the `fs` module, useful + * for mocking, testing, or customizing the behavior of the stream. + */ + fs?: object | undefined; + /** + * Perform a `fs.fsyncSync()` every time a write is + * completed. + */ + fsync?: boolean | undefined; + /** + * The maximum length of the internal buffer. If a write + * operation would cause the buffer to exceed `maxLength`, the data written is + * dropped and a drop event is emitted with the dropped data + */ + maxLength?: number | undefined; + /** + * The maximum number of bytes that can be written; + * @default 16384 + */ + maxWrite?: number | undefined; + /** + * The minimum length of the internal buffer that is + * required to be full before flushing. + */ + minLength?: number | undefined; + /** + * Ensure directory for `dest` file exists when true. + * @default false + */ + mkdir?: boolean | undefined; + /** + * Specify the creating file mode (see `fs.open()`). + */ + mode?: number | string | undefined; + /** + * Calls flush every `periodicFlush` milliseconds. + */ + periodicFlush?: number | undefined; + /** + * A function that will be called when `write()`, + * `writeSync()`, or `flushSync()` encounters an `EAGAIN` or `EBUSY` error. + * If the return value is `true` the operation will be retried, otherwise it + * will bubble the error. The `err` is the error that caused this function to + * be called, `writeBufferLen` is the length of the buffer that was written, + * and `remainingBufferLen` is the length of the remaining buffer that the + * stream did not try to write. + */ + retryEAGAIN?: ((err: Error | null, writeBufferLen: number, remainingBufferLen: number) => boolean) | undefined; + /** + * Perform writes synchronously. + */ + sync?: boolean | undefined; + } + interface Utf8StreamEventMap { + "close": []; + "drain": []; + "drop": [data: string | Buffer]; + "error": [error: Error]; + "finish": []; + "ready": []; + "write": [n: number]; + } + /** + * An optimized UTF-8 stream writer that allows for flushing all the internal + * buffering on demand. It handles `EAGAIN` errors correctly, allowing for + * customization, for example, by dropping content if the disk is busy. + * @since v24.6.0 + * @experimental + */ + class Utf8Stream implements EventEmitter { + constructor(options: Utf8StreamOptions); + /** + * Whether the stream is appending to the file or truncating it. + */ + readonly append: boolean; + /** + * The type of data that can be written to the stream. Supported + * values are `'utf8'` or `'buffer'`. + * @default 'utf8' + */ + readonly contentMode: "utf8" | "buffer"; + /** + * Close the stream immediately, without flushing the internal buffer. + */ + destroy(): void; + /** + * Close the stream gracefully, flushing the internal buffer before closing. + */ + end(): void; + /** + * The file descriptor that is being written to. + */ + readonly fd: number; + /** + * The file that is being written to. + */ + readonly file: string; + /** + * Writes the current buffer to the file if a write was not in progress. Do + * nothing if `minLength` is zero or if it is already writing. + */ + flush(callback: (err: Error | null) => void): void; + /** + * Flushes the buffered data synchronously. This is a costly operation. + */ + flushSync(): void; + /** + * Whether the stream is performing a `fs.fsyncSync()` after every + * write operation. + */ + readonly fsync: boolean; + /** + * The maximum length of the internal buffer. If a write + * operation would cause the buffer to exceed `maxLength`, the data written is + * dropped and a drop event is emitted with the dropped data. + */ + readonly maxLength: number; + /** + * The minimum length of the internal buffer that is required to be + * full before flushing. + */ + readonly minLength: number; + /** + * Whether the stream should ensure that the directory for the + * `dest` file exists. If `true`, it will create the directory if it does not + * exist. + * @default false + */ + readonly mkdir: boolean; + /** + * The mode of the file that is being written to. + */ + readonly mode: number | string; + /** + * The number of milliseconds between flushes. If set to `0`, no + * periodic flushes will be performed. + */ + readonly periodicFlush: number; + /** + * Reopen the file in place, useful for log rotation. + * @param file A path to a file to be written to (mode + * controlled by the append option). + */ + reopen(file: PathLike): void; + /** + * Whether the stream is writing synchronously or asynchronously. + */ + readonly sync: boolean; + /** + * When the `options.contentMode` is set to `'utf8'` when the stream is created, + * the `data` argument must be a string. If the `contentMode` is set to `'buffer'`, + * the `data` argument must be a `Buffer`. + * @param data The data to write. + */ + write(data: string | Buffer): boolean; + /** + * Whether the stream is currently writing data to the file. + */ + readonly writing: boolean; + /** + * Calls `utf8Stream.destroy()`. + */ + [Symbol.dispose](): void; + } + interface Utf8Stream extends InternalEventEmitter {} + interface WriteStreamEventMap extends stream.WritableEventMap { + "close": []; + "open": [fd: number]; + "ready": []; + } + /** + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: WriteStreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: WriteStreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: WriteStreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: WriteStreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'node:fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + function truncate(path: PathLike, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function truncate(path: PathLike, callback: NoParamCallback): void; + namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + function truncateSync(path: PathLike, len?: number): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + function ftruncate(fd: number, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + function ftruncate(fd: number, callback: NoParamCallback): void; + namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + function ftruncateSync(fd: number, len?: number): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'node:fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'node:fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, + ): void; + function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, + ): void; + function statfs( + path: PathLike, + options: StatFsOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, + ): void; + namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): StatsFs; + function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): BigIntStatsFs; + function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. + * + * Relative targets are relative to the link's parent directory. + * + * ```js + * import { symlink } from 'node:fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + * @param [type='null'] + */ + function symlink( + target: PathLike, + path: PathLike, + type: symlink.Type | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = "dir" | "file" | "junction"; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + * @param [type='null'] + */ + function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: NonSharedBuffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readlink( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: NonSharedBuffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + function native( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: NonSharedBuffer) => void, + ): void; + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | NonSharedBuffer) => void, + ): void; + function native( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + function native(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + function unlink(path: PathLike, callback: NoParamCallback): void; + namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + function unlinkSync(path: PathLike): void; + /** @deprecated `rmdir()` no longer provides any options. This interface will be removed in a future version. */ + // TODO: remove in future major + interface RmDirOptions {} + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + function rmdir(path: PathLike, callback: NoParamCallback): void; + namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + function rmdirSync(path: PathLike): void; + interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + function rm(path: PathLike, callback: NoParamCallback): void; + function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. + * @since v14.14.0 + */ + function rmSync(path: PathLike, options?: RmOptions): void; + interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created (for instance, if it was previously created). + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. + * + * ```js + * import { mkdir } from 'node:fs'; + * + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'node:fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function mkdir(path: PathLike, callback: NoParamCallback): void; + namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`import { sep } from 'node:path'`). + * + * ```js + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'node:path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp( + prefix: string, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: EncodingOption): string | NonSharedBuffer; + interface DisposableTempDir extends Disposable { + /** + * The path of the created directory. + */ + path: string; + /** + * A function which removes the created directory. + */ + remove(): void; + /** + * The same as `remove`. + */ + [Symbol.dispose](): void; + } + /** + * Returns a disposable object whose `path` property holds the created directory + * path. When the object is disposed, the directory and its contents will be + * removed if it still exists. If the directory cannot be deleted, disposal will + * throw an error. The object has a `remove()` method which will perform the same + * task. + * + * + * + * For detailed information, see the documentation of `fs.mkdtemp()`. + * + * There is no callback-based version of this API because it is designed for use + * with the `using` syntax. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v24.4.0 + */ + function mkdtempDisposableSync(prefix: string, options?: EncodingOption): DisposableTempDir; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: NonSharedBuffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | NonSharedBuffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readdir( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | "buffer" + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function __promisify__( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): NonSharedBuffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | NonSharedBuffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function readdirSync( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + function close(fd: number, callback?: NoParamCallback): void; + namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + function open( + path: PathLike, + flags: OpenMode | undefined, + mode: Mode | undefined | null, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + function open( + path: PathLike, + flags: OpenMode | undefined, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + function fsync(fd: number, callback: NoParamCallback): void; + namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + function fsyncSync(fd: number): void; + interface WriteOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `buffer.byteLength - offset` + */ + length?: number | undefined; + /** + * @default null + */ + position?: number | null | undefined; + } + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + function write( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + fd: number, + buffer: TBuffer, + options: WriteOptions, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + function write( + fd: number, + string: string, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + options?: WriteOptions, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + * @return The number of bytes written. + */ + function writeSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + type ReadPosition = number | bigint; + interface ReadOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + interface ReadOptionsWithBuffer extends ReadOptions { + buffer?: T | undefined; + } + /** @deprecated Use `ReadOptions` instead. */ + // TODO: remove in future major + interface ReadSyncOptions extends ReadOptions {} + /** @deprecated Use `ReadOptionsWithBuffer` instead. */ + // TODO: remove in future major + interface ReadAsyncOptions extends ReadOptionsWithBuffer {} + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + function read( + fd: number, + options: ReadOptionsWithBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + function read( + fd: number, + buffer: TBuffer, + options: ReadOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + function read( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NonSharedBuffer) => void, + ): void; + namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadOptionsWithBuffer, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NonSharedBuffer; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + * @param [position='null'] + */ + function readSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: ReadPosition | null, + ): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): NonSharedBuffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | NonSharedBuffer; + type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | undefined; + flush?: boolean | undefined; + } + ) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'node:fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + function writeFile( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function writeFile( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + callback: NoParamCallback, + ): void; + namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + function writeFileSync( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'node:fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: StatsListener, + ): StatWatcher; + function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: BigIntStatsListener, + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + function unwatchFile(filename: PathLike, listener?: StatsListener): void; + function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + type WatchIgnorePredicate = string | RegExp | ((filename: string) => boolean); + interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer" | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + ignore?: WatchIgnorePredicate | readonly WatchIgnorePredicate[] | undefined; + } + interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + type WatchEventType = "rename" | "change"; + type WatchListener = (event: WatchEventType, filename: T | null) => void; + type StatsListener = (curr: Stats, prev: Stats) => void; + type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + listener: WatchListener, + ): FSWatcher; + function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer" | null, + listener: WatchListener, + ): FSWatcher; + function watch(filename: PathLike, listener: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'node:fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won't be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'node:fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + function existsSync(path: PathLike): boolean; + namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'node:fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + function access(path: PathLike, callback: NoParamCallback): void; + namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'node:fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + signal?: AbortSignal | null | undefined; + highWaterMark?: number | undefined; + } + interface FSImplementation { + open?: (...args: any[]) => any; + close?: (...args: any[]) => any; + } + interface CreateReadStreamFSImplementation extends FSImplementation { + read: (...args: any[]) => any; + } + interface CreateWriteStreamFSImplementation extends FSImplementation { + write: (...args: any[]) => any; + writev?: (...args: any[]) => any; + } + interface ReadStreamOptions extends StreamOptions { + fs?: CreateReadStreamFSImplementation | null | undefined; + end?: number | undefined; + } + interface WriteStreamOptions extends StreamOptions { + fs?: CreateWriteStreamFSImplementation | null | undefined; + flush?: boolean | undefined; + } + /** + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + function fdatasync(fd: number, callback: NoParamCallback): void; + namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'node:fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'node:fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] + */ + function writev( + fd: number, + buffers: TBuffers, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: TBuffers) => void, + ): void; + function writev( + fd: number, + buffers: TBuffers, + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: TBuffers) => void, + ): void; + // Providing a default type parameter doesn't provide true BC for userland consumers, but at least suppresses TS2314 + // TODO: remove default in future major version + interface WriteVResult { + bytesWritten: number; + buffers: T; + } + namespace writev { + function __promisify__( + fd: number, + buffers: TBuffers, + position?: number, + ): Promise>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @param [position='null'] + * @return The number of bytes written. + */ + function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + */ + function readv( + fd: number, + buffers: TBuffers, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: TBuffers) => void, + ): void; + function readv( + fd: number, + buffers: TBuffers, + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: TBuffers) => void, + ): void; + // Providing a default type parameter doesn't provide true BC for userland consumers, but at least suppresses TS2314 + // TODO: remove default in future major version + interface ReadVResult { + bytesRead: number; + buffers: T; + } + namespace readv { + function __promisify__( + fd: number, + buffers: TBuffers, + position?: number, + ): Promise>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + * @return The number of bytes read. + */ + function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + + interface OpenAsBlobOptions { + /** + * An optional mime type for the blob. + * + * @default 'undefined' + */ + type?: string | undefined; + } + + /** + * Returns a `Blob` whose data is backed by the given file. + * + * The file must not be modified after the `Blob` is created. Any modifications + * will cause reading the `Blob` data to fail with a `DOMException` error. + * Synchronous stat operations on the file when the `Blob` is created, and before + * each read in order to detect whether the file data has been modified on disk. + * + * ```js + * import { openAsBlob } from 'node:fs'; + * + * const blob = await openAsBlob('the.file.txt'); + * const ab = await blob.arrayBuffer(); + * blob.stream(); + * ``` + * @since v19.8.0 + */ + function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; + + interface OpenDirOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean | undefined; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + function opendir( + path: PathLike, + options: OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, + ): void; + namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + interface BigIntOptions { + bigint: true; + } + interface StatOptions { + bigint?: boolean | undefined; + } + interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean | undefined; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean | undefined; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean | undefined; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number | undefined; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean | undefined; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean | undefined; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean | undefined; + } + interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?: ((source: string, destination: string) => boolean | Promise) | undefined; + } + interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?: ((source: string, destination: string) => boolean) | undefined; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + function cp( + source: string | URL, + destination: string | URL, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + function cp( + source: string | URL, + destination: string | URL, + opts: CopyOptions, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; + + // TODO: collapse + interface _GlobOptions { + /** + * Current working directory. + * @default process.cwd() + */ + cwd?: string | URL | undefined; + /** + * `true` if the glob should return paths as `Dirent`s, `false` otherwise. + * @default false + * @since v22.2.0 + */ + withFileTypes?: boolean | undefined; + /** + * Function to filter out files/directories or a + * list of glob patterns to be excluded. If a function is provided, return + * `true` to exclude the item, `false` to include it. + * If a string array is provided, each string should be a glob pattern that + * specifies paths to exclude. Note: Negation patterns (e.g., '!foo.js') are + * not supported. + * @default undefined + */ + exclude?: ((fileName: T) => boolean) | readonly string[] | undefined; + } + interface GlobOptions extends _GlobOptions {} + interface GlobOptionsWithFileTypes extends _GlobOptions { + withFileTypes: true; + } + interface GlobOptionsWithoutFileTypes extends _GlobOptions { + withFileTypes?: false | undefined; + } + + /** + * Retrieves the files matching the specified pattern. + * + * ```js + * import { glob } from 'node:fs'; + * + * glob('*.js', (err, matches) => { + * if (err) throw err; + * console.log(matches); + * }); + * ``` + * @since v22.0.0 + */ + function glob( + pattern: string | readonly string[], + callback: (err: NodeJS.ErrnoException | null, matches: string[]) => void, + ): void; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[], + ) => void, + ): void; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: string[], + ) => void, + ): void; + function glob( + pattern: string | readonly string[], + options: GlobOptions, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[] | string[], + ) => void, + ): void; + /** + * ```js + * import { globSync } from 'node:fs'; + * + * console.log(globSync('*.js')); + * ``` + * @since v22.0.0 + * @returns paths of files that match the pattern. + */ + function globSync(pattern: string | readonly string[]): string[]; + function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): Dirent[]; + function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): string[]; + function globSync( + pattern: string | readonly string[], + options: GlobOptions, + ): Dirent[] | string[]; +} +declare module "node:fs" { + export * as promises from "node:fs/promises"; +} +declare module "fs" { + export * from "node:fs"; +} diff --git a/node_modules/@types/node/fs/promises.d.ts b/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000..419112a --- /dev/null +++ b/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1319 @@ +declare module "node:fs/promises" { + import { NonSharedBuffer } from "node:buffer"; + import { Abortable } from "node:events"; + import { Interface as ReadlineInterface } from "node:readline"; + import { + BigIntStats, + BigIntStatsFs, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + EncodingOption, + GlobOptions, + GlobOptionsWithFileTypes, + GlobOptionsWithoutFileTypes, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadOptions, + ReadOptionsWithBuffer, + ReadPosition, + ReadStream, + ReadVResult, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + WatchOptions as _WatchOptions, + WriteStream, + WriteVResult, + } from "node:fs"; + import { Stream } from "node:stream"; + import { ReadableStream } from "node:stream/web"; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T | null; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + /** @deprecated This interface will be removed in a future version. Use `import { ReadOptionsWithBuffer } from "node:fs"` instead. */ + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: ReadPosition | null; + } + interface CreateReadStreamOptions extends Abortable { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + flush?: boolean | undefined; + } + interface ReadableWebStreamOptions { + autoClose?: boolean | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read( + buffer: T, + offset?: number | null, + length?: number | null, + position?: ReadPosition | null, + ): Promise>; + read( + buffer: T, + options?: ReadOptions, + ): Promise>; + read( + options?: ReadOptionsWithBuffer, + ): Promise>; + /** + * Returns a byte-oriented `ReadableStream` that may be used to read the file's + * contents. + * + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. + * + * ```js + * import { + * open, + * } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. + * @since v17.0.0 + */ + readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: + | ({ encoding?: null | undefined } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options: + | ({ encoding: BufferEncoding } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * @since v18.11.0 + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + }, + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is fulfilled with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is fulfilled with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param offset The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + buffer: TBuffer, + options?: { offset?: number; length?: number; position?: number }, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is fulfilled with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be fulfilled (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev( + buffers: TBuffers, + position?: number, + ): Promise>; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv( + buffers: TBuffers, + position?: number, + ): Promise>; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + /** + * Calls `filehandle.close()` and returns a promise that fulfills when the + * filehandle is closed. + * @since v20.4.0, v18.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + const constants: typeof fsConstants; + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is fulfilled with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access, constants } from 'node:fs/promises'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { copyFile, constants } from 'node:fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len` bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'node:fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a directory. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * fulfilled with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink( + path: PathLike, + options?: ObjectEncodingOptions | string | null, + ): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. Junction points on NTFS volumes + * can only point to directories. + * @since v10.0.0 + * @param [type='null'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + }, + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * try { + * await mkdtemp(join(tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing + * platform-specific path separator + * (`import { sep } from 'node:path'`). + * @since v10.0.0 + * @return Fulfills with a string containing the file system path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp( + prefix: string, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + interface DisposableTempDir extends AsyncDisposable { + /** + * The path of the created directory. + */ + path: string; + /** + * A function which removes the created directory. + */ + remove(): Promise; + /** + * The same as `remove`. + */ + [Symbol.asyncDispose](): Promise; + } + /** + * The resulting Promise holds an async-disposable object whose `path` property + * holds the created directory path. When the object is disposed, the directory + * and its contents will be removed asynchronously if it still exists. If the + * directory cannot be deleted, disposal will throw an error. The object has an + * async `remove()` method which will perform the same task. + * + * Both this function and the disposal function on the resulting object are + * async, so it should be used with `await` + `await using` as in + * `await using dir = await fsPromises.mkdtempDisposable('prefix')`. + * + * + * + * For detailed information, see the documentation of `fsPromises.mkdtemp()`. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v24.4.0 + */ + function mkdtempDisposable(prefix: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + /** + * If all data is successfully written to the file, and `flush` + * is `true`, `filehandle.sync()` is used to flush the data. + * @default false + */ + flush?: boolean | undefined; + } & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathLike | FileHandle, + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + interface WatchOptions extends _WatchOptions { + maxQueue?: number | undefined; + overflow?: "ignore" | "throw" | undefined; + } + interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * import { watch } from 'node:fs/promises'; + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding, + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; + /** + * ```js + * import { glob } from 'node:fs/promises'; + * + * for await (const entry of glob('*.js')) + * console.log(entry); + * ``` + * @since v22.0.0 + * @returns An AsyncIterator that yields the paths of files + * that match the pattern. + */ + function glob(pattern: string | readonly string[]): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptions, + ): NodeJS.AsyncIterator; +} +declare module "fs/promises" { + export * from "node:fs/promises"; +} diff --git a/node_modules/@types/node/globals.d.ts b/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000..36e7f90 --- /dev/null +++ b/node_modules/@types/node/globals.d.ts @@ -0,0 +1,150 @@ +declare var global: typeof globalThis; + +declare var process: NodeJS.Process; + +interface ErrorConstructor { + /** + * Creates a `.stack` property on `targetObject`, which when accessed returns + * a string representing the location in the code at which + * `Error.captureStackTrace()` was called. + * + * ```js + * const myObject = {}; + * Error.captureStackTrace(myObject); + * myObject.stack; // Similar to `new Error().stack` + * ``` + * + * The first line of the trace will be prefixed with + * `${myObject.name}: ${myObject.message}`. + * + * The optional `constructorOpt` argument accepts a function. If given, all frames + * above `constructorOpt`, including `constructorOpt`, will be omitted from the + * generated stack trace. + * + * The `constructorOpt` argument is useful for hiding implementation + * details of error generation from the user. For instance: + * + * ```js + * function a() { + * b(); + * } + * + * function b() { + * c(); + * } + * + * function c() { + * // Create an error without stack trace to avoid calculating the stack trace twice. + * const { stackTraceLimit } = Error; + * Error.stackTraceLimit = 0; + * const error = new Error(); + * Error.stackTraceLimit = stackTraceLimit; + * + * // Capture the stack trace above function b + * Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace + * throw error; + * } + * + * a(); + * ``` + */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + /** + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any; + /** + * The `Error.stackTraceLimit` property specifies the number of stack frames + * collected by a stack trace (whether generated by `new Error().stack` or + * `Error.captureStackTrace(obj)`). + * + * The default value is `10` but may be set to any valid JavaScript number. Changes + * will affect any stack trace captured _after_ the value has been changed. + * + * If set to a non-number value, or set to a negative number, stack traces will + * not capture any frames. + */ + stackTraceLimit: number; +} + +/** + * Enable this API with the `--expose-gc` CLI flag. + */ +declare var gc: NodeJS.GCFunction | undefined; + +declare namespace NodeJS { + interface CallSite { + getColumnNumber(): number | null; + getEnclosingColumnNumber(): number | null; + getEnclosingLineNumber(): number | null; + getEvalOrigin(): string | undefined; + getFileName(): string | null; + getFunction(): Function | undefined; + getFunctionName(): string | null; + getLineNumber(): number | null; + getMethodName(): string | null; + getPosition(): number; + getPromiseIndex(): number | null; + getScriptHash(): string; + getScriptNameOrSourceURL(): string | null; + getThis(): unknown; + getTypeName(): string | null; + isAsync(): boolean; + isConstructor(): boolean; + isEval(): boolean; + isNative(): boolean; + isPromiseAll(): boolean; + isToplevel(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface RefCounted { + ref(): this; + unref(): this; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + + type PartialOptions = { [K in keyof T]?: T[K] | undefined }; + + interface GCFunction { + (minor?: boolean): void; + (options: NodeJS.GCOptions & { execution: "async" }): Promise; + (options: NodeJS.GCOptions): void; + } + + interface GCOptions { + execution?: "sync" | "async" | undefined; + flavor?: "regular" | "last-resort" | undefined; + type?: "major-snapshot" | "major" | "minor" | undefined; + filename?: string | undefined; + } + + /** An iterable iterator returned by the Node.js API. */ + interface Iterator extends IteratorObject { + [Symbol.iterator](): NodeJS.Iterator; + } + + /** An async iterable iterator returned by the Node.js API. */ + interface AsyncIterator extends AsyncIteratorObject { + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } + + /** The [`BufferSource`](https://webidl.spec.whatwg.org/#BufferSource) type from the Web IDL specification. */ + type BufferSource = NonSharedArrayBufferView | ArrayBuffer; + + /** The [`AllowSharedBufferSource`](https://webidl.spec.whatwg.org/#AllowSharedBufferSource) type from the Web IDL specification. */ + type AllowSharedBufferSource = ArrayBufferView | ArrayBufferLike; +} diff --git a/node_modules/@types/node/globals.typedarray.d.ts b/node_modules/@types/node/globals.typedarray.d.ts new file mode 100644 index 0000000..e69dd0c --- /dev/null +++ b/node_modules/@types/node/globals.typedarray.d.ts @@ -0,0 +1,101 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float16Array + | Float32Array + | Float64Array; + type ArrayBufferView = + | TypedArray + | DataView; + + // The following aliases are required to allow use of non-shared ArrayBufferViews in @types/node + // while maintaining compatibility with TS <=5.6. + // TODO: remove once @types/node no longer supports TS 5.6, and replace with native types. + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedUint8Array = Uint8Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedUint8ClampedArray = Uint8ClampedArray; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedUint16Array = Uint16Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedUint32Array = Uint32Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedInt8Array = Int8Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedInt16Array = Int16Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedInt32Array = Int32Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBigUint64Array = BigUint64Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBigInt64Array = BigInt64Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedFloat16Array = Float16Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedFloat32Array = Float32Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedFloat64Array = Float64Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedDataView = DataView; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedTypedArray = TypedArray; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedArrayBufferView = ArrayBufferView; + } +} diff --git a/node_modules/@types/node/http.d.ts b/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000..c2e00e7 --- /dev/null +++ b/node_modules/@types/node/http.d.ts @@ -0,0 +1,2147 @@ +declare module "node:http" { + import { NonSharedBuffer } from "node:buffer"; + import { LookupOptions } from "node:dns"; + import { EventEmitter } from "node:events"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import { URL } from "node:url"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + "accept-encoding"?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-fetch-site"?: string | undefined; + "sec-fetch-mode"?: string | undefined; + "sec-fetch-user"?: string | undefined; + "sec-fetch-dest"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict { + accept?: string | string[] | undefined; + "accept-charset"?: string | string[] | undefined; + "accept-encoding"?: string | string[] | undefined; + "accept-language"?: string | string[] | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + "cdn-cache-control"?: string | undefined; + connection?: string | string[] | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | number | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-security-policy"?: string | undefined; + "content-security-policy-report-only"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | string[] | undefined; + dav?: string | string[] | undefined; + dnt?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-range"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + link?: string | string[] | undefined; + location?: string | undefined; + "max-forwards"?: string | undefined; + origin?: string | undefined; + pragma?: string | string[] | undefined; + "proxy-authenticate"?: string | string[] | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + "public-key-pins-report-only"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "referrer-policy"?: string | undefined; + refresh?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | string[] | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | string[] | undefined; + "sec-websocket-version"?: string | undefined; + server?: string | undefined; + "set-cookie"?: string | string[] | undefined; + "strict-transport-security"?: string | undefined; + te?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + "user-agent"?: string | undefined; + upgrade?: string | undefined; + "upgrade-insecure-requests"?: string | undefined; + vary?: string | undefined; + via?: string | string[] | undefined; + warning?: string | undefined; + "www-authenticate"?: string | string[] | undefined; + "x-content-type-options"?: string | undefined; + "x-dns-prefetch-control"?: string | undefined; + "x-frame-options"?: string | undefined; + "x-xss-protection"?: string | undefined; + } + interface ClientRequestArgs extends Pick { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + createConnection?: + | (( + options: ClientRequestArgs, + oncreate: (err: Error | null, socket: stream.Duplex) => void, + ) => stream.Duplex | null | undefined) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | readonly string[] | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: net.LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setDefaultHeaders?: boolean | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean | undefined; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean | undefined; + /** + * The number of milliseconds of inactivity a server needs to wait for additional incoming data, + * after it has finished writing the last response, before a socket will be destroyed. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * An additional buffer time added to the + * `server.keepAliveTimeout` to extend the internal socket timeout. + * @since 24.6.0 + * @default 1000 + */ + keepAliveTimeoutBuffer?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: number | undefined; + /** + * Sets the timeout value in milliseconds for receiving the complete HTTP headers from the client. + * See {@link Server.headersTimeout} for more information. + * @default 60000 + * @since 18.0.0 + */ + headersTimeout?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + /** + * Optionally overrides the value of `--max-http-header-size` for requests received by + * this server, i.e. the maximum length of request headers in bytes. + * @default 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it forces the server to respond with a 400 (Bad Request) status code + * to any HTTP/1.1 request message that lacks a Host header (as mandated by the specification). + * @default true + * @since 20.0.0 + */ + requireHostHeader?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + /** + * A callback which receives an + * incoming request and returns a boolean, to control which upgrade attempts + * should be accepted. Accepted upgrades will fire an `'upgrade'` event (or + * their sockets will be destroyed, if no listener is registered) while + * rejected upgrades will fire a `'request'` event like any non-upgrade + * request. + * @since v24.9.0 + * @default () => server.listenerCount('upgrade') > 0 + */ + shouldUpgradeCallback?: ((request: InstanceType) => boolean) | undefined; + /** + * If set to `true`, an error is thrown when writing to an HTTP response which does not have a body. + * @default false + * @since v18.17.0, v20.2.0 + */ + rejectNonStandardBodyWrites?: boolean | undefined; + /** + * If set to `true`, requests without `Content-Length` + * or `Transfer-Encoding` headers (indicating no body) will be initialized with an + * already-ended body stream, so they will never emit any stream events + * (like `'data'` or `'end'`). You can use `req.readableEnded` to detect this case. + * @since v25.1.0 + * @default false + */ + optimizeEmptyRequests?: boolean | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > = (request: InstanceType, response: InstanceType & { req: InstanceType }) => void; + interface ServerEventMap< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > extends net.ServerEventMap { + "checkContinue": Parameters>; + "checkExpectation": Parameters>; + "clientError": [exception: Error, socket: stream.Duplex]; + "connect": [request: InstanceType, socket: stream.Duplex, head: NonSharedBuffer]; + "connection": [socket: net.Socket]; + "dropRequest": [request: InstanceType, socket: stream.Duplex]; + "request": Parameters>; + "upgrade": [req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer]; + } + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > extends net.Server { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: (socket: net.Socket) => void): this; + setTimeout(callback: (socket: net.Socket) => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. + * + * This timeout value is combined with the + * `server.keepAliveTimeoutBuffer` option to determine the actual socket + * timeout, calculated as: + * socketTimeout = keepAliveTimeout + keepAliveTimeoutBuffer + * If the server receives new data before the keep-alive timeout has fired, it + * will reset the regular inactivity timeout, i.e., `server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the HTTP server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * An additional buffer time added to the + * `server.keepAliveTimeout` to extend the internal socket timeout. + * + * This buffer helps reduce connection reset (`ECONNRESET`) errors by increasing + * the socket timeout slightly beyond the advertised keep-alive timeout. + * + * This option applies only to new incoming connections. + * @since v24.6.0 + * @default 1000 + */ + keepAliveTimeoutBuffer: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ServerEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ServerEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: ServerEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: ServerEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface OutgoingMessageEventMap extends stream.WritableEventMap { + "prefinish": []; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + constructor(); + readonly req: Request; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Alias of `outgoingMessage.socket`. + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: net.Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: net.Socket | null; + /** + * Once a socket is associated with the message and is connected, `socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | readonly string[]): this; + /** + * Sets multiple header values for implicit headers. headers must be an instance of + * `Headers` or `Map`, if a header already exists in the to-be-sent headers, its + * value will be replaced. + * + * ```js + * const headers = new Headers({ foo: 'bar' }); + * outgoingMessage.setHeaders(headers); + * ``` + * + * or + * + * ```js + * const headers = new Map([['foo', 'bar']]); + * outgoingMessage.setHeaders(headers); + * ``` + * + * When headers have been set with `outgoingMessage.setHeaders()`, they will be + * merged with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * const headers = new Headers({ 'Content-Type': 'text/html' }); + * res.setHeaders(headers); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * @since v19.6.0, v18.15.0 + * @param name Header name + * @param value Header value + */ + setHeaders(headers: Headers | Map): this; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple + * times. + * + * If there were no previous values for the header, this is equivalent to calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | readonly string[]): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header field names in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Flushes the message headers. + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. + * @since v1.6.0 + */ + flushHeaders(): void; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: OutgoingMessageEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: OutgoingMessageEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: OutgoingMessageEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: OutgoingMessageEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length` header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; + constructor(req: Request); + assignSocket(socket: net.Socket): void; + detachSocket(socket: net.Socket): void; + /** + * Sends an HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on `Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics', + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }, earlyHintsCallback); + * ``` + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain', + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `Error` being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(callback?: () => void): void; + } + interface InformationEvent { + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + statusCode: number; + statusMessage: string; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + interface ClientRequestEventMap extends stream.WritableEventMap { + /** @deprecated Listen for the `'close'` event instead. */ + "abort": []; + "connect": [response: IncomingMessage, socket: net.Socket, head: NonSharedBuffer]; + "continue": []; + "information": [info: InformationEvent]; + "response": [response: IncomingMessage]; + "socket": [socket: net.Socket]; + "timeout": []; + "upgrade": [response: IncomingMessage, socket: net.Socket, head: NonSharedBuffer]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered. + * + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0, v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: net.Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ClientRequestEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ClientRequestEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: ClientRequestEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: ClientRequestEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface IncomingMessageEventMap extends stream.ReadableEventMap { + /** @deprecated Listen for `'close'` event instead. */ + "aborted": []; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers, and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the `IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: net.Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST', + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: net.Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: net.Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, `last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined: + * + * ```console + * $ node + * > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * URL { + * href: 'http://localhost/status?name=ryan', + * origin: 'http://localhost', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost', + * hostname: 'localhost', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * + * Ensure that you set `process.env.HOST` to the server's host name, or consider replacing this part entirely. If using `req.headers.host`, ensure proper + * validation is used, as clients may specify a custom `Host` header. + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: IncomingMessageEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: IncomingMessageEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: IncomingMessageEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: IncomingMessageEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface ProxyEnv extends NodeJS.ProcessEnv { + HTTP_PROXY?: string | undefined; + HTTPS_PROXY?: string | undefined; + NO_PROXY?: string | undefined; + http_proxy?: string | undefined; + https_proxy?: string | undefined; + no_proxy?: string | undefined; + } + interface AgentOptions extends NodeJS.PartialOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Milliseconds to subtract from + * the server-provided `keep-alive: timeout=...` hint when determining socket + * expiration time. This buffer helps ensure the agent closes the socket + * slightly before the server does, reducing the chance of sending a request + * on a socket that’s about to be closed by the server. + * @since v24.7.0 + * @default 1000 + */ + agentKeepAliveTimeoutBuffer?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: "fifo" | "lifo" | undefined; + /** + * Environment variables for proxy configuration. See + * [Built-in Proxy Support](https://nodejs.org/docs/latest-v25.x/api/http.html#built-in-proxy-support) for details. + * @since v24.5.0 + */ + proxyEnv?: ProxyEnv | undefined; + /** + * Default port to use when the port is not specified in requests. + * @since v24.5.0 + */ + defaultPort?: number | undefined; + /** + * The protocol to use for the agent. + * @since v24.5.0 + */ + protocol?: string | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the `keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false, // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * + * `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v25.x/api/net.html#socketconnectoptions-connectlistener) are also supported. + * + * To configure any of them, a custom {@link Agent} instance must be created. + * + * ```js + * import http from 'node:http'; + * const keepAliveAgent = new http.Agent({ keepAlive: true }); + * options.agent = keepAliveAgent; + * http.request(options, onResponseCallback) + * ``` + * @since v0.3.4 + */ + class Agent extends EventEmitter { + /** + * By default set to 256. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + /** + * Produces a socket/stream to be used for HTTP requests. + * + * By default, this function behaves identically to `net.createConnection()`, + * synchronously returning the created socket. The optional `callback` parameter in the + * signature is **not** used by this default implementation. + * + * However, custom agents may override this method to provide greater flexibility, + * for example, to create sockets asynchronously. When overriding `createConnection`: + * + * 1. **Synchronous socket creation**: The overriding method can return the + * socket/stream directly. + * 2. **Asynchronous socket creation**: The overriding method can accept the `callback` + * and pass the created socket/stream to it (e.g., `callback(null, newSocket)`). + * If an error occurs during socket creation, it should be passed as the first + * argument to the `callback` (e.g., `callback(err)`). + * + * The agent will call the provided `createConnection` function with `options` and + * this internal `callback`. The `callback` provided by the agent has a signature + * of `(err, stream)`. + * @since v0.11.4 + * @param options Options containing connection details. Check + * `net.createConnection` for the format of the options. For custom agents, + * this object is passed to the custom `createConnection` function. + * @param callback (Optional, primarily for custom agents) A function to be + * called by a custom `createConnection` implementation when the socket is + * created, especially for asynchronous operations. + * @returns The created socket. This is returned by the default + * implementation or by a custom synchronous `createConnection` implementation. + * If a custom `createConnection` uses the `callback` for asynchronous + * operation, this return value might not be the primary way to obtain the socket. + */ + createConnection( + options: ClientRequestArgs, + callback?: (err: Error | null, stream: stream.Duplex) => void, + ): stream.Duplex | null | undefined; + /** + * Called when `socket` is detached from a request and could be persisted by the`Agent`. Default behavior is to: + * + * ```js + * socket.setKeepAlive(true, this.keepAliveMsecs); + * socket.unref(); + * return true; + * ``` + * + * This method can be overridden by a particular `Agent` subclass. If this + * method returns a falsy value, the socket will be destroyed instead of persisting + * it for use with the next request. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + keepSocketAlive(socket: stream.Duplex): void; + /** + * Called when `socket` is attached to `request` after being persisted because of + * the keep-alive options. Default behavior is to: + * + * ```js + * socket.ref(); + * ``` + * + * This method can be overridden by a particular `Agent` subclass. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + reuseSocket(socket: stream.Duplex, request: ClientRequest): void; + /** + * Get a unique name for a set of request options, to determine whether a + * connection can be reused. For an HTTP agent, this returns`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent, + * the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options + * that determine socket reusability. + * @since v0.11.4 + * @param options A set of options providing information for name generation + */ + getName(options?: ClientRequestArgs): string; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer(); + * + * // Listen to the request event + * server.on('request', (request, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >( + options: ServerOptions, + requestListener?: RequestListener, + ): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!', + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData), + * }, + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort()` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` and the `cause`, if one was provided. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()` automatically. The callback must take care to + * consume the response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Performs the low-level validations on the provided `name` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Example: + * + * ```js + * import { validateHeaderName } from 'node:http'; + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + /** + * Dynamically resets the global configurations to enable built-in proxy support for + * `fetch()` and `http.request()`/`https.request()` at runtime, as an alternative + * to using the `--use-env-proxy` flag or `NODE_USE_ENV_PROXY` environment variable. + * It can also be used to override settings configured from the environment variables. + * + * As this function resets the global configurations, any previously configured + * `http.globalAgent`, `https.globalAgent` or undici global dispatcher would be + * overridden after this function is invoked. It's recommended to invoke it before any + * requests are made and avoid invoking it in the middle of any requests. + * + * See [Built-in Proxy Support](https://nodejs.org/docs/latest-v25.x/api/http.html#built-in-proxy-support) for details on proxy URL formats and `NO_PROXY` + * syntax. + * @since v25.4.0 + * @param proxyEnv An object containing proxy configuration. This accepts the + * same options as the `proxyEnv` option accepted by {@link Agent}. **Default:** + * `process.env`. + * @returns A function that restores the original agent and dispatcher + * settings to the state before this `http.setGlobalProxyFromEnv()` is invoked. + */ + function setGlobalProxyFromEnv(proxyEnv?: ProxyEnv): () => void; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; + /** + * A browser-compatible implementation of `WebSocket`. + * @since v22.5.0 + */ + const WebSocket: typeof import("undici-types").WebSocket; + /** + * @since v22.5.0 + */ + const CloseEvent: typeof import("undici-types").CloseEvent; + /** + * @since v22.5.0 + */ + const MessageEvent: typeof import("undici-types").MessageEvent; +} +declare module "http" { + export * from "node:http"; +} diff --git a/node_modules/@types/node/http2.d.ts b/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..b2fcc59 --- /dev/null +++ b/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2470 @@ +declare module "node:http2" { + import { NonSharedBuffer } from "node:buffer"; + import { InternalEventEmitter } from "node:events"; + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + /** @deprecated */ + sumDependencyWeight?: number | undefined; + /** @deprecated */ + weight?: number | undefined; + } + interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + interface StatOptions { + offset: number; + length: number; + } + interface ServerStreamFileResponseOptions { + statCheck?: + | ((stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void) + | undefined; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?: ((err: NodeJS.ErrnoException) => void) | undefined; + } + interface Http2StreamEventMap extends stream.DuplexEventMap { + "aborted": []; + "data": [chunk: string | NonSharedBuffer]; + "frameError": [type: number, code: number, id: number]; + "ready": []; + "streamClosed": [code: number]; + "timeout": []; + "trailers": [trailers: IncomingHttpHeaders, flags: number]; + "wantTrailers": []; + } + interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the `Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * @deprecated Priority signaling is no longer supported in Node.js. + */ + priority(options: unknown): void; + /** + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: Http2StreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: Http2StreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: Http2StreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: Http2StreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface ClientHttp2StreamEventMap extends Http2StreamEventMap { + "continue": []; + "headers": [headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number, rawHeaders: string[]]; + "push": [headers: IncomingHttpHeaders, flags: number]; + "response": [headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number, rawHeaders: string[]]; + } + interface ClientHttp2Stream extends Http2Stream { + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ClientHttp2StreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ClientHttp2StreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: ClientHttp2StreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: ClientHttp2StreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to `true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: Pick, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be used to send trailing header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders | readonly string[], options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will + * perform an `fs.fstat()` call to collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` + * or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an + * `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * If the `onError` callback is defined, then it will be called. Otherwise, the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.error(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate `304` response: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + interface Http2SessionEventMap { + "close": []; + "connect": [session: Http2Session, socket: net.Socket | tls.TLSSocket]; + "error": [err: Error]; + "frameError": [type: number, code: number, id: number]; + "goaway": [errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer]; + "localSettings": [settings: Settings]; + "ping": [payload: Buffer]; + "remoteSettings": [settings: Settings]; + "stream": [ + stream: Http2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ]; + "timeout": []; + } + interface Http2Session extends InternalEventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect` callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this `Http2Session`. + * The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. + * Will be `false` once all sent `SETTINGS` frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. + * The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to `http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or `tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` is not undefined, an `'error'` event will be emitted immediately before the `'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false` otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the `maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING` payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: NonSharedBuffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: NonSharedBuffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new `SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true` while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + } + interface ClientHttp2SessionEventMap extends Http2SessionEventMap { + "altsvc": [alt: string, origin: string, streamId: number]; + "connect": [session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket]; + "origin": [origins: string[]]; + "stream": [ + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ]; + } + interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * import http2 from 'node:http2'; + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS, + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request( + headers?: OutgoingHttpHeaders | readonly string[], + options?: ClientSessionRequestOptions, + ): ClientHttp2Stream; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ClientHttp2StreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ClientHttp2StreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: ClientHttp2StreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: ClientHttp2StreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + interface ServerHttp2SessionEventMap< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends Http2SessionEventMap { + "connect": [ + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ]; + "stream": [stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number, rawHeaders: string[]]; + } + interface ServerHttp2Session< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends Http2Session { + readonly server: + | Http2Server + | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL `'https://example.org/foo/bar'` is the ASCII string` 'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit( + eventName: E, + ...args: ServerHttp2SessionEventMap[E] + ): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): (( + ...args: ServerHttp2SessionEventMap[E] + ) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): (( + ...args: ServerHttp2SessionEventMap[E] + ) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + // Http2Server + interface SessionOptions { + /** + * Sets the maximum dynamic table size for deflating header fields. + * @default 4Kib + */ + maxDeflateDynamicTableSize?: number | undefined; + /** + * Sets the maximum number of settings entries per `SETTINGS` frame. + * The minimum value allowed is `1`. + * @default 32 + */ + maxSettings?: number | undefined; + /** + * Sets the maximum memory that the `Http2Session` is permitted to use. + * The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. + * The minimum value allowed is `1`. + * This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, + * but new `Http2Stream` instances will be rejected while this limit is exceeded. + * The current number of `Http2Stream` sessions, the current memory use of the header compression tables, + * current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. + * @default 10 + */ + maxSessionMemory?: number | undefined; + /** + * Sets the maximum number of header entries. + * This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. + * The minimum value is `1`. + * @default 128 + */ + maxHeaderListPairs?: number | undefined; + /** + * Sets the maximum number of outstanding, unacknowledged pings. + * @default 10 + */ + maxOutstandingPings?: number | undefined; + /** + * Sets the maximum allowed size for a serialized, compressed block of headers. + * Attempts to send headers that exceed this limit will result in + * a `'frameError'` event being emitted and the stream being closed and destroyed. + */ + maxSendHeaderBlockLength?: number | undefined; + /** + * Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. + * @default http2.constants.PADDING_STRATEGY_NONE + */ + paddingStrategy?: number | undefined; + /** + * Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. + * Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. + * @default 100 + */ + peerMaxConcurrentStreams?: number | undefined; + /** + * The initial settings to send to the remote peer upon connection. + */ + settings?: Settings | undefined; + /** + * The array of integer values determines the settings types, + * which are included in the `CustomSettings`-property of the received remoteSettings. + * Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types. + */ + remoteCustomSettings?: number[] | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + /** + * If `true`, it turns on strict leading + * and trailing whitespace validation for HTTP/2 header field names and values + * as per [RFC-9113](https://www.rfc-editor.org/rfc/rfc9113.html#section-8.2.1). + * @since v24.2.0 + * @default true + */ + strictFieldWhitespaceValidation?: boolean | undefined; + } + interface ClientSessionOptions extends SessionOptions { + /** + * Sets the maximum number of reserved push streams the client will accept at any given time. + * Once the current number of currently reserved push streams exceeds reaches this limit, + * new push streams sent by the server will be automatically rejected. + * The minimum allowed value is 0. The maximum allowed value is 232-1. + * A negative value sets this option to the maximum allowed value. + * @default 200 + */ + maxReservedRemoteStreams?: number | undefined; + /** + * An optional callback that receives the `URL` instance passed to `connect` and the `options` object, + * and returns any `Duplex` stream that is to be used as the connection for this session. + */ + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + /** + * The protocol to connect with, if not set in the `authority`. + * Value may be either `'http:'` or `'https:'`. + * @default 'https:' + */ + protocol?: "http:" | "https:" | undefined; + } + interface ServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SessionOptions { + streamResetBurst?: number | undefined; + streamResetRate?: number | undefined; + Http1IncomingMessage?: Http1Request | undefined; + Http1ServerResponse?: Http1Response | undefined; + Http2ServerRequest?: Http2Request | undefined; + Http2ServerResponse?: Http2Response | undefined; + } + interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + interface SecureServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions, tls.TlsOptions {} + interface ServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions {} + interface SecureServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface Http2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + interface Http2ServerEventMap< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends net.ServerEventMap, Pick { + "checkContinue": [request: InstanceType, response: InstanceType]; + "request": [request: InstanceType, response: InstanceType]; + "session": [session: ServerHttp2Session]; + "sessionError": [err: Error]; + } + interface Http2Server< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends net.Server, Http2ServerCommon { + // #region InternalEventEmitter + addListener( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit( + eventName: E, + ...args: Http2ServerEventMap[E] + ): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: Http2ServerEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: Http2ServerEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface Http2SecureServerEventMap< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends tls.ServerEventMap, Http2ServerEventMap { + "unknownProtocol": [socket: tls.TLSSocket]; + } + interface Http2SecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends tls.Server, Http2ServerCommon { + // #region InternalEventEmitter + addListener( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit( + eventName: E, + ...args: Http2SecureServerEventMap[E] + ): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): (( + ...args: Http2SecureServerEventMap[E] + ) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): (( + ...args: Http2SecureServerEventMap[E] + ) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface Http2ServerRequestEventMap extends stream.ReadableEventMap { + "aborted": [hadError: boolean, code: number]; + "data": [chunk: string | NonSharedBuffer]; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from `req.headers[':authority']` if present. Otherwise, it is derived from `req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns `'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream`s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: Http2ServerRequestEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: Http2ServerRequestEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: Http2ServerRequestEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: Http2ServerRequestEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple times. + * + * If there were no previous values for the header, this is equivalent to calling {@link setHeader}. + * + * Attempting to set a header field name or value that contains invalid characters will result in a + * [TypeError](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-typeerror) being thrown. + * + * ```js + * // Returns headers including "set-cookie: a" and "set-cookie: b" + * const server = http2.createServer((req, res) => { + * res.setHeader('set-cookie', 'a'); + * res.appendHeader('set-cookie', 'b'); + * res.writeHead(200); + * res.end('ok'); + * }); + * ``` + * @since v20.12.0 + */ + appendHeader(name: string, value: string | string[]): void; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 `request` object. + * @since v15.7.0 + */ + readonly req: Request; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `node:http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and `Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }); + * ``` + * @since v18.11.0 + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the `Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | readonly string[]): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders | readonly string[]): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + } + namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * import http2 from 'node:http2'; + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + function getPackedSettings(settings: Settings): NonSharedBuffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session` instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * import http2 from 'node:http2'; + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8000); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + function createServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: ServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session` instances. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8443); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + function createSecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: SecureServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + /** + * Create an HTTP/2 server session from an existing socket. + * @param socket A Duplex Stream + * @param options Any `{@link createServer}` options can be provided. + * @since v20.12.0 + */ + function performServerHandshake< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + socket: stream.Duplex, + options?: ServerOptions, + ): ServerHttp2Session; +} +declare module "node:http2" { + export { OutgoingHttpHeaders } from "node:http"; +} +declare module "http2" { + export * from "node:http2"; +} diff --git a/node_modules/@types/node/https.d.ts b/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..b10aad0 --- /dev/null +++ b/node_modules/@types/node/https.d.ts @@ -0,0 +1,400 @@ +declare module "node:https" { + import * as http from "node:http"; + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import { URL } from "node:url"; + interface ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.ServerOptions, tls.TlsOptions {} + interface RequestOptions extends http.RequestOptions, tls.SecureContextOptions { + checkServerIdentity?: + | ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined) + | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + } + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * + * Like `http.Agent`, the `createConnection(options[, callback])` method can be overridden + * to customize how TLS connections are established. + * + * > See `agent.createConnection()` for details on overriding this method, + * > including asynchronous socket creation with a callback. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + createConnection( + options: RequestOptions, + callback?: (err: Error | null, stream: Duplex) => void, + ): Duplex | null | undefined; + getName(options?: RequestOptions): string; + } + interface ServerEventMap< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.ServerEventMap, tls.ServerEventMap {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ServerEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ServerEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: ServerEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: ServerEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.Server {} + /** + * ```js + * // curl -k https://localhost:8000/ + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample', + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import https from 'node:https'; + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false, + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * import tls from 'node:tls'; + * import https from 'node:https'; + * import crypto from 'node:crypto'; + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha256 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * import https from 'node:https'; + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "https" { + export * from "node:https"; +} diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..08ab4f0 --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,115 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.8+. + +// Reference required TypeScript libraries: +/// +/// +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..cf385b7 --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,264 @@ +declare module "node:inspector" { + import { EventEmitter } from "node:events"; + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + } + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the [security warning](https://nodejs.org/docs/latest-v25.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure) + * regarding the `host` parameter usage. + * @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Defaults to what was specified on the CLI. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; + // These methods are exposed by the V8 inspector console API (inspector/v8-console.h). + // The method signatures differ from those of the Node.js console, and are deliberately + // typed permissively. + interface InspectorConsole { + debug(...data: any[]): void; + error(...data: any[]): void; + info(...data: any[]): void; + log(...data: any[]): void; + warn(...data: any[]): void; + dir(...data: any[]): void; + dirxml(...data: any[]): void; + table(...data: any[]): void; + trace(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(...data: any[]): void; + clear(...data: any[]): void; + count(label?: any): void; + countReset(label?: any): void; + assert(value?: any, ...data: any[]): void; + profile(label?: any): void; + profileEnd(label?: any): void; + time(label?: any): void; + timeLog(label?: any): void; + timeStamp(label?: any): void; + } + /** + * An object to send messages to the remote inspector console. + * @since v11.0.0 + */ + const console: InspectorConsole; + // DevTools protocol event broadcast methods + namespace Network { + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that + * the application is about to send an HTTP request. + * @since v22.6.0 + */ + function requestWillBeSent(params: RequestWillBeSentEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.dataReceived` event to connected frontends, or buffers the data if + * `Network.streamResourceContent` command was not invoked for the given request yet. + * + * Also enables `Network.getResponseBody` command to retrieve the response data. + * @since v24.2.0 + */ + function dataReceived(params: DataReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Enables `Network.getRequestPostData` command to retrieve the request data. + * @since v24.3.0 + */ + function dataSent(params: unknown): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that + * HTTP response is available. + * @since v22.6.0 + */ + function responseReceived(params: ResponseReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that + * HTTP request has finished loading. + * @since v22.6.0 + */ + function loadingFinished(params: LoadingFinishedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that + * HTTP request has failed to load. + * @since v22.7.0 + */ + function loadingFailed(params: LoadingFailedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.webSocketCreated` event to connected frontends. This event indicates that + * a WebSocket connection has been initiated. + * @since v24.7.0 + */ + function webSocketCreated(params: WebSocketCreatedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.webSocketHandshakeResponseReceived` event to connected frontends. + * This event indicates that the WebSocket handshake response has been received. + * @since v24.7.0 + */ + function webSocketHandshakeResponseReceived(params: WebSocketHandshakeResponseReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.webSocketClosed` event to connected frontends. + * This event indicates that a WebSocket connection has been closed. + * @since v24.7.0 + */ + function webSocketClosed(params: WebSocketClosedEventDataType): void; + } + namespace NetworkResources { + /** + * This feature is only available with the `--experimental-inspector-network-resource` flag enabled. + * + * The inspector.NetworkResources.put method is used to provide a response for a loadNetworkResource + * request issued via the Chrome DevTools Protocol (CDP). + * This is typically triggered when a source map is specified by URL, and a DevTools frontend—such as + * Chrome—requests the resource to retrieve the source map. + * + * This method allows developers to predefine the resource content to be served in response to such CDP requests. + * + * ```js + * const inspector = require('node:inspector'); + * // By preemptively calling put to register the resource, a source map can be resolved when + * // a loadNetworkResource request is made from the frontend. + * async function setNetworkResources() { + * const mapUrl = 'http://localhost:3000/dist/app.js.map'; + * const tsUrl = 'http://localhost:3000/src/app.ts'; + * const distAppJsMap = await fetch(mapUrl).then((res) => res.text()); + * const srcAppTs = await fetch(tsUrl).then((res) => res.text()); + * inspector.NetworkResources.put(mapUrl, distAppJsMap); + * inspector.NetworkResources.put(tsUrl, srcAppTs); + * }; + * setNetworkResources().then(() => { + * require('./dist/app'); + * }); + * ``` + * + * For more details, see the official CDP documentation: [Network.loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-loadNetworkResource) + * @since v24.5.0 + * @experimental + */ + function put(url: string, data: string): void; + } + namespace DOMStorage { + /** + * This feature is only available with the + * `--experimental-storage-inspection` flag enabled. + * + * Broadcasts the `DOMStorage.domStorageItemAdded` event to connected frontends. + * This event indicates that a new item has been added to the storage. + * @since v25.5.0 + */ + function domStorageItemAdded(params: DomStorageItemAddedEventDataType): void; + /** + * This feature is only available with the + * `--experimental-storage-inspection` flag enabled. + * + * Broadcasts the `DOMStorage.domStorageItemRemoved` event to connected frontends. + * This event indicates that an item has been removed from the storage. + * @since v25.5.0 + */ + function domStorageItemRemoved(params: DomStorageItemRemovedEventDataType): void; + /** + * This feature is only available with the + * `--experimental-storage-inspection` flag enabled. + + * Broadcasts the `DOMStorage.domStorageItemUpdated` event to connected frontends. + * This event indicates that a storage item has been updated. + * @since v25.5.0 + */ + function domStorageItemUpdated(params: DomStorageItemUpdatedEventDataType): void; + /** + * This feature is only available with the + * `--experimental-storage-inspection` flag enabled. + * + * Broadcasts the `DOMStorage.domStorageItemsCleared` event to connected + * frontends. This event indicates that all items have been cleared from the + * storage. + * @since v25.5.0 + */ + function domStorageItemsCleared(params: DomStorageItemsClearedEventDataType): void; + /** + * This feature is only available with the + * `--experimental-storage-inspection` flag enabled. + * @since v25.5.0 + */ + function registerStorage(params: unknown): void; + } +} +declare module "inspector" { + export * from "node:inspector"; +} diff --git a/node_modules/@types/node/inspector.generated.d.ts b/node_modules/@types/node/inspector.generated.d.ts new file mode 100644 index 0000000..93ae271 --- /dev/null +++ b/node_modules/@types/node/inspector.generated.d.ts @@ -0,0 +1,4401 @@ +// These definitions are automatically generated by the generate-inspector script. +// Do not edit this file directly. +// See scripts/generate-inspector/README.md for information on how to update the protocol definitions. +// Changes to the module itself should be added to the generator template (scripts/generate-inspector/inspector.d.ts.template). + +declare module "node:inspector" { + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: object | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: object; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: object | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace IO { + type StreamHandle = string; + interface ReadParameterType { + /** + * Handle of the stream to read. + */ + handle: StreamHandle; + /** + * Seek to the specified offset before reading (if not specified, proceed with offset + * following the last read). Some types of streams may only support sequential reads. + */ + offset?: number | undefined; + /** + * Maximum number of bytes to read (left upon the agent discretion if not specified). + */ + size?: number | undefined; + } + interface CloseParameterType { + /** + * Handle of the stream to close. + */ + handle: StreamHandle; + } + interface ReadReturnType { + /** + * Data that were read. + */ + data: string; + /** + * Set if the end-of-file condition occurred while reading. + */ + eof: boolean; + } + } + namespace Network { + /** + * Resource type as it was perceived by the rendering engine. + */ + type ResourceType = string; + /** + * Unique request identifier. + */ + type RequestId = string; + /** + * UTC time in seconds, counted from January 1, 1970. + */ + type TimeSinceEpoch = number; + /** + * Monotonically increasing time in seconds since an arbitrary point in the past. + */ + type MonotonicTime = number; + /** + * Information about the request initiator. + */ + interface Initiator { + /** + * Type of this initiator. + */ + type: string; + /** + * Initiator JavaScript stack trace, set for Script only. + * Requires the Debugger domain to be enabled. + */ + stack?: Runtime.StackTrace | undefined; + /** + * Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type. + */ + url?: string | undefined; + /** + * Initiator line number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + lineNumber?: number | undefined; + /** + * Initiator column number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + columnNumber?: number | undefined; + /** + * Set if another request triggered this request (e.g. preflight). + */ + requestId?: RequestId | undefined; + } + /** + * HTTP request data. + */ + interface Request { + url: string; + method: string; + headers: Headers; + hasPostData: boolean; + } + /** + * HTTP response data. + */ + interface Response { + url: string; + status: number; + statusText: string; + headers: Headers; + mimeType: string; + charset: string; + } + /** + * Request / response headers as keys / values of JSON object. + */ + interface Headers { + } + interface LoadNetworkResourcePageResult { + success: boolean; + stream?: IO.StreamHandle | undefined; + } + /** + * WebSocket response data. + */ + interface WebSocketResponse { + /** + * HTTP response status code. + */ + status: number; + /** + * HTTP response status text. + */ + statusText: string; + /** + * HTTP response headers. + */ + headers: Headers; + } + interface EnableParameterType { + /** + * Buffer size in bytes to use when preserving network payloads (XHRs, etc). + * @experimental + */ + maxTotalBufferSize?: number | undefined; + /** + * Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc). + * @experimental + */ + maxResourceBufferSize?: number | undefined; + } + interface GetRequestPostDataParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface GetResponseBodyParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface StreamResourceContentParameterType { + /** + * Identifier of the request to stream. + */ + requestId: RequestId; + } + interface LoadNetworkResourceParameterType { + /** + * URL of the resource to get content for. + */ + url: string; + } + interface GetRequestPostDataReturnType { + /** + * Request body string, omitting files from multipart requests + */ + postData: string; + } + interface GetResponseBodyReturnType { + /** + * Response body. + */ + body: string; + /** + * True, if content was sent as base64. + */ + base64Encoded: boolean; + } + interface StreamResourceContentReturnType { + /** + * Data that has been buffered until streaming is enabled. + */ + bufferedData: string; + } + interface LoadNetworkResourceReturnType { + resource: LoadNetworkResourcePageResult; + } + interface RequestWillBeSentEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Request data. + */ + request: Request; + /** + * Request initiator. + */ + initiator: Initiator; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Timestamp. + */ + wallTime: TimeSinceEpoch; + } + interface ResponseReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Response data. + */ + response: Response; + } + interface LoadingFailedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Error message. + */ + errorText: string; + } + interface LoadingFinishedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + } + interface DataReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Data chunk length. + */ + dataLength: number; + /** + * Actual bytes received (might be less than dataLength for compressed encodings). + */ + encodedDataLength: number; + /** + * Data that was received. + * @experimental + */ + data?: string | undefined; + } + interface WebSocketCreatedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * WebSocket request URL. + */ + url: string; + /** + * Request initiator. + */ + initiator: Initiator; + } + interface WebSocketClosedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + } + interface WebSocketHandshakeResponseReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * WebSocket response data. + */ + response: WebSocketResponse; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: object[]; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace Target { + type SessionID = string; + type TargetID = string; + interface TargetInfo { + targetId: TargetID; + type: string; + title: string; + url: string; + attached: boolean; + canAccessOpener: boolean; + } + interface SetAutoAttachParameterType { + autoAttach: boolean; + waitForDebuggerOnStart: boolean; + } + interface TargetCreatedEventDataType { + targetInfo: TargetInfo; + } + interface AttachedToTargetEventDataType { + sessionId: SessionID; + targetInfo: TargetInfo; + waitingForDebugger: boolean; + } + } + namespace DOMStorage { + type SerializedStorageKey = string; + /** + * DOM Storage identifier. + */ + interface StorageId { + /** + * Security origin for the storage. + */ + securityOrigin?: string | undefined; + /** + * Represents a key by which DOM Storage keys its CachedStorageAreas + */ + storageKey?: SerializedStorageKey | undefined; + /** + * Whether the storage is local storage (not session storage). + */ + isLocalStorage: boolean; + } + /** + * DOM Storage item. + */ + type Item = string[]; + interface ClearParameterType { + storageId: StorageId; + } + interface GetDOMStorageItemsParameterType { + storageId: StorageId; + } + interface RemoveDOMStorageItemParameterType { + storageId: StorageId; + key: string; + } + interface SetDOMStorageItemParameterType { + storageId: StorageId; + key: string; + value: string; + } + interface GetDOMStorageItemsReturnType { + entries: Item[]; + } + interface DomStorageItemAddedEventDataType { + storageId: StorageId; + key: string; + newValue: string; + } + interface DomStorageItemRemovedEventDataType { + storageId: StorageId; + key: string; + } + interface DomStorageItemUpdatedEventDataType { + storageId: StorageId; + key: string; + oldValue: string; + newValue: string; + } + interface DomStorageItemsClearedEventDataType { + storageId: StorageId; + } + } + namespace Storage { + type SerializedStorageKey = string; + interface GetStorageKeyParameterType { + frameId?: string | undefined; + } + interface GetStorageKeyReturnType { + storageKey: SerializedStorageKey; + } + } + interface Session { + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, callback?: (err: Error | null, params?: object) => void): void; + post(method: string, params?: object, callback?: (err: Error | null, params?: object) => void): void; + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: "Runtime.globalLexicalScopeNames", + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: "Debugger.enable", callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: "Debugger.getPossibleBreakpoints", + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.pauseOnAsyncCall", callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: "Debugger.getStackTrace", callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setReturnValue", callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: "Console.enable", callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable", callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; + post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; + post(method: "Profiler.start", callback?: (err: Error | null) => void): void; + post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; + post( + method: "HeapProfiler.getObjectByHeapObjectId", + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: "HeapProfiler.getSamplingProfile", callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Read a chunk of the stream + */ + post(method: "IO.read", params?: IO.ReadParameterType, callback?: (err: Error | null, params: IO.ReadReturnType) => void): void; + post(method: "IO.read", callback?: (err: Error | null, params: IO.ReadReturnType) => void): void; + post(method: "IO.close", params?: IO.CloseParameterType, callback?: (err: Error | null) => void): void; + post(method: "IO.close", callback?: (err: Error | null) => void): void; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: "Network.disable", callback?: (err: Error | null) => void): void; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: "Network.enable", params?: Network.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "Network.enable", callback?: (err: Error | null) => void): void; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: "Network.getRequestPostData", params?: Network.GetRequestPostDataParameterType, callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + post(method: "Network.getRequestPostData", callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + /** + * Returns content served for the given request. + */ + post(method: "Network.getResponseBody", params?: Network.GetResponseBodyParameterType, callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + post(method: "Network.getResponseBody", callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post( + method: "Network.streamResourceContent", + params?: Network.StreamResourceContentParameterType, + callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void + ): void; + post(method: "Network.streamResourceContent", callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void): void; + /** + * Fetches the resource and returns the content. + */ + post(method: "Network.loadNetworkResource", params?: Network.LoadNetworkResourceParameterType, callback?: (err: Error | null, params: Network.LoadNetworkResourceReturnType) => void): void; + post(method: "Network.loadNetworkResource", callback?: (err: Error | null, params: Network.LoadNetworkResourceReturnType) => void): void; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.enable", callback?: (err: Error | null) => void): void; + /** + * Disable NodeRuntime events + */ + post(method: "NodeRuntime.disable", callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", callback?: (err: Error | null) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.detach", callback?: (err: Error | null) => void): void; + post(method: "Target.setAutoAttach", params?: Target.SetAutoAttachParameterType, callback?: (err: Error | null) => void): void; + post(method: "Target.setAutoAttach", callback?: (err: Error | null) => void): void; + post(method: "DOMStorage.clear", params?: DOMStorage.ClearParameterType, callback?: (err: Error | null) => void): void; + post(method: "DOMStorage.clear", callback?: (err: Error | null) => void): void; + /** + * Disables storage tracking, prevents storage events from being sent to the client. + */ + post(method: "DOMStorage.disable", callback?: (err: Error | null) => void): void; + /** + * Enables storage tracking, storage events will now be delivered to the client. + */ + post(method: "DOMStorage.enable", callback?: (err: Error | null) => void): void; + post( + method: "DOMStorage.getDOMStorageItems", + params?: DOMStorage.GetDOMStorageItemsParameterType, + callback?: (err: Error | null, params: DOMStorage.GetDOMStorageItemsReturnType) => void + ): void; + post(method: "DOMStorage.getDOMStorageItems", callback?: (err: Error | null, params: DOMStorage.GetDOMStorageItemsReturnType) => void): void; + post(method: "DOMStorage.removeDOMStorageItem", params?: DOMStorage.RemoveDOMStorageItemParameterType, callback?: (err: Error | null) => void): void; + post(method: "DOMStorage.removeDOMStorageItem", callback?: (err: Error | null) => void): void; + post(method: "DOMStorage.setDOMStorageItem", params?: DOMStorage.SetDOMStorageItemParameterType, callback?: (err: Error | null) => void): void; + post(method: "DOMStorage.setDOMStorageItem", callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: "Storage.getStorageKey", params?: Storage.GetStorageKeyParameterType, callback?: (err: Error | null, params: Storage.GetStorageKeyReturnType) => void): void; + post(method: "Storage.getStorageKey", callback?: (err: Error | null, params: Storage.GetStorageKeyReturnType) => void): void; + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + addListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + addListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + addListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "Network.requestWillBeSent", message: InspectorNotification): boolean; + emit(event: "Network.responseReceived", message: InspectorNotification): boolean; + emit(event: "Network.loadingFailed", message: InspectorNotification): boolean; + emit(event: "Network.loadingFinished", message: InspectorNotification): boolean; + emit(event: "Network.dataReceived", message: InspectorNotification): boolean; + emit(event: "Network.webSocketCreated", message: InspectorNotification): boolean; + emit(event: "Network.webSocketClosed", message: InspectorNotification): boolean; + emit(event: "Network.webSocketHandshakeResponseReceived", message: InspectorNotification): boolean; + emit(event: "NodeRuntime.waitingForDisconnect"): boolean; + emit(event: "NodeRuntime.waitingForDebugger"): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + emit(event: "Target.targetCreated", message: InspectorNotification): boolean; + emit(event: "Target.attachedToTarget", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemAdded", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemRemoved", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemUpdated", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemsCleared", message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + on(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + on(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + on(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + on(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + on(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + once(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + once(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + once(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + once(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + once(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + prependListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + prependListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + prependListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + prependOnceListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + prependOnceListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + prependOnceListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; + } +} +declare module "node:inspector/promises" { + export { + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + IO, + Network, + NodeRuntime, + NodeTracing, + NodeWorker, + Target, + DOMStorage, + Storage, + } from 'inspector'; +} +declare module "node:inspector/promises" { + import { + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + IO, + Network, + NodeRuntime, + NodeTracing, + NodeWorker, + Target, + DOMStorage, + Storage, + } from "inspector"; + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + interface Session { + /** + * Posts a message to the inspector back-end. + * + * ```js + * import { Session } from 'node:inspector/promises'; + * try { + * const session = new Session(); + * session.connect(); + * const result = await session.post('Runtime.evaluate', { expression: '2 + 2' }); + * console.log(result); + * } catch (error) { + * console.error(error); + * } + * // Output: { result: { type: 'number', value: 4, description: '4' } } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, params?: object): Promise; + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains"): Promise; + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType): Promise; + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType): Promise; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType): Promise; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType): Promise; + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType): Promise; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType): Promise; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger"): Promise; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: "Runtime.enable"): Promise; + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable"): Promise; + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries"): Promise; + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType): Promise; + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType): Promise; + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType): Promise; + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType): Promise; + /** + * Returns all let, const and class variables from global scope. + */ + post(method: "Runtime.globalLexicalScopeNames", params?: Runtime.GlobalLexicalScopeNamesParameterType): Promise; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: "Debugger.enable"): Promise; + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable"): Promise; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType): Promise; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType): Promise; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType): Promise; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType): Promise; + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType): Promise; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post(method: "Debugger.getPossibleBreakpoints", params?: Debugger.GetPossibleBreakpointsParameterType): Promise; + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType): Promise; + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType): Promise; + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver"): Promise; + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType): Promise; + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut"): Promise; + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause"): Promise; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync"): Promise; + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume"): Promise; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType): Promise; + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType): Promise; + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType): Promise; + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType): Promise; + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType): Promise; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType): Promise; + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType): Promise; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType): Promise; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType): Promise; + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType): Promise; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType): Promise; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType): Promise; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: "Console.enable"): Promise; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable"): Promise; + /** + * Does nothing. + */ + post(method: "Console.clearMessages"): Promise; + post(method: "Profiler.enable"): Promise; + post(method: "Profiler.disable"): Promise; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType): Promise; + post(method: "Profiler.start"): Promise; + post(method: "Profiler.stop"): Promise; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType): Promise; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage"): Promise; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage"): Promise; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage"): Promise; + post(method: "HeapProfiler.enable"): Promise; + post(method: "HeapProfiler.disable"): Promise; + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType): Promise; + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType): Promise; + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType): Promise; + post(method: "HeapProfiler.collectGarbage"): Promise; + post(method: "HeapProfiler.getObjectByHeapObjectId", params?: HeapProfiler.GetObjectByHeapObjectIdParameterType): Promise; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType): Promise; + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType): Promise; + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType): Promise; + post(method: "HeapProfiler.stopSampling"): Promise; + post(method: "HeapProfiler.getSamplingProfile"): Promise; + /** + * Read a chunk of the stream + */ + post(method: "IO.read", params?: IO.ReadParameterType): Promise; + post(method: "IO.close", params?: IO.CloseParameterType): Promise; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: "Network.disable"): Promise; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: "Network.enable", params?: Network.EnableParameterType): Promise; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: "Network.getRequestPostData", params?: Network.GetRequestPostDataParameterType): Promise; + /** + * Returns content served for the given request. + */ + post(method: "Network.getResponseBody", params?: Network.GetResponseBodyParameterType): Promise; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post(method: "Network.streamResourceContent", params?: Network.StreamResourceContentParameterType): Promise; + /** + * Fetches the resource and returns the content. + */ + post(method: "Network.loadNetworkResource", params?: Network.LoadNetworkResourceParameterType): Promise; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.enable"): Promise; + /** + * Disable NodeRuntime events + */ + post(method: "NodeRuntime.disable"): Promise; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType): Promise; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories"): Promise; + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType): Promise; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop"): Promise; + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType): Promise; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType): Promise; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable"): Promise; + /** + * Detached from the worker with given sessionId. + */ + post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType): Promise; + post(method: "Target.setAutoAttach", params?: Target.SetAutoAttachParameterType): Promise; + post(method: "DOMStorage.clear", params?: DOMStorage.ClearParameterType): Promise; + /** + * Disables storage tracking, prevents storage events from being sent to the client. + */ + post(method: "DOMStorage.disable"): Promise; + /** + * Enables storage tracking, storage events will now be delivered to the client. + */ + post(method: "DOMStorage.enable"): Promise; + post(method: "DOMStorage.getDOMStorageItems", params?: DOMStorage.GetDOMStorageItemsParameterType): Promise; + post(method: "DOMStorage.removeDOMStorageItem", params?: DOMStorage.RemoveDOMStorageItemParameterType): Promise; + post(method: "DOMStorage.setDOMStorageItem", params?: DOMStorage.SetDOMStorageItemParameterType): Promise; + /** + * @experimental + */ + post(method: "Storage.getStorageKey", params?: Storage.GetStorageKeyParameterType): Promise; + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + addListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + addListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + addListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "Network.requestWillBeSent", message: InspectorNotification): boolean; + emit(event: "Network.responseReceived", message: InspectorNotification): boolean; + emit(event: "Network.loadingFailed", message: InspectorNotification): boolean; + emit(event: "Network.loadingFinished", message: InspectorNotification): boolean; + emit(event: "Network.dataReceived", message: InspectorNotification): boolean; + emit(event: "Network.webSocketCreated", message: InspectorNotification): boolean; + emit(event: "Network.webSocketClosed", message: InspectorNotification): boolean; + emit(event: "Network.webSocketHandshakeResponseReceived", message: InspectorNotification): boolean; + emit(event: "NodeRuntime.waitingForDisconnect"): boolean; + emit(event: "NodeRuntime.waitingForDebugger"): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + emit(event: "Target.targetCreated", message: InspectorNotification): boolean; + emit(event: "Target.attachedToTarget", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemAdded", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemRemoved", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemUpdated", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemsCleared", message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + on(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + on(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + on(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + on(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + on(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + once(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + once(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + once(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + once(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + once(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + prependListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + prependListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + prependListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + prependOnceListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + prependOnceListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + prependOnceListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; + } +} diff --git a/node_modules/@types/node/inspector/promises.d.ts b/node_modules/@types/node/inspector/promises.d.ts new file mode 100644 index 0000000..e75ff20 --- /dev/null +++ b/node_modules/@types/node/inspector/promises.d.ts @@ -0,0 +1,35 @@ +declare module "node:inspector/promises" { + import { EventEmitter } from "node:events"; + export { close, console, NetworkResources, open, url, waitForDebugger } from "node:inspector"; + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + export class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + } +} +declare module "inspector/promises" { + export * from "node:inspector/promises"; +} diff --git a/node_modules/@types/node/module.d.ts b/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..7f61a67 --- /dev/null +++ b/node_modules/@types/node/module.d.ts @@ -0,0 +1,754 @@ +declare module "node:module" { + import { URL } from "node:url"; + class Module { + constructor(id: string, parent?: Module); + } + interface Module extends NodeJS.Module {} + namespace Module { + export { Module }; + } + namespace Module { + /** + * A list of the names of all modules provided by Node.js. Can be used to verify + * if a module is maintained by a third party or not. + * + * Note: the list doesn't contain prefix-only modules like `node:test`. + * @since v9.3.0, v8.10.0, v6.13.0 + */ + const builtinModules: readonly string[]; + /** + * @since v12.2.0 + * @param path Filename to be used to construct the require + * function. Must be a file URL object, file URL string, or absolute path + * string. + */ + function createRequire(path: string | URL): NodeJS.Require; + namespace constants { + /** + * The following constants are returned as the `status` field in the object returned by + * {@link enableCompileCache} to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache). + * @since v22.8.0 + */ + namespace compileCacheStatus { + /** + * Node.js has enabled the compile cache successfully. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ENABLED: number; + /** + * The compile cache has already been enabled before, either by a previous call to + * {@link enableCompileCache}, or by the `NODE_COMPILE_CACHE=dir` + * environment variable. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ALREADY_ENABLED: number; + /** + * Node.js fails to enable the compile cache. This can be caused by the lack of + * permission to use the specified directory, or various kinds of file system errors. + * The detail of the failure will be returned in the `message` field in the + * returned object. + */ + const FAILED: number; + /** + * Node.js cannot enable the compile cache because the environment variable + * `NODE_DISABLE_COMPILE_CACHE=1` has been set. + */ + const DISABLED: number; + } + } + interface EnableCompileCacheOptions { + /** + * Optional. Directory to store the compile cache. If not specified, + * the directory specified by the `NODE_COMPILE_CACHE=dir` environment variable + * will be used if it's set, or `path.join(os.tmpdir(), 'node-compile-cache')` + * otherwise. + * @since v25.0.0 + */ + directory?: string | undefined; + /** + * Optional. If `true`, enables portable compile cache so that + * the cache can be reused even if the project directory is moved. This is a best-effort + * feature. If not specified, it will depend on whether the environment variable + * `NODE_COMPILE_CACHE_PORTABLE=1` is set. + * @since v25.0.0 + */ + portable?: boolean | undefined; + } + interface EnableCompileCacheResult { + /** + * One of the {@link constants.compileCacheStatus} + */ + status: number; + /** + * If Node.js cannot enable the compile cache, this contains + * the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`. + */ + message?: string; + /** + * If the compile cache is enabled, this contains the directory + * where the compile cache is stored. Only set if `status` is + * `module.constants.compileCacheStatus.ENABLED` or + * `module.constants.compileCacheStatus.ALREADY_ENABLED`. + */ + directory?: string; + } + /** + * Enable [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache) + * in the current Node.js instance. + * + * For general use cases, it's recommended to call `module.enableCompileCache()` without + * specifying the `options.directory`, so that the directory can be overridden by the + * `NODE_COMPILE_CACHE` environment variable when necessary. + * + * Since compile cache is supposed to be a optimization that is not mission critical, this + * method is designed to not throw any exception when the compile cache cannot be enabled. + * Instead, it will return an object containing an error message in the `message` field to + * aid debugging. If compile cache is enabled successfully, the `directory` field in the + * returned object contains the path to the directory where the compile cache is stored. The + * `status` field in the returned object would be one of the `module.constants.compileCacheStatus` + * values to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache). + * + * This method only affects the current Node.js instance. To enable it in child worker threads, + * either call this method in child worker threads too, or set the + * `process.env.NODE_COMPILE_CACHE` value to compile cache directory so the behavior can + * be inherited into the child workers. The directory can be obtained either from the + * `directory` field returned by this method, or with {@link getCompileCacheDir}. + * @since v22.8.0 + * @param options Optional. If a string is passed, it is considered to be `options.directory`. + */ + function enableCompileCache(options?: string | EnableCompileCacheOptions): EnableCompileCacheResult; + /** + * Flush the [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache) + * accumulated from modules already loaded + * in the current Node.js instance to disk. This returns after all the flushing + * file system operations come to an end, no matter they succeed or not. If there + * are any errors, this will fail silently, since compile cache misses should not + * interfere with the actual operation of the application. + * @since v22.10.0 + */ + function flushCompileCache(): void; + /** + * @since v22.8.0 + * @return Path to the [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache) + * directory if it is enabled, or `undefined` otherwise. + */ + function getCompileCacheDir(): string | undefined; + /** + * ```text + * /path/to/project + * ├ packages/ + * ├ bar/ + * ├ bar.js + * └ package.json // name = '@foo/bar' + * └ qux/ + * ├ node_modules/ + * └ some-package/ + * └ package.json // name = 'some-package' + * ├ qux.js + * └ package.json // name = '@foo/qux' + * ├ main.js + * └ package.json // name = '@foo' + * ``` + * ```js + * // /path/to/project/packages/bar/bar.js + * import { findPackageJSON } from 'node:module'; + * + * findPackageJSON('..', import.meta.url); + * // '/path/to/project/package.json' + * // Same result when passing an absolute specifier instead: + * findPackageJSON(new URL('../', import.meta.url)); + * findPackageJSON(import.meta.resolve('../')); + * + * findPackageJSON('some-package', import.meta.url); + * // '/path/to/project/packages/bar/node_modules/some-package/package.json' + * // When passing an absolute specifier, you might get a different result if the + * // resolved module is inside a subfolder that has nested `package.json`. + * findPackageJSON(import.meta.resolve('some-package')); + * // '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json' + * + * findPackageJSON('@foo/qux', import.meta.url); + * // '/path/to/project/packages/qux/package.json' + * ``` + * @since v22.14.0 + * @param specifier The specifier for the module whose `package.json` to + * retrieve. When passing a _bare specifier_, the `package.json` at the root of + * the package is returned. When passing a _relative specifier_ or an _absolute specifier_, + * the closest parent `package.json` is returned. + * @param base The absolute location (`file:` URL string or FS path) of the + * containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use + * `import.meta.url`. You do not need to pass it if `specifier` is an _absolute specifier_. + * @returns A path if the `package.json` is found. When `startLocation` + * is a package, the package's root `package.json`; when a relative or unresolved, the closest + * `package.json` to the `startLocation`. + */ + function findPackageJSON(specifier: string | URL, base?: string | URL): string | undefined; + /** + * @since v18.6.0, v16.17.0 + */ + function isBuiltin(moduleName: string): boolean; + interface RegisterOptions { + /** + * If you want to resolve `specifier` relative to a + * base URL, such as `import.meta.url`, you can pass that URL here. This + * property is ignored if the `parentURL` is supplied as the second argument. + * @default 'data:' + */ + parentURL?: string | URL | undefined; + /** + * Any arbitrary, cloneable JavaScript value to pass into the + * {@link initialize} hook. + */ + data?: Data | undefined; + /** + * [Transferable objects](https://nodejs.org/docs/latest-v25.x/api/worker_threads.html#portpostmessagevalue-transferlist) + * to be passed into the `initialize` hook. + */ + transferList?: any[] | undefined; + } + /* eslint-disable @definitelytyped/no-unnecessary-generics */ + /** + * Register a module that exports hooks that customize Node.js module + * resolution and loading behavior. See + * [Customization hooks](https://nodejs.org/docs/latest-v25.x/api/module.html#customization-hooks). + * + * This feature requires `--allow-worker` if used with the + * [Permission Model](https://nodejs.org/docs/latest-v25.x/api/permissions.html#permission-model). + * @since v20.6.0, v18.19.0 + * @param specifier Customization hooks to be registered; this should be + * the same string that would be passed to `import()`, except that if it is + * relative, it is resolved relative to `parentURL`. + * @param parentURL f you want to resolve `specifier` relative to a base + * URL, such as `import.meta.url`, you can pass that URL here. + */ + function register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + function register(specifier: string | URL, options?: RegisterOptions): void; + interface RegisterHooksOptions { + /** + * See [load hook](https://nodejs.org/docs/latest-v25.x/api/module.html#loadurl-context-nextload). + * @default undefined + */ + load?: LoadHookSync | undefined; + /** + * See [resolve hook](https://nodejs.org/docs/latest-v25.x/api/module.html#resolvespecifier-context-nextresolve). + * @default undefined + */ + resolve?: ResolveHookSync | undefined; + } + interface ModuleHooks { + /** + * Deregister the hook instance. + */ + deregister(): void; + } + /** + * Register [hooks](https://nodejs.org/docs/latest-v25.x/api/module.html#customization-hooks) + * that customize Node.js module resolution and loading behavior. + * @since v22.15.0 + * @experimental + */ + function registerHooks(options: RegisterHooksOptions): ModuleHooks; + interface StripTypeScriptTypesOptions { + /** + * Possible values are: + * * `'strip'` Only strip type annotations without performing the transformation of TypeScript features. + * * `'transform'` Strip type annotations and transform TypeScript features to JavaScript. + * @default 'strip' + */ + mode?: "strip" | "transform" | undefined; + /** + * Only when `mode` is `'transform'`, if `true`, a source map + * will be generated for the transformed code. + * @default false + */ + sourceMap?: boolean | undefined; + /** + * Specifies the source url used in the source map. + */ + sourceUrl?: string | undefined; + } + /** + * `module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It + * can be used to strip type annotations from TypeScript code before running it + * with `vm.runInContext()` or `vm.compileFunction()`. + * By default, it will throw an error if the code contains TypeScript features + * that require transformation such as `Enums`, + * see [type-stripping](https://nodejs.org/docs/latest-v25.x/api/typescript.md#type-stripping) for more information. + * When mode is `'transform'`, it also transforms TypeScript features to JavaScript, + * see [transform TypeScript features](https://nodejs.org/docs/latest-v25.x/api/typescript.md#typescript-features) for more information. + * When mode is `'strip'`, source maps are not generated, because locations are preserved. + * If `sourceMap` is provided, when mode is `'strip'`, an error will be thrown. + * + * _WARNING_: The output of this function should not be considered stable across Node.js versions, + * due to changes in the TypeScript parser. + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code); + * console.log(strippedCode); + * // Prints: const a = 1; + * ``` + * + * If `sourceUrl` is provided, it will be used appended as a comment at the end of the output: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' }); + * console.log(strippedCode); + * // Prints: const a = 1\n\n//# sourceURL=source.ts; + * ``` + * + * When `mode` is `'transform'`, the code is transformed to JavaScript: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = ` + * namespace MathUtil { + * export const add = (a: number, b: number) => a + b; + * }`; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true }); + * console.log(strippedCode); + * // Prints: + * // var MathUtil; + * // (function(MathUtil) { + * // MathUtil.add = (a, b)=>a + b; + * // })(MathUtil || (MathUtil = {})); + * // # sourceMappingURL=data:application/json;base64, ... + * ``` + * @since v22.13.0 + * @param code The code to strip type annotations from. + * @returns The code with type annotations stripped. + */ + function stripTypeScriptTypes(code: string, options?: StripTypeScriptTypesOptions): string; + /* eslint-enable @definitelytyped/no-unnecessary-generics */ + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * import fs from 'node:fs'; + * import assert from 'node:assert'; + * import { syncBuiltinESMExports } from 'node:module'; + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node:fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ImportPhase = "source" | "evaluation"; + type ModuleFormat = + | "addon" + | "builtin" + | "commonjs" + | "commonjs-typescript" + | "json" + | "module" + | "module-typescript" + | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + conditions: string[]; + importAttributes: ImportAttributes; + parentURL: string | undefined; + } + interface ResolveFnOutput { + format?: string | null | undefined; + importAttributes?: ImportAttributes | undefined; + shortCircuit?: boolean | undefined; + url: string; + } + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + type ResolveHookSync = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput, + ) => ResolveFnOutput; + interface LoadHookContext { + conditions: string[]; + format: string | null | undefined; + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: string | null | undefined; + shortCircuit?: boolean | undefined; + source?: ModuleSource | undefined; + } + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + type LoadHookSync = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput, + ) => LoadFnOutput; + interface SourceMapsSupport { + /** + * If the source maps support is enabled + */ + enabled: boolean; + /** + * If the support is enabled for files in `node_modules`. + */ + nodeModules: boolean; + /** + * If the support is enabled for generated code from `eval` or `new Function`. + */ + generatedCode: boolean; + } + /** + * This method returns whether the [Source Map v3](https://tc39.es/ecma426/) support for stack + * traces is enabled. + * @since v23.7.0, v22.14.0 + */ + function getSourceMapsSupport(): SourceMapsSupport; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + function findSourceMap(path: string): SourceMap | undefined; + interface SetSourceMapsSupportOptions { + /** + * If enabling the support for files in `node_modules`. + * @default false + */ + nodeModules?: boolean | undefined; + /** + * If enabling the support for generated code from `eval` or `new Function`. + * @default false + */ + generatedCode?: boolean | undefined; + } + /** + * This function enables or disables the [Source Map v3](https://tc39.es/ecma426/) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options + * `--enable-source-maps`, with additional options to alter the support for files + * in `node_modules` or generated codes. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. Preferably, use the commandline options + * `--enable-source-maps` to avoid losing track of source maps of modules loaded + * before this API call. + * @since v23.7.0, v22.14.0 + */ + function setSourceMapsSupport(enabled: boolean, options?: SetSourceMapsSupportOptions): void; + interface SourceMapConstructorOptions { + /** + * @since v21.0.0, v20.5.0 + */ + lineLengths?: readonly number[] | undefined; + } + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name: string | undefined; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + constructor(payload: SourceMapPayload, options?: SourceMapConstructorOptions); + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping | {}; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + function runMain(main?: string): void; + function wrap(script: string): string; + } + global { + namespace NodeJS { + interface Module { + /** + * The module objects required for the first time by this one. + * @since v0.1.16 + */ + children: Module[]; + /** + * The `module.exports` object is created by the `Module` system. Sometimes this is + * not acceptable; many want their module to be an instance of some class. To do + * this, assign the desired export object to `module.exports`. + * @since v0.1.16 + */ + exports: any; + /** + * The fully resolved filename of the module. + * @since v0.1.16 + */ + filename: string; + /** + * The identifier for the module. Typically this is the fully resolved + * filename. + * @since v0.1.16 + */ + id: string; + /** + * `true` if the module is running during the Node.js preload + * phase. + * @since v15.4.0, v14.17.0 + */ + isPreloading: boolean; + /** + * Whether or not the module is done loading, or is in the process of + * loading. + * @since v0.1.16 + */ + loaded: boolean; + /** + * The module that first required this one, or `null` if the current module is the + * entry point of the current process, or `undefined` if the module was loaded by + * something that is not a CommonJS module (e.g. REPL or `import`). + * @since v0.1.16 + * @deprecated Please use `require.main` and `module.children` instead. + */ + parent: Module | null | undefined; + /** + * The directory name of the module. This is usually the same as the + * `path.dirname()` of the `module.id`. + * @since v11.14.0 + */ + path: string; + /** + * The search paths for the module. + * @since v0.4.0 + */ + paths: string[]; + /** + * The `module.require()` method provides a way to load a module as if + * `require()` was called from the original module. + * @since v0.5.1 + */ + require(id: string): any; + } + interface Require { + /** + * Used to import modules, `JSON`, and local files. + * @since v0.1.13 + */ + (id: string): any; + /** + * Modules are cached in this object when they are required. By deleting a key + * value from this object, the next `require` will reload the module. + * This does not apply to + * [native addons](https://nodejs.org/docs/latest-v25.x/api/addons.html), + * for which reloading will result in an error. + * @since v0.3.0 + */ + cache: Dict; + /** + * Instruct `require` on how to handle certain file extensions. + * @since v0.3.0 + * @deprecated + */ + extensions: RequireExtensions; + /** + * The `Module` object representing the entry script loaded when the Node.js + * process launched, or `undefined` if the entry point of the program is not a + * CommonJS module. + * @since v0.1.17 + */ + main: Module | undefined; + /** + * @since v0.3.0 + */ + resolve: RequireResolve; + } + /** @deprecated */ + interface RequireExtensions extends Dict<(module: Module, filename: string) => any> { + ".js": (module: Module, filename: string) => any; + ".json": (module: Module, filename: string) => any; + ".node": (module: Module, filename: string) => any; + } + interface RequireResolveOptions { + /** + * Paths to resolve module location from. If present, these + * paths are used instead of the default resolution paths, with the exception + * of + * [GLOBAL\_FOLDERS](https://nodejs.org/docs/latest-v25.x/api/modules.html#loading-from-the-global-folders) + * like `$HOME/.node_modules`, which are + * always included. Each of these paths is used as a starting point for + * the module resolution algorithm, meaning that the `node_modules` hierarchy + * is checked from this location. + * @since v8.9.0 + */ + paths?: string[] | undefined; + } + interface RequireResolve { + /** + * Use the internal `require()` machinery to look up the location of a module, + * but rather than loading the module, just return the resolved filename. + * + * If the module can not be found, a `MODULE_NOT_FOUND` error is thrown. + * @since v0.3.0 + * @param request The module path to resolve. + */ + (request: string, options?: RequireResolveOptions): string; + /** + * Returns an array containing the paths searched during resolution of `request` or + * `null` if the `request` string references a core module, for example `http` or + * `fs`. + * @since v8.9.0 + * @param request The module path whose lookup paths are being retrieved. + */ + paths(request: string): string[] | null; + } + } + /** + * The directory name of the current module. This is the same as the + * `path.dirname()` of the `__filename`. + * @since v0.1.27 + */ + var __dirname: string; + /** + * The file name of the current module. This is the current module file's absolute + * path with symlinks resolved. + * + * For a main program this is not necessarily the same as the file name used in the + * command line. + * @since v0.0.1 + */ + var __filename: string; + /** + * The `exports` variable is available within a module's file-level scope, and is + * assigned the value of `module.exports` before the module is evaluated. + * @since v0.1.16 + */ + var exports: NodeJS.Module["exports"]; + /** + * A reference to the current module. + * @since v0.1.16 + */ + var module: NodeJS.Module; + /** + * @since v0.1.13 + */ + var require: NodeJS.Require; + // Global-scope aliases for backwards compatibility with @types/node <13.0.x + // TODO: consider removing in a future major version update + /** @deprecated Use `NodeJS.Module` instead. */ + interface NodeModule extends NodeJS.Module {} + /** @deprecated Use `NodeJS.Require` instead. */ + interface NodeRequire extends NodeJS.Require {} + /** @deprecated Use `NodeJS.RequireResolve` instead. */ + interface RequireResolve extends NodeJS.RequireResolve {} + } + export = Module; +} +declare module "module" { + import module = require("node:module"); + export = module; +} diff --git a/node_modules/@types/node/net.d.ts b/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..bb6d3a3 --- /dev/null +++ b/node_modules/@types/node/net.d.ts @@ -0,0 +1,970 @@ +declare module "node:net" { + import { NonSharedBuffer } from "node:buffer"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter, InternalEventEmitter } from "node:events"; + import * as stream from "node:stream"; + type LookupFunction = ( + hostname: string, + options: dns.LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + onread?: OnReadOpts | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + blockList?: BlockList | undefined; + typeOfService?: number | undefined; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to `buffer` and a reference to `buffer`. + * Return `false` from this function to implicitly `pause()` the socket. + */ + callback(bytesWritten: number, buffer: Uint8Array): boolean; + } + interface TcpSocketConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + } + interface IpcSocketConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + interface SocketEventMap extends Omit { + "close": [hadError: boolean]; + "connect": []; + "connectionAttempt": [ip: string, port: number, family: number]; + "connectionAttemptFailed": [ip: string, port: number, family: number, error: Error]; + "connectionAttemptTimeout": [ip: string, port: number, family: number]; + "data": [data: string | NonSharedBuffer]; + "lookup": [err: Error | null, address: string, family: number | null, host: string]; + "ready": []; + "timeout": []; + } + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + */ + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + /** + * Sends data on the socket, with an explicit encoding for string data. + * @see {@link Socket.write} for full details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the current Type of Service (TOS) field for IPv4 packets or Traffic + * Class for IPv6 packets for this socket. + * + * `setTypeOfService()` may be called before the socket is connected; the value + * will be cached and applied when the socket establishes a connection. + * `getTypeOfService()` will return the currently set value even before connection. + * + * On some platforms (e.g., Linux), certain TOS/ECN bits may be masked or ignored, + * and behavior can differ between IPv4 and IPv6 or dual-stack sockets. Callers + * should verify platform-specific semantics. + * @since v25.6.0 + * @returns The current TOS value. + */ + getTypeOfService(): number; + /** + * Sets the Type of Service (TOS) field for IPv4 packets or Traffic Class for IPv6 + * Packets sent from this socket. This can be used to prioritize network traffic. + * + * `setTypeOfService()` may be called before the socket is connected; the value + * will be cached and applied when the socket establishes a connection. + * `getTypeOfService()` will return the currently set value even before connection. + * + * On some platforms (e.g., Linux), certain TOS/ECN bits may be masked or ignored, + * and behavior can differ between IPv4 and IPv6 or dual-stack sockets. Callers + * should verify platform-specific semantics. + * @since v25.6.0 + * @param tos The TOS value to set (0-255). + * @returns The socket itself. + */ + setTypeOfService(tos: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`, `socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remotePort: number | undefined; + /** + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + /** + * Half-closes the socket, with one final chunk of data. + * @see {@link Socket.end} for full details. + * @since v0.1.90 + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(buffer: Uint8Array | string, callback?: () => void): this; + /** + * Half-closes the socket, with one final chunk of data. + * @see {@link Socket.end} for full details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + // #region InternalEventEmitter + addListener(eventName: E, listener: (...args: SocketEventMap[E]) => void): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: SocketEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: SocketEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: SocketEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: SocketEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: SocketEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: E, listener: (...args: SocketEventMap[E]) => void): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: SocketEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: SocketEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: SocketEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: SocketEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface ListenOptions extends Abortable { + backlog?: number | undefined; + exclusive?: boolean | undefined; + host?: string | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + reusePort?: boolean | undefined; + path?: string | undefined; + port?: number | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * Optionally overrides all `net.Socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * @default See [stream.getDefaultHighWaterMark()](https://nodejs.org/docs/latest-v25.x/api/stream.html#streamgetdefaulthighwatermarkobjectmode). + * @since v18.17.0, v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * `blockList` can be used for disabling inbound + * access to specific IP addresses, IP ranges, or IP subnets. This does not + * work if the server is behind a reverse proxy, NAT, etc. because the address + * checked against the block list is the address of the proxy, or the one + * specified by the NAT. + * @since v22.13.0 + */ + blockList?: BlockList | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + interface ServerEventMap { + "close": []; + "connection": [socket: Socket]; + "error": [err: Error]; + "listening": []; + "drop": [data?: DropArgument]; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server implements EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.error('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + readonly listening: boolean; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + interface Server extends InternalEventEmitter {} + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + /** + * The list of rules added to the blocklist. + * @since v15.0.0, v14.18.0 + */ + rules: readonly string[]; + /** + * Returns `true` if the `value` is a `net.BlockList`. + * @since v22.13.0 + * @param value Any JS value + */ + static isBlockList(value: unknown): value is BlockList; + /** + * ```js + * const blockList = new net.BlockList(); + * const data = [ + * 'Subnet: IPv4 192.168.1.0/24', + * 'Address: IPv4 10.0.0.5', + * 'Range: IPv4 192.168.2.1-192.168.2.10', + * 'Range: IPv4 10.0.0.1-10.0.0.10', + * ]; + * blockList.fromJSON(data); + * blockList.fromJSON(JSON.stringify(data)); + * ``` + * @since v24.5.0 + * @experimental + */ + fromJSON(data: string | readonly string[]): void; + /** + * @since v24.5.0 + * @experimental + */ + toJSON(): readonly string[]; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * import net from 'node:net'; + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```bash + * telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```bash + * nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @param value The new default value. + * The initial default value is `true`, unless the command line option + * `--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `500` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`. + * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option. + * @since v19.8.0, v18.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line + * option `--network-family-autoselection-attempt-timeout`. + * @since v19.8.0, v18.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + /** + * @since v22.13.0 + * @param input An input string containing an IP address and optional port, + * e.g. `123.1.2.3:1234` or `[1::1]:1234`. + * @returns Returns a `SocketAddress` if parsing was successful. + * Otherwise returns `undefined`. + */ + static parse(input: string): SocketAddress | undefined; + } +} +declare module "net" { + export * from "node:net"; +} diff --git a/node_modules/@types/node/os.d.ts b/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..562c463 --- /dev/null +++ b/node_modules/@types/node/os.d.ts @@ -0,0 +1,498 @@ +declare module "node:os" { + import { NonSharedBuffer } from "buffer"; + interface CpuInfo { + model: string; + speed: number; + times: { + /** The number of milliseconds the CPU has spent in user mode. */ + user: number; + /** The number of milliseconds the CPU has spent in nice mode. */ + nice: number; + /** The number of milliseconds the CPU has spent in sys mode. */ + sys: number; + /** The number of milliseconds the CPU has spent in idle mode. */ + idle: number; + /** The number of milliseconds the CPU has spent in irq mode. */ + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + scopeid?: number; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20, + * }, + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + interface UserInfoOptions { + encoding?: BufferEncoding | "buffer" | undefined; + } + interface UserInfoOptionsWithBufferEncoding extends UserInfoOptions { + encoding: "buffer"; + } + interface UserInfoOptionsWithStringEncoding extends UserInfoOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a [`SystemError`](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options?: UserInfoOptionsWithStringEncoding): UserInfo; + function userInfo(options: UserInfoOptionsWithBufferEncoding): UserInfo; + function userInfo(options: UserInfoOptions): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace dlopen { + const RTLD_LAZY: number; + const RTLD_NOW: number; + const RTLD_GLOBAL: number; + const RTLD_LOCAL: number; + const RTLD_DEEPBIND: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + /** + * The operating system-specific end-of-line marker. + * * `\n` on POSIX + * * `\r\n` on Windows + */ + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, + * `'mips'`, `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`. + * + * The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v25.x/api/process.html#processarch). + * @since v0.5.0 + */ + function arch(): NodeJS.Architecture; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, + * `mips`, `mips64`, `ppc64`, `ppc64le`, `s390x`, `i386`, `i686`, `x86_64`. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "os" { + export * from "node:os"; +} diff --git a/node_modules/@types/node/package.json b/node_modules/@types/node/package.json new file mode 100644 index 0000000..83b0e0a --- /dev/null +++ b/node_modules/@types/node/package.json @@ -0,0 +1,155 @@ +{ + "name": "@types/node", + "version": "25.6.0", + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "githubUsername": "Microsoft", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "githubUsername": "jkomyno", + "url": "https://github.com/jkomyno" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "Marcin Kopacz", + "githubUsername": "chyzwar", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "githubUsername": "trivikr", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "githubUsername": "yoursunny", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "githubUsername": "qwelias", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "githubUsername": "addaleax", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "githubUsername": "victorperin", + "url": "https://github.com/victorperin" + }, + { + "name": "NodeJS Contributors", + "githubUsername": "NodeJS", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "githubUsername": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "githubUsername": "mcollina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + }, + { + "name": "René", + "githubUsername": "Renegade334", + "url": "https://github.com/Renegade334" + }, + { + "name": "Yagiz Nizipli", + "githubUsername": "anonrig", + "url": "https://github.com/anonrig" + } + ], + "main": "", + "types": "index.d.ts", + "typesVersions": { + "<=5.6": { + "*": [ + "ts5.6/*" + ] + }, + "<=5.7": { + "*": [ + "ts5.7/*" + ] + } + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~7.19.0" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "753bd9272f1c86686cc2d1bb435a7f033157f700201f64f0319742347e1ca060", + "typeScriptVersion": "5.3" +} \ No newline at end of file diff --git a/node_modules/@types/node/path.d.ts b/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..ae8fd97 --- /dev/null +++ b/node_modules/@types/node/path.d.ts @@ -0,0 +1,178 @@ +declare module "node:path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. If the path is a zero-length string, '.' is returned, representing the current working directory. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + function normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + function resolve(...paths: string[]): string; + /** + * The `path.matchesGlob()` method determines if `path` matches the `pattern`. + * @param path The path to glob-match against. + * @param pattern The glob to check the path against. + * @returns Whether or not the `path` matched the `pattern`. + * @throws {TypeError} if `path` or `pattern` are not strings. + * @since v22.5.0 + */ + function matchesGlob(path: string, pattern: string): boolean; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + function dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + function basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + function extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + const sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + const delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + function parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + function format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + function toNamespacedPath(path: string): string; + } + namespace path { + export { + /** + * The `path.posix` property provides access to POSIX specific implementations of the `path` methods. + * + * The API is accessible via `require('node:path').posix` or `require('node:path/posix')`. + */ + path as posix, + /** + * The `path.win32` property provides access to Windows-specific implementations of the `path` methods. + * + * The API is accessible via `require('node:path').win32` or `require('node:path/win32')`. + */ + path as win32, + }; + } + export = path; +} +declare module "path" { + import path = require("node:path"); + export = path; +} diff --git a/node_modules/@types/node/path/posix.d.ts b/node_modules/@types/node/path/posix.d.ts new file mode 100644 index 0000000..d60f629 --- /dev/null +++ b/node_modules/@types/node/path/posix.d.ts @@ -0,0 +1,8 @@ +declare module "node:path/posix" { + import path = require("node:path"); + export = path.posix; +} +declare module "path/posix" { + import path = require("path"); + export = path.posix; +} diff --git a/node_modules/@types/node/path/win32.d.ts b/node_modules/@types/node/path/win32.d.ts new file mode 100644 index 0000000..e6aa9fa --- /dev/null +++ b/node_modules/@types/node/path/win32.d.ts @@ -0,0 +1,8 @@ +declare module "node:path/win32" { + import path = require("node:path"); + export = path.win32; +} +declare module "path/win32" { + import path = require("path"); + export = path.win32; +} diff --git a/node_modules/@types/node/perf_hooks.d.ts b/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..46e725c --- /dev/null +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,612 @@ +declare module "node:perf_hooks" { + import { InternalEventTargetEventProperties } from "node:events"; + // #region web types + type EntryType = + | "dns" // Node.js only + | "function" // Node.js only + | "gc" // Node.js only + | "http2" // Node.js only + | "http" // Node.js only + | "mark" // available on the Web + | "measure" // available on the Web + | "net" // Node.js only + | "node" // Node.js only + | "resource"; // available on the Web + interface ConnectionTimingInfo { + domainLookupStartTime: number; + domainLookupEndTime: number; + connectionStartTime: number; + connectionEndTime: number; + secureConnectionStartTime: number; + ALPNNegotiatedProtocol: string; + } + interface FetchTimingInfo { + startTime: number; + redirectStartTime: number; + redirectEndTime: number; + postRedirectStartTime: number; + finalServiceWorkerStartTime: number; + finalNetworkRequestStartTime: number; + finalNetworkResponseStartTime: number; + endTime: number; + finalConnectionTimingInfo: ConnectionTimingInfo | null; + encodedBodySize: number; + decodedBodySize: number; + } + type PerformanceEntryList = PerformanceEntry[]; + interface PerformanceMarkOptions { + detail?: any; + startTime?: number; + } + interface PerformanceMeasureOptions { + detail?: any; + duration?: number; + end?: string | number; + start?: string | number; + } + interface PerformanceObserverCallback { + (entries: PerformanceObserverEntryList, observer: PerformanceObserver): void; + } + interface PerformanceObserverInit { + buffered?: boolean; + entryTypes?: EntryType[]; + type?: EntryType; + } + // TODO: remove in next major + /** @deprecated Use `TimerifyOptions` instead. */ + interface PerformanceTimerifyOptions extends TimerifyOptions {} + interface PerformanceEventMap { + "resourcetimingbufferfull": Event; + } + interface Performance extends EventTarget, InternalEventTargetEventProperties { + readonly nodeTiming: PerformanceNodeTiming; + readonly timeOrigin: number; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(resourceTimingName?: string): void; + getEntries(): PerformanceEntryList; + getEntriesByName(name: string, type?: EntryType): PerformanceEntryList; + getEntriesByType(type: EntryType): PerformanceEntryList; + mark(markName: string, markOptions?: PerformanceMarkOptions): PerformanceMark; + markResourceTiming( + timingInfo: FetchTimingInfo, + requestedUrl: string, + initiatorType: string, + global: unknown, + cacheMode: string, + bodyInfo: unknown, + responseStatus: number, + deliveryType?: string, + ): PerformanceResourceTiming; + measure(measureName: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(measureName: string, options: PerformanceMeasureOptions, endMark?: string): PerformanceMeasure; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; + addEventListener( + type: K, + listener: (ev: PerformanceEventMap[K]) => void, + options?: AddEventListenerOptions | boolean, + ): void; + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: AddEventListenerOptions | boolean, + ): void; + removeEventListener( + type: K, + listener: (ev: PerformanceEventMap[K]) => void, + options?: EventListenerOptions | boolean, + ): void; + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: EventListenerOptions | boolean, + ): void; + /** + * This is an alias of `perf_hooks.eventLoopUtilization()`. + * + * _This property is an extension by Node.js. It is not available in Web browsers._ + * @since v14.10.0, v12.19.0 + * @param utilization1 The result of a previous call to + * `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to + * `eventLoopUtilization()` prior to `utilization1`. + */ + eventLoopUtilization( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ): EventLoopUtilization; + /** + * This is an alias of `perf_hooks.timerify()`. + * + * _This property is an extension by Node.js. It is not available in Web browsers._ + * @since v8.5.0 + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + } + var Performance: { + prototype: Performance; + new(): Performance; + }; + interface PerformanceEntry { + readonly duration: number; + readonly entryType: EntryType; + readonly name: string; + readonly startTime: number; + toJSON(): any; + } + var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; + }; + interface PerformanceMark extends PerformanceEntry { + readonly detail: any; + readonly entryType: "mark"; + } + var PerformanceMark: { + prototype: PerformanceMark; + new(markName: string, markOptions?: PerformanceMarkOptions): PerformanceMark; + }; + interface PerformanceMeasure extends PerformanceEntry { + readonly detail: any; + readonly entryType: "measure"; + } + var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; + }; + interface PerformanceObserver { + disconnect(): void; + observe(options: PerformanceObserverInit): void; + takeRecords(): PerformanceEntryList; + } + var PerformanceObserver: { + prototype: PerformanceObserver; + new(callback: PerformanceObserverCallback): PerformanceObserver; + readonly supportedEntryTypes: readonly EntryType[]; + }; + interface PerformanceObserverEntryList { + getEntries(): PerformanceEntryList; + getEntriesByName(name: string, type?: EntryType): PerformanceEntryList; + getEntriesByType(type: EntryType): PerformanceEntryList; + } + var PerformanceObserverEntryList: { + prototype: PerformanceObserverEntryList; + new(): PerformanceObserverEntryList; + }; + interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly decodedBodySize: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly encodedBodySize: number; + readonly entryType: "resource"; + readonly fetchStart: number; + readonly initiatorType: string; + readonly nextHopProtocol: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly responseStatus: number; + readonly secureConnectionStart: number; + readonly transferSize: number; + readonly workerStart: number; + toJSON(): any; + } + var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; + }; + var performance: Performance; + // #endregion + /** + * _This class is an extension by Node.js. It is not available in Web browsers._ + * + * Provides detailed Node.js timing data. + * + * The constructor of this class is not exposed to users directly. + * @since v19.0.0 + */ + class PerformanceNodeEntry extends PerformanceEntry { + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail: any; + readonly entryType: "dns" | "function" | "gc" | "http2" | "http" | "net" | "node"; + } + interface UVMetrics { + /** + * Number of event loop iterations. + */ + readonly loopCount: number; + /** + * Number of events that have been processed by the event handler. + */ + readonly events: number; + /** + * Number of events that were waiting to be processed when the event provider was called. + */ + readonly eventsWaiting: number; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + interface PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + readonly entryType: "node"; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; + /** + * This is a wrapper to the `uv_metrics_info` function. + * It returns the current set of event loop metrics. + * + * It is recommended to use this property inside a function whose execution was + * scheduled using `setImmediate` to avoid collecting metrics before finishing all + * operations scheduled during the current loop iteration. + * @since v22.8.0, v20.18.0 + */ + readonly uvMetricsInfo: UVMetrics; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 + */ + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 + */ + readonly exceedsBigInt: bigint; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly minBigInt: bigint; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + /** + * Disables the update interval timer when the histogram is disposed. + * + * ```js + * const { monitorEventLoopDelay } = require('node:perf_hooks'); + * { + * using hist = monitorEventLoopDelay({ resolution: 20 }); + * hist.enable(); + * // The histogram will be disabled when the block is exited. + * } + * ``` + * @since v24.2.0 + */ + [Symbol.dispose](): void; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * The `eventLoopUtilization()` function returns an object that contains the + * cumulative duration of time the event loop has been both idle and active as a + * high resolution milliseconds timer. The `utilization` value is the calculated + * Event Loop Utilization (ELU). + * + * If bootstrapping has not yet finished on the main thread the properties have + * the value of `0`. The ELU is immediately available on [Worker threads](https://nodejs.org/docs/latest-v25.x/api/worker_threads.html#worker-threads) since + * bootstrap happens within the event loop. + * + * Both `utilization1` and `utilization2` are optional parameters. + * + * If `utilization1` is passed, then the delta between the current call's `active` + * and `idle` times, as well as the corresponding `utilization` value are + * calculated and returned (similar to `process.hrtime()`). + * + * If `utilization1` and `utilization2` are both passed, then the delta is + * calculated between the two arguments. This is a convenience option because, + * unlike `process.hrtime()`, calculating the ELU is more complex than a + * single subtraction. + * + * ELU is similar to CPU utilization, except that it only measures event loop + * statistics and not CPU usage. It represents the percentage of time the event + * loop has spent outside the event loop's event provider (e.g. `epoll_wait`). + * No other CPU idle time is taken into consideration. The following is an example + * of how a mostly idle process will have a high ELU. + * + * ```js + * import { eventLoopUtilization } from 'node:perf_hooks'; + * import { spawnSync } from 'node:child_process'; + * + * setImmediate(() => { + * const elu = eventLoopUtilization(); + * spawnSync('sleep', ['5']); + * console.log(eventLoopUtilization(elu).utilization); + * }); + * ``` + * + * Although the CPU is mostly idle while running this script, the value of + * `utilization` is `1`. This is because the call to + * `child_process.spawnSync()` blocks the event loop from proceeding. + * + * Passing in a user-defined object instead of the result of a previous call to + * `eventLoopUtilization()` will lead to undefined behavior. The return values + * are not guaranteed to reflect any correct state of the event loop. + * @since v25.2.0 + * @param utilization1 The result of a previous call to + * `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to + * `eventLoopUtilization()` prior to `utilization1`. + */ + function eventLoopUtilization( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ): EventLoopUtilization; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * import { monitorEventLoopDelay } from 'node:perf_hooks'; + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface TimerifyOptions { + /** + * A histogram object created using + * `perf_hooks.createHistogram()` that will record runtime durations in + * nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Wraps a function within a new function that measures the running time of the + * wrapped function. A `PerformanceObserver` must be subscribed to the `'function'` + * event type in order for the timing details to be accessed. + * + * ```js + * import { timerify, performance, PerformanceObserver } from 'node:perf_hooks'; + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached + * to the promise and the duration will be reported once the finally handler is + * invoked. + * @since v25.2.0 + */ + function timerify any>(fn: T, options?: TimerifyOptions): T; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + lowest?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + highest?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + // TODO: remove these in a future major + /** @deprecated Use the canonical `PerformanceMarkOptions` instead. */ + interface MarkOptions extends PerformanceMarkOptions {} + /** @deprecated Use the canonical `PerformanceMeasureOptions` instead. */ + interface MeasureOptions extends PerformanceMeasureOptions {} +} +declare module "perf_hooks" { + export * from "node:perf_hooks"; +} diff --git a/node_modules/@types/node/process.d.ts b/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..ea50c94 --- /dev/null +++ b/node_modules/@types/node/process.d.ts @@ -0,0 +1,2175 @@ +declare module "node:process" { + import { Control, MessageOptions, SendHandle } from "node:child_process"; + import { PathLike } from "node:fs"; + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + interface BuiltInModule { + "assert": typeof import("assert"); + "node:assert": typeof import("node:assert"); + "assert/strict": typeof import("assert/strict"); + "node:assert/strict": typeof import("node:assert/strict"); + "async_hooks": typeof import("async_hooks"); + "node:async_hooks": typeof import("node:async_hooks"); + "buffer": typeof import("buffer"); + "node:buffer": typeof import("node:buffer"); + "child_process": typeof import("child_process"); + "node:child_process": typeof import("node:child_process"); + "cluster": typeof import("cluster"); + "node:cluster": typeof import("node:cluster"); + "console": typeof import("console"); + "node:console": typeof import("node:console"); + "constants": typeof import("constants"); + "node:constants": typeof import("node:constants"); + "crypto": typeof import("crypto"); + "node:crypto": typeof import("node:crypto"); + "dgram": typeof import("dgram"); + "node:dgram": typeof import("node:dgram"); + "diagnostics_channel": typeof import("diagnostics_channel"); + "node:diagnostics_channel": typeof import("node:diagnostics_channel"); + "dns": typeof import("dns"); + "node:dns": typeof import("node:dns"); + "dns/promises": typeof import("dns/promises"); + "node:dns/promises": typeof import("node:dns/promises"); + "domain": typeof import("domain"); + "node:domain": typeof import("node:domain"); + "events": typeof import("events"); + "node:events": typeof import("node:events"); + "fs": typeof import("fs"); + "node:fs": typeof import("node:fs"); + "fs/promises": typeof import("fs/promises"); + "node:fs/promises": typeof import("node:fs/promises"); + "http": typeof import("http"); + "node:http": typeof import("node:http"); + "http2": typeof import("http2"); + "node:http2": typeof import("node:http2"); + "https": typeof import("https"); + "node:https": typeof import("node:https"); + "inspector": typeof import("inspector"); + "node:inspector": typeof import("node:inspector"); + "inspector/promises": typeof import("inspector/promises"); + "node:inspector/promises": typeof import("node:inspector/promises"); + "module": typeof import("module"); + "node:module": typeof import("node:module"); + "net": typeof import("net"); + "node:net": typeof import("node:net"); + "os": typeof import("os"); + "node:os": typeof import("node:os"); + "path": typeof import("path"); + "node:path": typeof import("node:path"); + "path/posix": typeof import("path/posix"); + "node:path/posix": typeof import("node:path/posix"); + "path/win32": typeof import("path/win32"); + "node:path/win32": typeof import("node:path/win32"); + "perf_hooks": typeof import("perf_hooks"); + "node:perf_hooks": typeof import("node:perf_hooks"); + "process": typeof import("process"); + "node:process": typeof import("node:process"); + "punycode": typeof import("punycode"); + "node:punycode": typeof import("node:punycode"); + "querystring": typeof import("querystring"); + "node:querystring": typeof import("node:querystring"); + "node:quic": typeof import("node:quic"); + "readline": typeof import("readline"); + "node:readline": typeof import("node:readline"); + "readline/promises": typeof import("readline/promises"); + "node:readline/promises": typeof import("node:readline/promises"); + "repl": typeof import("repl"); + "node:repl": typeof import("node:repl"); + "node:sea": typeof import("node:sea"); + "node:sqlite": typeof import("node:sqlite"); + "stream": typeof import("stream"); + "node:stream": typeof import("node:stream"); + "stream/consumers": typeof import("stream/consumers"); + "node:stream/consumers": typeof import("node:stream/consumers"); + "stream/promises": typeof import("stream/promises"); + "node:stream/promises": typeof import("node:stream/promises"); + "stream/web": typeof import("stream/web"); + "node:stream/web": typeof import("node:stream/web"); + "string_decoder": typeof import("string_decoder"); + "node:string_decoder": typeof import("node:string_decoder"); + "node:test": typeof import("node:test"); + "node:test/reporters": typeof import("node:test/reporters"); + "timers": typeof import("timers"); + "node:timers": typeof import("node:timers"); + "timers/promises": typeof import("timers/promises"); + "node:timers/promises": typeof import("node:timers/promises"); + "tls": typeof import("tls"); + "node:tls": typeof import("node:tls"); + "trace_events": typeof import("trace_events"); + "node:trace_events": typeof import("node:trace_events"); + "tty": typeof import("tty"); + "node:tty": typeof import("node:tty"); + "url": typeof import("url"); + "node:url": typeof import("node:url"); + "util": typeof import("util"); + "node:util": typeof import("node:util"); + "util/types": typeof import("util/types"); + "node:util/types": typeof import("node:util/types"); + "v8": typeof import("v8"); + "node:v8": typeof import("node:v8"); + "vm": typeof import("vm"); + "node:vm": typeof import("node:vm"); + "wasi": typeof import("wasi"); + "node:wasi": typeof import("node:wasi"); + "worker_threads": typeof import("worker_threads"); + "node:worker_threads": typeof import("node:worker_threads"); + "zlib": typeof import("zlib"); + "node:zlib": typeof import("node:zlib"); + } + type SignalsEventMap = { [S in NodeJS.Signals]: [signal: S] }; + interface ProcessEventMap extends SignalsEventMap { + "beforeExit": [code: number]; + "disconnect": []; + "exit": [code: number]; + "message": [ + message: object | boolean | number | string | null, + sendHandle: SendHandle | undefined, + ]; + "rejectionHandled": [promise: Promise]; + "uncaughtException": [error: Error, origin: NodeJS.UncaughtExceptionOrigin]; + "uncaughtExceptionMonitor": [error: Error, origin: NodeJS.UncaughtExceptionOrigin]; + "unhandledRejection": [reason: unknown, promise: Promise]; + "warning": [warning: Error]; + "worker": [worker: Worker]; + "workerMessage": [value: any, source: number]; + } + global { + var process: NodeJS.Process; + namespace process { + export { ProcessEventMap }; + } + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ + rss: number; + /** + * Refers to V8's memory usage. + */ + heapTotal: number; + /** + * Refers to V8's memory usage. + */ + heapUsed: number; + external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessFeatures { + /** + * A boolean value that is `true` if the current Node.js build is caching builtin modules. + * @since v12.0.0 + */ + readonly cached_builtins: boolean; + /** + * A boolean value that is `true` if the current Node.js build is a debug build. + * @since v0.5.5 + */ + readonly debug: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes the inspector. + * @since v11.10.0 + */ + readonly inspector: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for IPv6. + * + * Since all Node.js builds have IPv6 support, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly ipv6: boolean; + /** + * A boolean value that is `true` if the current Node.js build supports + * [loading ECMAScript modules using `require()`](https://nodejs.org/docs/latest-v25.x/api/modules.md#loading-ecmascript-modules-using-require). + * @since v22.10.0 + */ + readonly require_module: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for TLS. + * @since v0.5.3 + */ + readonly tls: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for ALPN in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional ALPN support. + * This value is therefore identical to that of `process.features.tls`. + * @since v4.8.0 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_alpn: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for OCSP in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional OCSP support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.11.13 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_ocsp: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for SNI in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional SNI support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.5.3 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_sni: boolean; + /** + * A value that is `"strip"` by default, + * `"transform"` if Node.js is run with `--experimental-transform-types`, and `false` if + * Node.js is run with `--no-strip-types`. + * @since v22.10.0 + */ + readonly typescript: "strip" | "transform" | false; + /** + * A boolean value that is `true` if the current Node.js build includes support for libuv. + * + * Since it's not possible to build Node.js without libuv, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly uv: boolean; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "loong64" + | "mips" + | "mipsel" + | "ppc64" + | "riscv64" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['beforeExit']) => { ... }; + * ``` + */ + type BeforeExitListener = (...args: ProcessEventMap["beforeExit"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['disconnect']) => { ... }; + * ``` + */ + type DisconnectListener = (...args: ProcessEventMap["disconnect"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['exit']) => { ... }; + * ``` + */ + type ExitListener = (...args: ProcessEventMap["exit"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['message']) => { ... }; + * ``` + */ + type MessageListener = (...args: ProcessEventMap["message"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['rejectionHandled']) => { ... }; + * ``` + */ + type RejectionHandledListener = (...args: ProcessEventMap["rejectionHandled"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + */ + type SignalsListener = (signal: Signals) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['uncaughtException']) => { ... }; + * ``` + */ + type UncaughtExceptionListener = (...args: ProcessEventMap["uncaughtException"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['unhandledRejection']) => { ... }; + * ``` + */ + type UnhandledRejectionListener = (...args: ProcessEventMap["unhandledRejection"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['warning']) => { ... }; + * ``` + */ + type WarningListener = (...args: ProcessEventMap["warning"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['worker']) => { ... }; + * ``` + */ + type WorkerListener = (...args: ProcessEventMap["worker"]) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict {} + interface HRTime { + /** + * This is the legacy version of {@link process.hrtime.bigint()} + * before bigint was introduced in JavaScript. + * + * The `process.hrtime()` method returns the current high-resolution real time in a `[seconds, nanoseconds]` tuple `Array`, + * where `nanoseconds` is the remaining part of the real time that can't be represented in second precision. + * + * `time` is an optional parameter that must be the result of a previous `process.hrtime()` call to diff with the current time. + * If the parameter passed in is not a tuple `Array`, a TypeError will be thrown. + * Passing in a user-defined array instead of the result of a previous call to `process.hrtime()` will lead to undefined behavior. + * + * These times are relative to an arbitrary time in the past, + * and not related to the time of day and therefore not subject to clock drift. + * The primary use is for measuring performance between intervals: + * ```js + * const { hrtime } = require('node:process'); + * const NS_PER_SEC = 1e9; + * const time = hrtime(); + * // [ 1800216, 25 ] + * + * setTimeout(() => { + * const diff = hrtime(time); + * // [ 1, 552 ] + * + * console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); + * // Benchmark took 1000000552 nanoseconds + * }, 1000); + * ``` + * @since 0.7.6 + * @legacy Use {@link process.hrtime.bigint()} instead. + * @param time The result of a previous call to `process.hrtime()` + */ + (time?: [number, number]): [number, number]; + /** + * The `bigint` version of the {@link process.hrtime()} method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike {@link process.hrtime()}, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + * @since v10.7.0 + */ + bigint(): bigint; + } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } + interface ProcessReport { + /** + * Write reports in a compact format, single-line JSON, more easily consumable by log processing systems + * than the default multi-line format designed for human consumption. + * @since v13.12.0, v12.17.0 + */ + compact: boolean; + /** + * Directory where the report is written. + * The default value is the empty string, indicating that reports are written to the current + * working directory of the Node.js process. + */ + directory: string; + /** + * Filename where the report is written. If set to the empty string, the output filename will be comprised + * of a timestamp, PID, and sequence number. The default value is the empty string. + */ + filename: string; + /** + * Returns a JavaScript Object representation of a diagnostic report for the running process. + * The report's JavaScript stack trace is taken from `err`, if present. + */ + getReport(err?: Error): object; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * If true, a diagnostic report is generated without the environment variables. + * @default false + */ + excludeEnv: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from `err`, if present. + * + * If the value of filename is set to `'stdout'` or `'stderr'`, the report is written + * to the stdout or stderr of the process respectively. + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param err A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string, err?: Error): string; + writeReport(err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. If a [program entry point](https://nodejs.org/docs/latest-v25.x/api/cli.html#program-entry-point) was provided, the second element + * will be the absolute path to it. The remaining elements are additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --icu-data-dir=./foo --require ./bar.js script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ["--icu-data-dir=./foo", "--require", "./bar.js"] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v25.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and `process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number | string | null): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @default undefined + * @since v0.11.8 + */ + exitCode: number | string | null | undefined; + finalization: { + /** + * This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected. + * If the object `ref` was garbage collected before the `exit` event is emitted, the callback will be removed from the finalization registry, and it will not be called on process exit. + * + * Inside the callback you can release the resources allocated by the `ref` object. + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, + * this means that there is a possibility that the callback will not be called under special circumstances. + * + * The idea of ​​this function is to help you free up resources when the starts process exiting, but also let the object be garbage collected if it is no longer being used. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + register(ref: T, callback: (ref: T, event: "exit") => void): void; + /** + * This function behaves exactly like the `register`, except that the callback will be called when the process emits the `beforeExit` event if `ref` object was not garbage collected. + * + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, this means that there is a possibility that the callback will not be called under special circumstances. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + registerBeforeExit(ref: T, callback: (ref: T, event: "beforeExit") => void): void; + /** + * This function remove the register of the object from the finalization registry, so the callback will not be called anymore. + * @param ref The reference to the resource that was registered previously. + * @since v22.5.0 + * @experimental + */ + unregister(ref: object): void; + }; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; + /** + * Provides a way to load built-in modules in a globally available function. + * @param id ID of the built-in module being requested. + */ + getBuiltinModule(id: ID): BuiltInModule[ID]; + getBuiltinModule(id: string): object | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function, `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. + * @since v16.6.0, v14.18.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: PathLike): void; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.threadCpuUsage()` method returns the user and system CPU time usage of + * the current worker thread, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). + * + * The result of a previous call to `process.threadCpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * @since v23.9.0 + * @param previousValue A previous return value from calling + * `process.threadCpuUsage()` + */ + threadCpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the `process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ` memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, + * `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `0` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + */ + constrainedMemory(): number; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v25.x/api/process.html#processavailablememory) for more information. + * @since v20.13.0 + */ + availableMemory(): number; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * The process.noDeprecation property indicates whether the --no-deprecation flag is set on the current Node.js process. + * See the documentation for the ['warning' event](https://nodejs.org/docs/latest/api/process.html#event-warning) and the [emitWarning()](https://nodejs.org/docs/latest/api/process.html#processemitwarningwarning-type-code-ctor) method for more information about this flag's behavior. + */ + noDeprecation?: boolean; + /** + * This API is available through the [--permission](https://nodejs.org/api/cli.html#--permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + readonly features: ProcessFeatures; + /** + * The `process.traceProcessWarnings` property indicates whether the `--trace-warnings` flag + * is set on the current Node.js process. This property allows programmatic control over the + * tracing of warnings, enabling or disabling stack traces for warnings at runtime. + * + * ```js + * // Enable trace warnings + * process.traceProcessWarnings = true; + * + * // Emit a warning with a stack trace + * process.emitWarning('Warning with stack trace'); + * + * // Disable trace warnings + * process.traceProcessWarnings = false; + * ``` + * @since v6.10.0 + */ + traceProcessWarnings: boolean; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. + * If no IPC channel exists, this property is undefined. + * @since v7.1.0 + */ + channel?: Control; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send?( + message: any, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + send?( + message: any, + sendHandle: SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send?( + message: any, + callback: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect?(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return `true` so long as the IPC + * channel is connected and will return `false` after `process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic reports for the current process. + * Additional documentation is available in the [report documentation](https://nodejs.org/docs/latest-v25.x/api/report.html). + * @since v11.8.0 + */ + report: ProcessReport; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * The `process.traceDeprecation` property indicates whether the `--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /** + * An object is "refable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "refable". + */ + ref(maybeRefable: any): void; + /** + * An object is "unrefable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "unref'd". + */ + unref(maybeRefable: any): void; + /** + * Replaces the current process with a new process. + * + * This is achieved by using the `execve` POSIX function and therefore no memory or other + * resources from the current process are preserved, except for the standard input, + * standard output and standard error file descriptor. + * + * All other resources are discarded by the system when the processes are swapped, without triggering + * any exit or close events and without running any cleanup handler. + * + * This function will never return, unless an error occurred. + * + * This function is not available on Windows or IBM i. + * @since v22.15.0 + * @experimental + * @param file The name or path of the executable file to run. + * @param args List of string arguments. No argument can contain a null-byte (`\u0000`). + * @param env Environment key-value pairs. + * No key or value can contain a null-byte (`\u0000`). + * **Default:** `process.env`. + */ + execve?(file: string, args?: readonly string[], env?: ProcessEnv): never; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ProcessEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ProcessEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ProcessEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: ProcessEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: ProcessEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: ProcessEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ProcessEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ProcessEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ProcessEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: ProcessEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ProcessEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + } + } + export = process; +} +declare module "process" { + import process = require("node:process"); + export = process; +} diff --git a/node_modules/@types/node/punycode.d.ts b/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..87fdec9 --- /dev/null +++ b/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,89 @@ +declare module "node:punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "punycode" { + export * from "node:punycode"; +} diff --git a/node_modules/@types/node/querystring.d.ts b/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..6d821a4 --- /dev/null +++ b/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,139 @@ +declare module "node:querystring" { + interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ + maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | bigint + | ReadonlyArray + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```json + * { + * "foo": "bar", + * "abc": ["xyz", "123"] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "querystring" { + export * from "node:querystring"; +} diff --git a/node_modules/@types/node/quic.d.ts b/node_modules/@types/node/quic.d.ts new file mode 100644 index 0000000..7fe6188 --- /dev/null +++ b/node_modules/@types/node/quic.d.ts @@ -0,0 +1,897 @@ +declare module "node:quic" { + import { KeyObject, webcrypto } from "node:crypto"; + import { SocketAddress } from "node:net"; + import { ReadableStream } from "node:stream/web"; + /** + * @since v23.8.0 + */ + type OnSessionCallback = (this: QuicEndpoint, session: QuicSession) => void; + /** + * @since v23.8.0 + */ + type OnStreamCallback = (this: QuicSession, stream: QuicStream) => void; + /** + * @since v23.8.0 + */ + type OnDatagramCallback = (this: QuicSession, datagram: Uint8Array, early: boolean) => void; + /** + * @since v23.8.0 + */ + type OnDatagramStatusCallback = (this: QuicSession, id: bigint, status: "lost" | "acknowledged") => void; + /** + * @since v23.8.0 + */ + type OnPathValidationCallback = ( + this: QuicSession, + result: "success" | "failure" | "aborted", + newLocalAddress: SocketAddress, + newRemoteAddress: SocketAddress, + oldLocalAddress: SocketAddress, + oldRemoteAddress: SocketAddress, + preferredAddress: boolean, + ) => void; + /** + * @since v23.8.0 + */ + type OnSessionTicketCallback = (this: QuicSession, ticket: object) => void; + /** + * @since v23.8.0 + */ + type OnVersionNegotiationCallback = ( + this: QuicSession, + version: number, + requestedVersions: number[], + supportedVersions: number[], + ) => void; + /** + * @since v23.8.0 + */ + type OnHandshakeCallback = ( + this: QuicSession, + sni: string, + alpn: string, + cipher: string, + cipherVersion: string, + validationErrorReason: string, + validationErrorCode: number, + earlyDataAccepted: boolean, + ) => void; + /** + * @since v23.8.0 + */ + type OnBlockedCallback = (this: QuicStream) => void; + /** + * @since v23.8.0 + */ + type OnStreamErrorCallback = (this: QuicStream, error: any) => void; + /** + * @since v23.8.0 + */ + interface TransportParams { + /** + * The preferred IPv4 address to advertise. + * @since v23.8.0 + */ + preferredAddressIpv4?: SocketAddress | undefined; + /** + * The preferred IPv6 address to advertise. + * @since v23.8.0 + */ + preferredAddressIpv6?: SocketAddress | undefined; + /** + * @since v23.8.0 + */ + initialMaxStreamDataBidiLocal?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + initialMaxStreamDataBidiRemote?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + initialMaxStreamDataUni?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + initialMaxData?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + initialMaxStreamsBidi?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + initialMaxStreamsUni?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + maxIdleTimeout?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + activeConnectionIDLimit?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + ackDelayExponent?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + maxAckDelay?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + maxDatagramFrameSize?: bigint | number | undefined; + } + /** + * @since v23.8.0 + */ + interface SessionOptions { + /** + * An endpoint to use. + * @since v23.8.0 + */ + endpoint?: EndpointOptions | QuicEndpoint | undefined; + /** + * The ALPN protocol identifier. + * @since v23.8.0 + */ + alpn?: string | undefined; + /** + * The CA certificates to use for sessions. + * @since v23.8.0 + */ + ca?: ArrayBuffer | NodeJS.ArrayBufferView | ReadonlyArray | undefined; + /** + * Specifies the congestion control algorithm that will be used. + * Must be set to one of either `'reno'`, `'cubic'`, or `'bbr'`. + * + * This is an advanced option that users typically won't have need to specify. + * @since v23.8.0 + */ + cc?: `${constants.cc}` | undefined; + /** + * The TLS certificates to use for sessions. + * @since v23.8.0 + */ + certs?: ArrayBuffer | NodeJS.ArrayBufferView | ReadonlyArray | undefined; + /** + * The list of supported TLS 1.3 cipher algorithms. + * @since v23.8.0 + */ + ciphers?: string | undefined; + /** + * The CRL to use for sessions. + * @since v23.8.0 + */ + crl?: ArrayBuffer | NodeJS.ArrayBufferView | ReadonlyArray | undefined; + /** + * The list of support TLS 1.3 cipher groups. + * @since v23.8.0 + */ + groups?: string | undefined; + /** + * True to enable TLS keylogging output. + * @since v23.8.0 + */ + keylog?: boolean | undefined; + /** + * The TLS crypto keys to use for sessions. + * @since v23.8.0 + */ + keys?: KeyObject | webcrypto.CryptoKey | ReadonlyArray | undefined; + /** + * Specifies the maximum UDP packet payload size. + * @since v23.8.0 + */ + maxPayloadSize?: bigint | number | undefined; + /** + * Specifies the maximum stream flow-control window size. + * @since v23.8.0 + */ + maxStreamWindow?: bigint | number | undefined; + /** + * Specifies the maximum session flow-control window size. + * @since v23.8.0 + */ + maxWindow?: bigint | number | undefined; + /** + * The minimum QUIC version number to allow. This is an advanced option that users + * typically won't have need to specify. + * @since v23.8.0 + */ + minVersion?: number | undefined; + /** + * When the remote peer advertises a preferred address, this option specifies whether + * to use it or ignore it. + * @since v23.8.0 + */ + preferredAddressPolicy?: "use" | "ignore" | "default" | undefined; + /** + * True if qlog output should be enabled. + * @since v23.8.0 + */ + qlog?: boolean | undefined; + /** + * A session ticket to use for 0RTT session resumption. + * @since v23.8.0 + */ + sessionTicket?: NodeJS.ArrayBufferView | undefined; + /** + * Specifies the maximum number of milliseconds a TLS handshake is permitted to take + * to complete before timing out. + * @since v23.8.0 + */ + handshakeTimeout?: bigint | number | undefined; + /** + * The peer server name to target. + * @since v23.8.0 + */ + sni?: string | undefined; + /** + * True to enable TLS tracing output. + * @since v23.8.0 + */ + tlsTrace?: boolean | undefined; + /** + * The QUIC transport parameters to use for the session. + * @since v23.8.0 + */ + transportParams?: TransportParams | undefined; + /** + * Specifies the maximum number of unacknowledged packets a session should allow. + * @since v23.8.0 + */ + unacknowledgedPacketThreshold?: bigint | number | undefined; + /** + * True to require verification of TLS client certificate. + * @since v23.8.0 + */ + verifyClient?: boolean | undefined; + /** + * True to require private key verification. + * @since v23.8.0 + */ + verifyPrivateKey?: boolean | undefined; + /** + * The QUIC version number to use. This is an advanced option that users typically + * won't have need to specify. + * @since v23.8.0 + */ + version?: number | undefined; + } + /** + * Initiate a new client-side session. + * + * ```js + * import { connect } from 'node:quic'; + * import { Buffer } from 'node:buffer'; + * + * const enc = new TextEncoder(); + * const alpn = 'foo'; + * const client = await connect('123.123.123.123:8888', { alpn }); + * await client.createUnidirectionalStream({ + * body: enc.encode('hello world'), + * }); + * ``` + * + * By default, every call to `connect(...)` will create a new local + * `QuicEndpoint` instance bound to a new random local IP port. To + * specify the exact local address to use, or to multiplex multiple + * QUIC sessions over a single local port, pass the `endpoint` option + * with either a `QuicEndpoint` or `EndpointOptions` as the argument. + * + * ```js + * import { QuicEndpoint, connect } from 'node:quic'; + * + * const endpoint = new QuicEndpoint({ + * address: '127.0.0.1:1234', + * }); + * + * const client = await connect('123.123.123.123:8888', { endpoint }); + * ``` + * @since v23.8.0 + */ + function connect(address: string | SocketAddress, options?: SessionOptions): Promise; + /** + * Configures the endpoint to listen as a server. When a new session is initiated by + * a remote peer, the given `onsession` callback will be invoked with the created + * session. + * + * ```js + * import { listen } from 'node:quic'; + * + * const endpoint = await listen((session) => { + * // ... handle the session + * }); + * + * // Closing the endpoint allows any sessions open when close is called + * // to complete naturally while preventing new sessions from being + * // initiated. Once all existing sessions have finished, the endpoint + * // will be destroyed. The call returns a promise that is resolved once + * // the endpoint is destroyed. + * await endpoint.close(); + * ``` + * + * By default, every call to `listen(...)` will create a new local + * `QuicEndpoint` instance bound to a new random local IP port. To + * specify the exact local address to use, or to multiplex multiple + * QUIC sessions over a single local port, pass the `endpoint` option + * with either a `QuicEndpoint` or `EndpointOptions` as the argument. + * + * At most, any single `QuicEndpoint` can only be configured to listen as + * a server once. + * @since v23.8.0 + */ + function listen(onsession: OnSessionCallback, options?: SessionOptions): Promise; + /** + * The endpoint configuration options passed when constructing a new `QuicEndpoint` instance. + * @since v23.8.0 + */ + interface EndpointOptions { + /** + * If not specified the endpoint will bind to IPv4 `localhost` on a random port. + * @since v23.8.0 + */ + address?: SocketAddress | string | undefined; + /** + * The endpoint maintains an internal cache of validated socket addresses as a + * performance optimization. This option sets the maximum number of addresses + * that are cache. This is an advanced option that users typically won't have + * need to specify. + * @since v23.8.0 + */ + addressLRUSize?: bigint | number | undefined; + /** + * When `true`, indicates that the endpoint should bind only to IPv6 addresses. + * @since v23.8.0 + */ + ipv6Only?: boolean | undefined; + /** + * Specifies the maximum number of concurrent sessions allowed per remote peer address. + * @since v23.8.0 + */ + maxConnectionsPerHost?: bigint | number | undefined; + /** + * Specifies the maximum total number of concurrent sessions. + * @since v23.8.0 + */ + maxConnectionsTotal?: bigint | number | undefined; + /** + * Specifies the maximum number of QUIC retry attempts allowed per remote peer address. + * @since v23.8.0 + */ + maxRetries?: bigint | number | undefined; + /** + * Specifies the maximum number of stateless resets that are allowed per remote peer address. + * @since v23.8.0 + */ + maxStatelessResetsPerHost?: bigint | number | undefined; + /** + * Specifies the length of time a QUIC retry token is considered valid. + * @since v23.8.0 + */ + retryTokenExpiration?: bigint | number | undefined; + /** + * Specifies the 16-byte secret used to generate QUIC retry tokens. + * @since v23.8.0 + */ + resetTokenSecret?: NodeJS.ArrayBufferView | undefined; + /** + * Specifies the length of time a QUIC token is considered valid. + * @since v23.8.0 + */ + tokenExpiration?: bigint | number | undefined; + /** + * Specifies the 16-byte secret used to generate QUIC tokens. + * @since v23.8.0 + */ + tokenSecret?: NodeJS.ArrayBufferView | undefined; + /** + * @since v23.8.0 + */ + udpReceiveBufferSize?: number | undefined; + /** + * @since v23.8.0 + */ + udpSendBufferSize?: number | undefined; + /** + * @since v23.8.0 + */ + udpTTL?: number | undefined; + /** + * When `true`, requires that the endpoint validate peer addresses using retry packets + * while establishing a new connection. + * @since v23.8.0 + */ + validateAddress?: boolean | undefined; + } + /** + * A `QuicEndpoint` encapsulates the local UDP-port binding for QUIC. It can be + * used as both a client and a server. + * @since v23.8.0 + */ + class QuicEndpoint implements AsyncDisposable { + constructor(options?: EndpointOptions); + /** + * The local UDP socket address to which the endpoint is bound, if any. + * + * If the endpoint is not currently bound then the value will be `undefined`. Read only. + * @since v23.8.0 + */ + readonly address: SocketAddress | undefined; + /** + * When `endpoint.busy` is set to true, the endpoint will temporarily reject + * new sessions from being created. Read/write. + * + * ```js + * // Mark the endpoint busy. New sessions will be prevented. + * endpoint.busy = true; + * + * // Mark the endpoint free. New session will be allowed. + * endpoint.busy = false; + * ``` + * + * The `busy` property is useful when the endpoint is under heavy load and needs to + * temporarily reject new sessions while it catches up. + * @since v23.8.0 + */ + busy: boolean; + /** + * Gracefully close the endpoint. The endpoint will close and destroy itself when + * all currently open sessions close. Once called, new sessions will be rejected. + * + * Returns a promise that is fulfilled when the endpoint is destroyed. + * @since v23.8.0 + */ + close(): Promise; + /** + * A promise that is fulfilled when the endpoint is destroyed. This will be the same promise that is + * returned by the `endpoint.close()` function. Read only. + * @since v23.8.0 + */ + readonly closed: Promise; + /** + * True if `endpoint.close()` has been called and closing the endpoint has not yet completed. + * Read only. + * @since v23.8.0 + */ + readonly closing: boolean; + /** + * Forcefully closes the endpoint by forcing all open sessions to be immediately + * closed. + * @since v23.8.0 + */ + destroy(error?: any): void; + /** + * True if `endpoint.destroy()` has been called. Read only. + * @since v23.8.0 + */ + readonly destroyed: boolean; + /** + * The statistics collected for an active session. Read only. + * @since v23.8.0 + */ + readonly stats: QuicEndpoint.Stats; + /** + * Calls `endpoint.close()` and returns a promise that fulfills when the + * endpoint has closed. + * @since v23.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + namespace QuicEndpoint { + /** + * A view of the collected statistics for an endpoint. + * @since v23.8.0 + */ + class Stats { + private constructor(); + /** + * A timestamp indicating the moment the endpoint was created. Read only. + * @since v23.8.0 + */ + readonly createdAt: bigint; + /** + * A timestamp indicating the moment the endpoint was destroyed. Read only. + * @since v23.8.0 + */ + readonly destroyedAt: bigint; + /** + * The total number of bytes received by this endpoint. Read only. + * @since v23.8.0 + */ + readonly bytesReceived: bigint; + /** + * The total number of bytes sent by this endpoint. Read only. + * @since v23.8.0 + */ + readonly bytesSent: bigint; + /** + * The total number of QUIC packets successfully received by this endpoint. Read only. + * @since v23.8.0 + */ + readonly packetsReceived: bigint; + /** + * The total number of QUIC packets successfully sent by this endpoint. Read only. + * @since v23.8.0 + */ + readonly packetsSent: bigint; + /** + * The total number of peer-initiated sessions received by this endpoint. Read only. + * @since v23.8.0 + */ + readonly serverSessions: bigint; + /** + * The total number of sessions initiated by this endpoint. Read only. + * @since v23.8.0 + */ + readonly clientSessions: bigint; + /** + * The total number of times an initial packet was rejected due to the + * endpoint being marked busy. Read only. + * @since v23.8.0 + */ + readonly serverBusyCount: bigint; + /** + * The total number of QUIC retry attempts on this endpoint. Read only. + * @since v23.8.0 + */ + readonly retryCount: bigint; + /** + * The total number sessions rejected due to QUIC version mismatch. Read only. + * @since v23.8.0 + */ + readonly versionNegotiationCount: bigint; + /** + * The total number of stateless resets handled by this endpoint. Read only. + * @since v23.8.0 + */ + readonly statelessResetCount: bigint; + /** + * The total number of sessions that were closed before handshake completed. Read only. + * @since v23.8.0 + */ + readonly immediateCloseCount: bigint; + } + } + interface CreateStreamOptions { + body?: ArrayBuffer | NodeJS.ArrayBufferView | Blob | undefined; + sendOrder?: number | undefined; + } + interface SessionPath { + local: SocketAddress; + remote: SocketAddress; + } + /** + * A `QuicSession` represents the local side of a QUIC connection. + * @since v23.8.0 + */ + class QuicSession implements AsyncDisposable { + private constructor(); + /** + * Initiate a graceful close of the session. Existing streams will be allowed + * to complete but no new streams will be opened. Once all streams have closed, + * the session will be destroyed. The returned promise will be fulfilled once + * the session has been destroyed. + * @since v23.8.0 + */ + close(): Promise; + /** + * A promise that is fulfilled once the session is destroyed. + * @since v23.8.0 + */ + readonly closed: Promise; + /** + * Immediately destroy the session. All streams will be destroys and the + * session will be closed. + * @since v23.8.0 + */ + destroy(error?: any): void; + /** + * True if `session.destroy()` has been called. Read only. + * @since v23.8.0 + */ + readonly destroyed: boolean; + /** + * The endpoint that created this session. Read only. + * @since v23.8.0 + */ + readonly endpoint: QuicEndpoint; + /** + * The callback to invoke when a new stream is initiated by a remote peer. Read/write. + * @since v23.8.0 + */ + onstream: OnStreamCallback | undefined; + /** + * The callback to invoke when a new datagram is received from a remote peer. Read/write. + * @since v23.8.0 + */ + ondatagram: OnDatagramCallback | undefined; + /** + * The callback to invoke when the status of a datagram is updated. Read/write. + * @since v23.8.0 + */ + ondatagramstatus: OnDatagramStatusCallback | undefined; + /** + * The callback to invoke when the path validation is updated. Read/write. + * @since v23.8.0 + */ + onpathvalidation: OnPathValidationCallback | undefined; + /** + * The callback to invoke when a new session ticket is received. Read/write. + * @since v23.8.0 + */ + onsessionticket: OnSessionTicketCallback | undefined; + /** + * The callback to invoke when a version negotiation is initiated. Read/write. + * @since v23.8.0 + */ + onversionnegotiation: OnVersionNegotiationCallback | undefined; + /** + * The callback to invoke when the TLS handshake is completed. Read/write. + * @since v23.8.0 + */ + onhandshake: OnHandshakeCallback | undefined; + /** + * Open a new bidirectional stream. If the `body` option is not specified, + * the outgoing stream will be half-closed. + * @since v23.8.0 + */ + createBidirectionalStream(options?: CreateStreamOptions): Promise; + /** + * Open a new unidirectional stream. If the `body` option is not specified, + * the outgoing stream will be closed. + * @since v23.8.0 + */ + createUnidirectionalStream(options?: CreateStreamOptions): Promise; + /** + * The local and remote socket addresses associated with the session. Read only. + * @since v23.8.0 + */ + path: SessionPath | undefined; + /** + * Sends an unreliable datagram to the remote peer, returning the datagram ID. + * If the datagram payload is specified as an `ArrayBufferView`, then ownership of + * that view will be transfered to the underlying stream. + * @since v23.8.0 + */ + sendDatagram(datagram: string | NodeJS.ArrayBufferView): bigint; + /** + * Return the current statistics for the session. Read only. + * @since v23.8.0 + */ + readonly stats: QuicSession.Stats; + /** + * Initiate a key update for the session. + * @since v23.8.0 + */ + updateKey(): void; + /** + * Calls `session.close()` and returns a promise that fulfills when the + * session has closed. + * @since v23.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + namespace QuicSession { + /** + * @since v23.8.0 + */ + class Stats { + private constructor(); + /** + * @since v23.8.0 + */ + readonly createdAt: bigint; + /** + * @since v23.8.0 + */ + readonly closingAt: bigint; + /** + * @since v23.8.0 + */ + readonly handshakeCompletedAt: bigint; + /** + * @since v23.8.0 + */ + readonly handshakeConfirmedAt: bigint; + /** + * @since v23.8.0 + */ + readonly bytesReceived: bigint; + /** + * @since v23.8.0 + */ + readonly bytesSent: bigint; + /** + * @since v23.8.0 + */ + readonly bidiInStreamCount: bigint; + /** + * @since v23.8.0 + */ + readonly bidiOutStreamCount: bigint; + /** + * @since v23.8.0 + */ + readonly uniInStreamCount: bigint; + /** + * @since v23.8.0 + */ + readonly uniOutStreamCount: bigint; + /** + * @since v23.8.0 + */ + readonly maxBytesInFlights: bigint; + /** + * @since v23.8.0 + */ + readonly bytesInFlight: bigint; + /** + * @since v23.8.0 + */ + readonly blockCount: bigint; + /** + * @since v23.8.0 + */ + readonly cwnd: bigint; + /** + * @since v23.8.0 + */ + readonly latestRtt: bigint; + /** + * @since v23.8.0 + */ + readonly minRtt: bigint; + /** + * @since v23.8.0 + */ + readonly rttVar: bigint; + /** + * @since v23.8.0 + */ + readonly smoothedRtt: bigint; + /** + * @since v23.8.0 + */ + readonly ssthresh: bigint; + /** + * @since v23.8.0 + */ + readonly datagramsReceived: bigint; + /** + * @since v23.8.0 + */ + readonly datagramsSent: bigint; + /** + * @since v23.8.0 + */ + readonly datagramsAcknowledged: bigint; + /** + * @since v23.8.0 + */ + readonly datagramsLost: bigint; + } + } + /** + * @since v23.8.0 + */ + class QuicStream { + private constructor(); + /** + * A promise that is fulfilled when the stream is fully closed. + * @since v23.8.0 + */ + readonly closed: Promise; + /** + * Immediately and abruptly destroys the stream. + * @since v23.8.0 + */ + destroy(error?: any): void; + /** + * True if `stream.destroy()` has been called. + * @since v23.8.0 + */ + readonly destroyed: boolean; + /** + * The directionality of the stream. Read only. + * @since v23.8.0 + */ + readonly direction: "bidi" | "uni"; + /** + * The stream ID. Read only. + * @since v23.8.0 + */ + readonly id: bigint; + /** + * The callback to invoke when the stream is blocked. Read/write. + * @since v23.8.0 + */ + onblocked: OnBlockedCallback | undefined; + /** + * The callback to invoke when the stream is reset. Read/write. + * @since v23.8.0 + */ + onreset: OnStreamErrorCallback | undefined; + /** + * @since v23.8.0 + */ + readonly readable: ReadableStream; + /** + * The session that created this stream. Read only. + * @since v23.8.0 + */ + readonly session: QuicSession; + /** + * The current statistics for the stream. Read only. + * @since v23.8.0 + */ + readonly stats: QuicStream.Stats; + } + namespace QuicStream { + /** + * @since v23.8.0 + */ + class Stats { + private constructor(); + /** + * @since v23.8.0 + */ + readonly ackedAt: bigint; + /** + * @since v23.8.0 + */ + readonly bytesReceived: bigint; + /** + * @since v23.8.0 + */ + readonly bytesSent: bigint; + /** + * @since v23.8.0 + */ + readonly createdAt: bigint; + /** + * @since v23.8.0 + */ + readonly destroyedAt: bigint; + /** + * @since v23.8.0 + */ + readonly finalSize: bigint; + /** + * @since v23.8.0 + */ + readonly isConnected: bigint; + /** + * @since v23.8.0 + */ + readonly maxOffset: bigint; + /** + * @since v23.8.0 + */ + readonly maxOffsetAcknowledged: bigint; + /** + * @since v23.8.0 + */ + readonly maxOffsetReceived: bigint; + /** + * @since v23.8.0 + */ + readonly openedAt: bigint; + /** + * @since v23.8.0 + */ + readonly receivedAt: bigint; + } + } + namespace constants { + enum cc { + RENO = "reno", + CUBIC = "cubic", + BBR = "bbr", + } + const DEFAULT_CIPHERS: string; + const DEFAULT_GROUPS: string; + } +} diff --git a/node_modules/@types/node/readline.d.ts b/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..5042975 --- /dev/null +++ b/node_modules/@types/node/readline.d.ts @@ -0,0 +1,507 @@ +declare module "node:readline" { + import { Abortable, EventEmitter, InternalEventEmitter } from "node:events"; + interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + interface InterfaceEventMap { + "close": []; + "error": [error: Error]; + "history": [history: string[]]; + "line": [input: string]; + "pause": []; + "resume": []; + "SIGCONT": []; + "SIGINT": []; + "SIGTSTP": []; + } + /** + * Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a + * single `input` [Readable](https://nodejs.org/docs/latest-v25.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v25.x/api/stream.html#writable-streams) stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + class Interface implements EventEmitter, Disposable { + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' '), + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * Alias for `rl.close()`. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s `input` _as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } + interface Interface extends InternalEventEmitter {} + type ReadLine = Interface; // type forwarded for backwards compatibility + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + type CompleterResult = [string[], string]; + interface ReadLineOptions { + /** + * The [`Readable`](https://nodejs.org/docs/latest-v25.x/api/stream.html#readable-streams) stream to listen to + */ + input: NodeJS.ReadableStream; + /** + * The [`Writable`](https://nodejs.org/docs/latest-v25.x/api/stream.html#writable-streams) stream to write readline data to. + */ + output?: NodeJS.WritableStream | undefined; + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * `true` if the `input` and `output` streams should be treated like a TTY, + * and have ANSI/VT100 escape codes written to it. + * Default: checking `isTTY` on the `output` stream upon instantiation. + */ + terminal?: boolean | undefined; + /** + * Initial list of history lines. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + /** + * Maximum number of history lines retained. + * To disable the history set this value to `0`. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default 30 + */ + historySize?: number | undefined; + /** + * If `true`, when a new input line added to the history list duplicates an older one, + * this removes the older line from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + /** + * The prompt string to use. + * @default "> " + */ + prompt?: string | undefined; + /** + * If the delay between `\r` and `\n` exceeds `crlfDelay` milliseconds, + * both `\r` and `\n` will be treated as separate end-of-line input. + * `crlfDelay` will be coerced to a number no less than `100`. + * It can be set to `Infinity`, in which case + * `\r` followed by `\n` will always be considered a single newline + * (which may be reasonable for [reading files](https://nodejs.org/docs/latest-v25.x/api/readline.html#example-read-file-stream-line-by-line) with `\r\n` line delimiter). + * @default 100 + */ + crlfDelay?: number | undefined; + /** + * The duration `readline` will wait for a character + * (when reading an ambiguous key sequence in milliseconds + * one that can both form a complete key sequence using the input read so far + * and can take additional input to complete a longer key sequence). + * @default 500 + */ + escapeCodeTimeout?: number | undefined; + /** + * The number of spaces a tab is equal to (minimum 1). + * @default 8 + */ + tabSize?: number | undefined; + /** + * Allows closing the interface using an AbortSignal. + * Aborting the signal will internally call `close` on the interface. + */ + signal?: AbortSignal | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface` instance. + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. + * @since v0.1.98 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ', + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity, + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * import { once } from 'node:events'; + * import { createReadStream } from 'node:fs'; + * import { createInterface } from 'node:readline'; + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + type Direction = -1 | 0 | 1; + interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v25.x/api/tty.html) stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v25.x/api/tty.html) stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given [TTY](https://nodejs.org/docs/latest-v25.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given [TTY](https://nodejs.org/docs/latest-v25.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * as promises from "node:readline/promises"; +} +declare module "readline" { + export * from "node:readline"; +} diff --git a/node_modules/@types/node/readline/promises.d.ts b/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000..ccee490 --- /dev/null +++ b/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,158 @@ +declare module "node:readline/promises" { + import { Abortable } from "node:events"; + import { + CompleterResult, + Direction, + Interface as _Interface, + ReadLineOptions as _ReadLineOptions, + } from "node:readline"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean | undefined; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + type Completer = (line: string) => CompleterResult | Promise; + interface ReadLineOptions extends Omit<_ReadLineOptions, "completer"> { + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | undefined; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * import readlinePromises from 'node:readline/promises'; + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "readline/promises" { + export * from "node:readline/promises"; +} diff --git a/node_modules/@types/node/repl.d.ts b/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..7481bea --- /dev/null +++ b/node_modules/@types/node/repl.d.ts @@ -0,0 +1,405 @@ +declare module "node:repl" { + import { AsyncCompleter, Completer, Interface, InterfaceEventMap } from "node:readline"; + import { InspectOptions } from "node:util"; + import { Context } from "node:vm"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. See the [custom evaluation functions](https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#custom-evaluation-functions) + * section for more details. + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * @default the REPL instance's `terminal` value + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * @default false + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * @default false + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * @default a wrapper for `util.inspect` + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * @default false + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + interface REPLServerSetupHistoryOptions { + filePath?: string | undefined; + size?: number | undefined; + removeHistoryDuplicates?: boolean | undefined; + onHistoryFileLoaded?: ((err: Error | null, repl: REPLServer) => void) | undefined; + } + interface REPLServerEventMap extends InterfaceEventMap { + "exit": []; + "reset": [context: Context]; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * import repl from 'node:repl'; + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * import repl from 'node:repl'; + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * }, + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, a pipe `'|'` is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(historyPath: string, callback: (err: Error | null, repl: this) => void): void; + setupHistory( + historyConfig?: REPLServerSetupHistoryOptions, + callback?: (err: Error | null, repl: this) => void, + ): void; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: REPLServerEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: REPLServerEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: REPLServerEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: REPLServerEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: REPLServerEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: REPLServerEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: REPLServerEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: REPLServerEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: REPLServerEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: REPLServerEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: REPLServerEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * import repl from 'node:repl'; + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "repl" { + export * from "node:repl"; +} diff --git a/node_modules/@types/node/sea.d.ts b/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000..85ab108 --- /dev/null +++ b/node_modules/@types/node/sea.d.ts @@ -0,0 +1,47 @@ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): ArrayBuffer; + /** + * This method can be used to retrieve an array of all the keys of assets + * embedded into the single-executable application. + * An error is thrown when not running inside a single-executable application. + * @since v24.8.0 + * @returns An array containing all the keys of the assets + * embedded in the executable. If no assets are embedded, returns an empty array. + */ + function getAssetKeys(): string[]; +} diff --git a/node_modules/@types/node/sqlite.d.ts b/node_modules/@types/node/sqlite.d.ts new file mode 100644 index 0000000..d2111bb --- /dev/null +++ b/node_modules/@types/node/sqlite.d.ts @@ -0,0 +1,1021 @@ +declare module "node:sqlite" { + import { PathLike } from "node:fs"; + type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView; + type SQLOutputValue = null | number | bigint | string | NodeJS.NonSharedUint8Array; + interface DatabaseSyncOptions { + /** + * If `true`, the database is opened by the constructor. When + * this value is `false`, the database must be opened via the `open()` method. + * @since v22.5.0 + * @default true + */ + open?: boolean | undefined; + /** + * If `true`, foreign key constraints + * are enabled. This is recommended but can be disabled for compatibility with + * legacy database schemas. The enforcement of foreign key constraints can be + * enabled and disabled after opening the database using + * [`PRAGMA foreign_keys`](https://www.sqlite.org/pragma.html#pragma_foreign_keys). + * @since v22.10.0 + * @default true + */ + enableForeignKeyConstraints?: boolean | undefined; + /** + * If `true`, SQLite will accept + * [double-quoted string literals](https://www.sqlite.org/quirks.html#dblquote). + * This is not recommended but can be + * enabled for compatibility with legacy database schemas. + * @since v22.10.0 + * @default false + */ + enableDoubleQuotedStringLiterals?: boolean | undefined; + /** + * If `true`, the database is opened in read-only mode. + * If the database does not exist, opening it will fail. + * @since v22.12.0 + * @default false + */ + readOnly?: boolean | undefined; + /** + * If `true`, the `loadExtension` SQL function + * and the `loadExtension()` method are enabled. + * You can call `enableLoadExtension(false)` later to disable this feature. + * @since v22.13.0 + * @default false + */ + allowExtension?: boolean | undefined; + /** + * The [busy timeout](https://sqlite.org/c3ref/busy_timeout.html) in milliseconds. This is the maximum amount of + * time that SQLite will wait for a database lock to be released before + * returning an error. + * @since v24.0.0 + * @default 0 + */ + timeout?: number | undefined; + /** + * If `true`, integer fields are read as JavaScript `BigInt` values. If `false`, + * integer fields are read as JavaScript numbers. + * @since v24.4.0 + * @default false + */ + readBigInts?: boolean | undefined; + /** + * If `true`, query results are returned as arrays instead of objects. + * @since v24.4.0 + * @default false + */ + returnArrays?: boolean | undefined; + /** + * If `true`, allows binding named parameters without the prefix + * character (e.g., `foo` instead of `:foo`). + * @since v24.4.40 + * @default true + */ + allowBareNamedParameters?: boolean | undefined; + /** + * If `true`, unknown named parameters are ignored when binding. + * If `false`, an exception is thrown for unknown named parameters. + * @since v24.4.40 + * @default false + */ + allowUnknownNamedParameters?: boolean | undefined; + /** + * If `true`, enables the defensive flag. When the defensive flag is enabled, + * language features that allow ordinary SQL to deliberately corrupt the database file are disabled. + * The defensive flag can also be set using `enableDefensive()`. + * @since v25.1.0 + * @default true + */ + defensive?: boolean | undefined; + } + interface CreateSessionOptions { + /** + * A specific table to track changes for. By default, changes to all tables are tracked. + * @since v22.12.0 + */ + table?: string | undefined; + /** + * Name of the database to track. This is useful when multiple databases have been added using + * [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html). + * @since v22.12.0 + * @default 'main' + */ + db?: string | undefined; + } + interface ApplyChangesetOptions { + /** + * Skip changes that, when targeted table name is supplied to this function, return a truthy value. + * By default, all changes are attempted. + * @since v22.12.0 + */ + filter?: ((tableName: string) => boolean) | undefined; + /** + * A function that determines how to handle conflicts. The function receives one argument, + * which can be one of the following values: + * + * * `SQLITE_CHANGESET_DATA`: A `DELETE` or `UPDATE` change does not contain the expected "before" values. + * * `SQLITE_CHANGESET_NOTFOUND`: A row matching the primary key of the `DELETE` or `UPDATE` change does not exist. + * * `SQLITE_CHANGESET_CONFLICT`: An `INSERT` change results in a duplicate primary key. + * * `SQLITE_CHANGESET_FOREIGN_KEY`: Applying a change would result in a foreign key violation. + * * `SQLITE_CHANGESET_CONSTRAINT`: Applying a change results in a `UNIQUE`, `CHECK`, or `NOT NULL` constraint + * violation. + * + * The function should return one of the following values: + * + * * `SQLITE_CHANGESET_OMIT`: Omit conflicting changes. + * * `SQLITE_CHANGESET_REPLACE`: Replace existing values with conflicting changes (only valid with + `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT` conflicts). + * * `SQLITE_CHANGESET_ABORT`: Abort on conflict and roll back the database. + * + * When an error is thrown in the conflict handler or when any other value is returned from the handler, + * applying the changeset is aborted and the database is rolled back. + * + * **Default**: A function that returns `SQLITE_CHANGESET_ABORT`. + * @since v22.12.0 + */ + onConflict?: ((conflictType: number) => number) | undefined; + } + interface FunctionOptions { + /** + * If `true`, the [`SQLITE_DETERMINISTIC`](https://www.sqlite.org/c3ref/c_deterministic.html) flag is + * set on the created function. + * @default false + */ + deterministic?: boolean | undefined; + /** + * If `true`, the [`SQLITE_DIRECTONLY`](https://www.sqlite.org/c3ref/c_directonly.html) flag is set on + * the created function. + * @default false + */ + directOnly?: boolean | undefined; + /** + * If `true`, integer arguments to `function` + * are converted to `BigInt`s. If `false`, integer arguments are passed as + * JavaScript numbers. + * @default false + */ + useBigIntArguments?: boolean | undefined; + /** + * If `true`, `function` may be invoked with any number of + * arguments (between zero and + * [`SQLITE_MAX_FUNCTION_ARG`](https://www.sqlite.org/limits.html#max_function_arg)). If `false`, + * `function` must be invoked with exactly `function.length` arguments. + * @default false + */ + varargs?: boolean | undefined; + } + interface AggregateOptions extends FunctionOptions { + /** + * The identity value for the aggregation function. This value is used when the aggregation + * function is initialized. When a `Function` is passed the identity will be its return value. + */ + start: T | (() => T); + /** + * The function to call for each row in the aggregation. The + * function receives the current state and the row value. The return value of + * this function should be the new state. + */ + step: (accumulator: T, ...args: SQLOutputValue[]) => T; + /** + * The function to call to get the result of the + * aggregation. The function receives the final state and should return the + * result of the aggregation. + */ + result?: ((accumulator: T) => SQLInputValue) | undefined; + /** + * When this function is provided, the `aggregate` method will work as a window function. + * The function receives the current state and the dropped row value. The return value of this function should be the + * new state. + */ + inverse?: ((accumulator: T, ...args: SQLOutputValue[]) => T) | undefined; + } + interface PrepareOptions { + /** + * If `true`, integer fields are read as `BigInt`s. + * @since v25.5.0 + */ + readBigInts?: boolean | undefined; + /** + * If `true`, results are returned as arrays. + * @since v25.5.0 + */ + returnArrays?: boolean | undefined; + /** + * If `true`, allows binding named parameters without the prefix character. + * @since v25.5.0 + */ + allowBareNamedParameters?: boolean | undefined; + /** + * If `true`, unknown named parameters are ignored. + * @since v25.5.0 + */ + allowUnknownNamedParameters?: boolean | undefined; + } + /** + * This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs + * exposed by this class execute synchronously. + * @since v22.5.0 + */ + class DatabaseSync implements Disposable { + /** + * Constructs a new `DatabaseSync` instance. + * @param path The path of the database. + * A SQLite database can be stored in a file or completely [in memory](https://www.sqlite.org/inmemorydb.html). + * To use a file-backed database, the path should be a file path. + * To use an in-memory database, the path should be the special name `':memory:'`. + * @param options Configuration options for the database connection. + */ + constructor(path: PathLike, options?: DatabaseSyncOptions); + /** + * Registers a new aggregate function with the SQLite database. This method is a wrapper around + * [`sqlite3_create_window_function()`](https://www.sqlite.org/c3ref/create_function.html). + * + * When used as a window function, the `result` function will be called multiple times. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const db = new DatabaseSync(':memory:'); + * db.exec(` + * CREATE TABLE t3(x, y); + * INSERT INTO t3 VALUES ('a', 4), + * ('b', 5), + * ('c', 3), + * ('d', 8), + * ('e', 1); + * `); + * + * db.aggregate('sumint', { + * start: 0, + * step: (acc, value) => acc + value, + * }); + * + * db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 } + * ``` + * @since v24.0.0 + * @param name The name of the SQLite function to create. + * @param options Function configuration settings. + */ + aggregate(name: string, options: AggregateOptions): void; + aggregate(name: string, options: AggregateOptions): void; + /** + * Closes the database connection. An exception is thrown if the database is not + * open. This method is a wrapper around [`sqlite3_close_v2()`](https://www.sqlite.org/c3ref/close.html). + * @since v22.5.0 + */ + close(): void; + /** + * Loads a shared library into the database connection. This method is a wrapper + * around [`sqlite3_load_extension()`](https://www.sqlite.org/c3ref/load_extension.html). It is required to enable the + * `allowExtension` option when constructing the `DatabaseSync` instance. + * @since v22.13.0 + * @param path The path to the shared library to load. + */ + loadExtension(path: string): void; + /** + * Enables or disables the `loadExtension` SQL function, and the `loadExtension()` + * method. When `allowExtension` is `false` when constructing, you cannot enable + * loading extensions for security reasons. + * @since v22.13.0 + * @param allow Whether to allow loading extensions. + */ + enableLoadExtension(allow: boolean): void; + /** + * Enables or disables the defensive flag. When the defensive flag is active, + * language features that allow ordinary SQL to deliberately corrupt the database file are disabled. + * See [`SQLITE_DBCONFIG_DEFENSIVE`](https://www.sqlite.org/c3ref/c_dbconfig_defensive.html#sqlitedbconfigdefensive) in the SQLite documentation for details. + * @since v25.1.0 + * @param active Whether to set the defensive flag. + */ + enableDefensive(active: boolean): void; + /** + * This method is a wrapper around [`sqlite3_db_filename()`](https://sqlite.org/c3ref/db_filename.html) + * @since v24.0.0 + * @param dbName Name of the database. This can be `'main'` (the default primary database) or any other + * database that has been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) **Default:** `'main'`. + * @returns The location of the database file. When using an in-memory database, + * this method returns null. + */ + location(dbName?: string): string | null; + /** + * This method allows one or more SQL statements to be executed without returning + * any results. This method is useful when executing SQL statements read from a + * file. This method is a wrapper around [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html). + * @since v22.5.0 + * @param sql A SQL string to execute. + */ + exec(sql: string): void; + /** + * This method is used to create SQLite user-defined functions. This method is a + * wrapper around [`sqlite3_create_function_v2()`](https://www.sqlite.org/c3ref/create_function.html). + * @since v22.13.0 + * @param name The name of the SQLite function to create. + * @param options Optional configuration settings for the function. + * @param func The JavaScript function to call when the SQLite + * function is invoked. The return value of this function should be a valid + * SQLite data type: see + * [Type conversion between JavaScript and SQLite](https://nodejs.org/docs/latest-v25.x/api/sqlite.html#type-conversion-between-javascript-and-sqlite). + * The result defaults to `NULL` if the return value is `undefined`. + */ + function( + name: string, + options: FunctionOptions, + func: (...args: SQLOutputValue[]) => SQLInputValue, + ): void; + function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void; + /** + * Sets an authorizer callback that SQLite will invoke whenever it attempts to + * access data or modify the database schema through prepared statements. + * This can be used to implement security policies, audit access, or restrict certain operations. + * This method is a wrapper around [`sqlite3_set_authorizer()`](https://sqlite.org/c3ref/set_authorizer.html). + * + * When invoked, the callback receives five arguments: + * + * * `actionCode` {number} The type of operation being performed (e.g., + * `SQLITE_INSERT`, `SQLITE_UPDATE`, `SQLITE_SELECT`). + * * `arg1` {string|null} The first argument (context-dependent, often a table name). + * * `arg2` {string|null} The second argument (context-dependent, often a column name). + * * `dbName` {string|null} The name of the database. + * * `triggerOrView` {string|null} The name of the trigger or view causing the access. + * + * The callback must return one of the following constants: + * + * * `SQLITE_OK` - Allow the operation. + * * `SQLITE_DENY` - Deny the operation (causes an error). + * * `SQLITE_IGNORE` - Ignore the operation (silently skip). + * + * ```js + * import { DatabaseSync, constants } from 'node:sqlite'; + * const db = new DatabaseSync(':memory:'); + * + * // Set up an authorizer that denies all table creation + * db.setAuthorizer((actionCode) => { + * if (actionCode === constants.SQLITE_CREATE_TABLE) { + * return constants.SQLITE_DENY; + * } + * return constants.SQLITE_OK; + * }); + * + * // This will work + * db.prepare('SELECT 1').get(); + * + * // This will throw an error due to authorization denial + * try { + * db.exec('CREATE TABLE blocked (id INTEGER)'); + * } catch (err) { + * console.log('Operation blocked:', err.message); + * } + * ``` + * @since v24.10.0 + * @param callback The authorizer function to set, or `null` to + * clear the current authorizer. + */ + setAuthorizer( + callback: + | (( + actionCode: number, + arg1: string | null, + arg2: string | null, + dbName: string | null, + triggerOrView: string | null, + ) => number) + | null, + ): void; + /** + * Whether the database is currently open or not. + * @since v22.15.0 + */ + readonly isOpen: boolean; + /** + * Whether the database is currently within a transaction. This method + * is a wrapper around [`sqlite3_get_autocommit()`](https://sqlite.org/c3ref/get_autocommit.html). + * @since v24.0.0 + */ + readonly isTransaction: boolean; + /** + * Opens the database specified in the `path` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via + * the constructor. An exception is thrown if the database is already open. + * @since v22.5.0 + */ + open(): void; + /** + * Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper + * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html). + * @since v22.5.0 + * @param sql A SQL string to compile to a prepared statement. + * @param options Optional configuration for the prepared statement. + * @return The prepared statement. + */ + prepare(sql: string, options?: PrepareOptions): StatementSync; + /** + * Creates a new {@link SQLTagStore}, which is a Least Recently Used (LRU) cache + * for storing prepared statements. This allows for the efficient reuse of + * prepared statements by tagging them with a unique identifier. + * + * When a tagged SQL literal is executed, the `SQLTagStore` checks if a prepared + * statement for the corresponding SQL query string already exists in the cache. + * If it does, the cached statement is used. If not, a new prepared statement is + * created, executed, and then stored in the cache for future use. This mechanism + * helps to avoid the overhead of repeatedly parsing and preparing the same SQL + * statements. + * + * Tagged statements bind the placeholder values from the template literal as + * parameters to the underlying prepared statement. For example: + * + * ```js + * sqlTagStore.get`SELECT ${value}`; + * ``` + * + * is equivalent to: + * + * ```js + * db.prepare('SELECT ?').get(value); + * ``` + * + * However, in the first example, the tag store will cache the underlying prepared + * statement for future use. + * + * > **Note:** The `${value}` syntax in tagged statements _binds_ a parameter to + * > the prepared statement. This differs from its behavior in _untagged_ template + * > literals, where it performs string interpolation. + * > + * > ```js + * > // This a safe example of binding a parameter to a tagged statement. + * > sqlTagStore.run`INSERT INTO t1 (id) VALUES (${id})`; + * > + * > // This is an *unsafe* example of an untagged template string. + * > // `id` is interpolated into the query text as a string. + * > // This can lead to SQL injection and data corruption. + * > db.run(`INSERT INTO t1 (id) VALUES (${id})`); + * > ``` + * + * The tag store will match a statement from the cache if the query strings + * (including the positions of any bound placeholders) are identical. + * + * ```js + * // The following statements will match in the cache: + * sqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`; + * sqlTagStore.get`SELECT * FROM t1 WHERE id = ${12345} AND active = 1`; + * + * // The following statements will not match, as the query strings + * // and bound placeholders differ: + * sqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`; + * sqlTagStore.get`SELECT * FROM t1 WHERE id = 12345 AND active = 1`; + * + * // The following statements will not match, as matches are case-sensitive: + * sqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`; + * sqlTagStore.get`select * from t1 where id = ${id} and active = 1`; + * ``` + * + * The only way of binding parameters in tagged statements is with the `${value}` + * syntax. Do not add parameter binding placeholders (`?` etc.) to the SQL query + * string itself. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const db = new DatabaseSync(':memory:'); + * const sql = db.createSQLTagStore(); + * + * db.exec('CREATE TABLE users (id INT, name TEXT)'); + * + * // Using the 'run' method to insert data. + * // The tagged literal is used to identify the prepared statement. + * sql.run`INSERT INTO users VALUES (1, 'Alice')`; + * sql.run`INSERT INTO users VALUES (2, 'Bob')`; + * + * // Using the 'get' method to retrieve a single row. + * const name = 'Alice'; + * const user = sql.get`SELECT * FROM users WHERE name = ${name}`; + * console.log(user); // { id: 1, name: 'Alice' } + * + * // Using the 'all' method to retrieve all rows. + * const allUsers = sql.all`SELECT * FROM users ORDER BY id`; + * console.log(allUsers); + * // [ + * // { id: 1, name: 'Alice' }, + * // { id: 2, name: 'Bob' } + * // ] + * ``` + * @since v24.9.0 + * @returns A new SQL tag store for caching prepared statements. + */ + createTagStore(maxSize?: number): SQLTagStore; + /** + * Creates and attaches a session to the database. This method is a wrapper around + * [`sqlite3session_create()`](https://www.sqlite.org/session/sqlite3session_create.html) and + * [`sqlite3session_attach()`](https://www.sqlite.org/session/sqlite3session_attach.html). + * @param options The configuration options for the session. + * @returns A session handle. + * @since v22.12.0 + */ + createSession(options?: CreateSessionOptions): Session; + /** + * An exception is thrown if the database is not + * open. This method is a wrapper around + * [`sqlite3changeset_apply()`](https://www.sqlite.org/session/sqlite3changeset_apply.html). + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const sourceDb = new DatabaseSync(':memory:'); + * const targetDb = new DatabaseSync(':memory:'); + * + * sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * + * const session = sourceDb.createSession(); + * + * const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * + * const changeset = session.changeset(); + * targetDb.applyChangeset(changeset); + * // Now that the changeset has been applied, targetDb contains the same data as sourceDb. + * ``` + * @param changeset A binary changeset or patchset. + * @param options The configuration options for how the changes will be applied. + * @returns Whether the changeset was applied successfully without being aborted. + * @since v22.12.0 + */ + applyChangeset(changeset: Uint8Array, options?: ApplyChangesetOptions): boolean; + /** + * Closes the database connection. If the database connection is already closed + * then this is a no-op. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + } + /** + * @since v22.12.0 + */ + interface Session { + /** + * Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times. + * An exception is thrown if the database or the session is not open. This method is a wrapper around + * [`sqlite3session_changeset()`](https://www.sqlite.org/session/sqlite3session_changeset.html). + * @returns Binary changeset that can be applied to other databases. + * @since v22.12.0 + */ + changeset(): NodeJS.NonSharedUint8Array; + /** + * Similar to the method above, but generates a more compact patchset. See + * [Changesets and Patchsets](https://www.sqlite.org/sessionintro.html#changesets_and_patchsets) + * in the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_patchset()`](https://www.sqlite.org/session/sqlite3session_patchset.html). + * @returns Binary patchset that can be applied to other databases. + * @since v22.12.0 + */ + patchset(): NodeJS.NonSharedUint8Array; + /** + * Closes the session. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_delete()`](https://www.sqlite.org/session/sqlite3session_delete.html). + */ + close(): void; + /** + * Closes the session. If the session is already closed, does nothing. + * @since v24.9.0 + */ + [Symbol.dispose](): void; + } + /** + * This class represents a single LRU (Least Recently Used) cache for storing + * prepared statements. + * + * Instances of this class are created via the `database.createTagStore()` + * method, not by using a constructor. The store caches prepared statements based + * on the provided SQL query string. When the same query is seen again, the store + * retrieves the cached statement and safely applies the new values through + * parameter binding, thereby preventing attacks like SQL injection. + * + * The cache has a maxSize that defaults to 1000 statements, but a custom size can + * be provided (e.g., `database.createTagStore(100)`). All APIs exposed by this + * class execute synchronously. + * @since v24.9.0 + */ + interface SQLTagStore { + /** + * Executes the given SQL query and returns all resulting rows as an array of + * objects. + * + * This function is intended to be used as a template literal tag, not to be + * called directly. + * @since v24.9.0 + * @param stringElements Template literal elements containing the SQL + * query. + * @param boundParameters Parameter values to be bound to placeholders in the template string. + * @returns An array of objects representing the rows returned by the query. + */ + all( + stringElements: TemplateStringsArray, + ...boundParameters: SQLInputValue[] + ): Record[]; + /** + * Executes the given SQL query and returns the first resulting row as an object. + * + * This function is intended to be used as a template literal tag, not to be + * called directly. + * @since v24.9.0 + * @param stringElements Template literal elements containing the SQL + * query. + * @param boundParameters Parameter values to be bound to placeholders in the template string. + * @returns An object representing the first row returned by + * the query, or `undefined` if no rows are returned. + */ + get( + stringElements: TemplateStringsArray, + ...boundParameters: SQLInputValue[] + ): Record | undefined; + /** + * Executes the given SQL query and returns an iterator over the resulting rows. + * + * This function is intended to be used as a template literal tag, not to be + * called directly. + * @since v24.9.0 + * @param stringElements Template literal elements containing the SQL + * query. + * @param boundParameters Parameter values to be bound to placeholders in the template string. + * @returns An iterator that yields objects representing the rows returned by the query. + */ + iterate( + stringElements: TemplateStringsArray, + ...boundParameters: SQLInputValue[] + ): NodeJS.Iterator>; + /** + * Executes the given SQL query, which is expected to not return any rows (e.g., INSERT, UPDATE, DELETE). + * + * This function is intended to be used as a template literal tag, not to be + * called directly. + * @since v24.9.0 + * @param stringElements Template literal elements containing the SQL + * query. + * @param boundParameters Parameter values to be bound to placeholders in the template string. + * @returns An object containing information about the execution, including `changes` and `lastInsertRowid`. + */ + run(stringElements: TemplateStringsArray, ...boundParameters: SQLInputValue[]): StatementResultingChanges; + /** + * A read-only property that returns the number of prepared statements currently in the cache. + * @since v24.9.0 + */ + readonly size: number; + /** + * A read-only property that returns the maximum number of prepared statements the cache can hold. + * @since v24.9.0 + */ + readonly capacity: number; + /** + * A read-only property that returns the `DatabaseSync` object associated with this `SQLTagStore`. + * @since v24.9.0 + */ + readonly db: DatabaseSync; + /** + * Resets the LRU cache, clearing all stored prepared statements. + * @since v24.9.0 + */ + clear(): void; + } + interface StatementColumnMetadata { + /** + * The unaliased name of the column in the origin + * table, or `null` if the column is the result of an expression or subquery. + * This property is the result of [`sqlite3_column_origin_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + column: string | null; + /** + * The unaliased name of the origin database, or + * `null` if the column is the result of an expression or subquery. This + * property is the result of [`sqlite3_column_database_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + database: string | null; + /** + * The name assigned to the column in the result set of a + * `SELECT` statement. This property is the result of + * [`sqlite3_column_name()`](https://www.sqlite.org/c3ref/column_name.html). + */ + name: string; + /** + * The unaliased name of the origin table, or `null` if + * the column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_table_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + table: string | null; + /** + * The declared data type of the column, or `null` if the + * column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_decltype()`](https://www.sqlite.org/c3ref/column_decltype.html). + */ + type: string | null; + } + interface StatementResultingChanges { + /** + * The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_changes64()`](https://www.sqlite.org/c3ref/changes.html). + */ + changes: number | bigint; + /** + * The most recently inserted rowid. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html). + */ + lastInsertRowid: number | bigint; + } + /** + * This class represents a single [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This class cannot be + * instantiated via its constructor. Instead, instances are created via the`database.prepare()` method. All APIs exposed by this class execute + * synchronously. + * + * A prepared statement is an efficient binary representation of the SQL used to + * create it. Prepared statements are parameterizable, and can be invoked multiple + * times with different bound values. Parameters also offer protection against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. For these reasons, prepared statements are + * preferred + * over hand-crafted SQL strings when handling user input. + * @since v22.5.0 + */ + class StatementSync { + private constructor(); + /** + * This method executes a prepared statement and returns all results as an array of + * objects. If the prepared statement does not return any results, this method + * returns an empty array. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of + * the row. + */ + all(...anonymousParameters: SQLInputValue[]): Record[]; + all( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record[]; + /** + * This method is used to retrieve information about the columns returned by the + * prepared statement. + * @since v23.11.0 + * @returns An array of objects. Each object corresponds to a column + * in the prepared statement, and contains the following properties: + */ + columns(): StatementColumnMetadata[]; + /** + * The source SQL text of the prepared statement with parameter + * placeholders replaced by the values that were used during the most recent + * execution of this prepared statement. This property is a wrapper around + * [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly expandedSQL: string; + /** + * This method executes a prepared statement and returns the first result as an + * object. If the prepared statement does not return any results, this method + * returns `undefined`. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no + * rows were returned from the database then this method returns `undefined`. + */ + get(...anonymousParameters: SQLInputValue[]): Record | undefined; + get( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record | undefined; + /** + * This method executes a prepared statement and returns an iterator of + * objects. If the prepared statement does not return any results, this method + * returns an empty iterator. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.13.0 + * @param namedParameters An optional object used to bind named parameters. + * The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @returns An iterable iterator of objects. Each object corresponds to a row + * returned by executing the prepared statement. The keys and values of each + * object correspond to the column names and values of the row. + */ + iterate(...anonymousParameters: SQLInputValue[]): NodeJS.Iterator>; + iterate( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): NodeJS.Iterator>; + /** + * This method executes a prepared statement and returns an object summarizing the + * resulting changes. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + */ + run(...anonymousParameters: SQLInputValue[]): StatementResultingChanges; + run( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): StatementResultingChanges; + /** + * The names of SQLite parameters begin with a prefix character. By default,`node:sqlite` requires that this prefix character is present when binding + * parameters. However, with the exception of dollar sign character, these + * prefix characters also require extra quoting when used in object keys. + * + * To improve ergonomics, this method can be used to also allow bare named + * parameters, which do not require the prefix character in JavaScript code. There + * are several caveats to be aware of when enabling bare named parameters: + * + * * The prefix character is still required in SQL. + * * The prefix character is still allowed in JavaScript. In fact, prefixed names + * will have slightly better binding performance. + * * Using ambiguous named parameters, such as `$k` and `@k`, in the same prepared + * statement will result in an exception as it cannot be determined how to bind + * a bare name. + * @since v22.5.0 + * @param enabled Enables or disables support for binding named parameters without the prefix character. + */ + setAllowBareNamedParameters(enabled: boolean): void; + /** + * By default, if an unknown name is encountered while binding parameters, an + * exception is thrown. This method allows unknown named parameters to be ignored. + * @since v22.15.0 + * @param enabled Enables or disables support for unknown named parameters. + */ + setAllowUnknownNamedParameters(enabled: boolean): void; + /** + * When enabled, query results returned by the `all()`, `get()`, and `iterate()` methods will be returned as arrays instead + * of objects. + * @since v24.0.0 + * @param enabled Enables or disables the return of query results as arrays. + */ + setReturnArrays(enabled: boolean): void; + /** + * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript + * numbers by default. However, SQLite `INTEGER`s can store values larger than + * JavaScript numbers are capable of representing. In such cases, this method can + * be used to read `INTEGER` data using JavaScript `BigInt`s. This method has no + * impact on database write operations where numbers and `BigInt`s are both + * supported at all times. + * @since v22.5.0 + * @param enabled Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database. + */ + setReadBigInts(enabled: boolean): void; + /** + * The source SQL text of the prepared statement. This property is a + * wrapper around [`sqlite3_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly sourceSQL: string; + } + interface BackupOptions { + /** + * Name of the source database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + source?: string | undefined; + /** + * Name of the target database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + target?: string | undefined; + /** + * Number of pages to be transmitted in each batch of the backup. + * @default 100 + */ + rate?: number | undefined; + /** + * An optional callback function that will be called after each backup step. The argument passed + * to this callback is an `Object` with `remainingPages` and `totalPages` properties, describing the current progress + * of the backup operation. + */ + progress?: ((progressInfo: BackupProgressInfo) => void) | undefined; + } + interface BackupProgressInfo { + totalPages: number; + remainingPages: number; + } + /** + * This method makes a database backup. This method abstracts the + * [`sqlite3_backup_init()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupinit), + * [`sqlite3_backup_step()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupstep) + * and [`sqlite3_backup_finish()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish) functions. + * + * The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same + * `DatabaseSync` - object will be reflected in the backup right away. However, mutations from other connections will cause + * the backup process to restart. + * + * ```js + * import { backup, DatabaseSync } from 'node:sqlite'; + * + * const sourceDb = new DatabaseSync('source.db'); + * const totalPagesTransferred = await backup(sourceDb, 'backup.db', { + * rate: 1, // Copy one page at a time. + * progress: ({ totalPages, remainingPages }) => { + * console.log('Backup in progress', { totalPages, remainingPages }); + * }, + * }); + * + * console.log('Backup completed', totalPagesTransferred); + * ``` + * @since v23.8.0 + * @param sourceDb The database to backup. The source database must be open. + * @param path The path where the backup will be created. If the file already exists, + * the contents will be overwritten. + * @param options Optional configuration for the backup. The + * following properties are supported: + * @returns A promise that fulfills with the total number of backed-up pages upon completion, or rejects if an + * error occurs. + */ + function backup(sourceDb: DatabaseSync, path: PathLike, options?: BackupOptions): Promise; + /** + * @since v22.13.0 + */ + namespace constants { + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected "before" values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_DATA: number; + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_NOTFOUND: number; + /** + * This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_CONFLICT: number; + /** + * If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns `SQLITE_CHANGESET_OMIT`, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns `SQLITE_CHANGESET_ABORT`, the changeset is rolled back. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_FOREIGN_KEY: number; + /** + * Conflicting changes are omitted. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_OMIT: number; + /** + * Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT`. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_REPLACE: number; + /** + * Abort when a change encounters a conflict and roll back database. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_ABORT: number; + /** + * Deny the operation and cause an error to be returned. + * @since v24.10.0 + */ + const SQLITE_DENY: number; + /** + * Ignore the operation and continue as if it had never been requested. + * @since 24.10.0 + */ + const SQLITE_IGNORE: number; + /** + * Allow the operation to proceed normally. + * @since v24.10.0 + */ + const SQLITE_OK: number; + const SQLITE_CREATE_INDEX: number; + const SQLITE_CREATE_TABLE: number; + const SQLITE_CREATE_TEMP_INDEX: number; + const SQLITE_CREATE_TEMP_TABLE: number; + const SQLITE_CREATE_TEMP_TRIGGER: number; + const SQLITE_CREATE_TEMP_VIEW: number; + const SQLITE_CREATE_TRIGGER: number; + const SQLITE_CREATE_VIEW: number; + const SQLITE_DELETE: number; + const SQLITE_DROP_INDEX: number; + const SQLITE_DROP_TABLE: number; + const SQLITE_DROP_TEMP_INDEX: number; + const SQLITE_DROP_TEMP_TABLE: number; + const SQLITE_DROP_TEMP_TRIGGER: number; + const SQLITE_DROP_TEMP_VIEW: number; + const SQLITE_DROP_TRIGGER: number; + const SQLITE_DROP_VIEW: number; + const SQLITE_INSERT: number; + const SQLITE_PRAGMA: number; + const SQLITE_READ: number; + const SQLITE_SELECT: number; + const SQLITE_TRANSACTION: number; + const SQLITE_UPDATE: number; + const SQLITE_ATTACH: number; + const SQLITE_DETACH: number; + const SQLITE_ALTER_TABLE: number; + const SQLITE_REINDEX: number; + const SQLITE_ANALYZE: number; + const SQLITE_CREATE_VTABLE: number; + const SQLITE_DROP_VTABLE: number; + const SQLITE_FUNCTION: number; + const SQLITE_SAVEPOINT: number; + const SQLITE_COPY: number; + const SQLITE_RECURSIVE: number; + } +} diff --git a/node_modules/@types/node/stream.d.ts b/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..1591667 --- /dev/null +++ b/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1774 @@ +declare module "node:stream" { + import { Blob } from "node:buffer"; + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:stream/promises"; + import * as web from "node:stream/web"; + class Stream extends EventEmitter { + /** + * @since v0.9.4 + */ + pipe( + destination: T, + options?: Stream.PipeOptions, + ): T; + } + namespace Stream { + export { promises, Stream }; + } + namespace Stream { + interface PipeOptions { + /** + * End the writer when the reader ends. + * @default true + */ + end?: boolean | undefined; + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?: ((this: T, callback: (error?: Error | null) => void) => void) | undefined; + destroy?: ((this: T, error: Error | null, callback: (error?: Error | null) => void) => void) | undefined; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?: ((this: T, size: number) => void) | undefined; + } + interface ReadableIteratorOptions { + /** + * When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, + * `return`, or `throw` will not destroy the stream. + * @default true + */ + destroyOnReturn?: boolean | undefined; + } + interface ReadableOperatorOptions extends Abortable { + /** + * The maximum concurrent invocations of `fn` to call + * on the stream at once. + * @default 1 + */ + concurrency?: number | undefined; + /** + * How many items to buffer while waiting for user consumption + * of the output. + * @default concurrency * 2 - 1 + */ + highWaterMark?: number | undefined; + } + /** @deprecated Use `ReadableOperatorOptions` instead. */ + interface ArrayOptions extends ReadableOperatorOptions {} + interface ReadableToWebOptions { + strategy?: web.QueuingStrategy | undefined; + type?: web.ReadableStreamType | undefined; + } + interface ReadableEventMap { + "close": []; + "data": [chunk: any]; + "end": []; + "error": [err: Error]; + "pause": []; + "readable": []; + "resume": []; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + constructor(options?: ReadableOptions); + /** + * A utility method for creating Readable Streams out of iterators. + * @since v12.3.0, v10.17.0 + * @param iterable Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed. + * @param options Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + */ + static fromWeb( + readableStream: web.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + */ + static toWeb( + streamReadable: NodeJS.ReadableStream, + options?: ReadableToWebOptions, + ): web.ReadableStream; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: NodeJS.ReadableStream | web.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call {@link read}, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the {@link setEncoding} method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when [`'end'`](https://nodejs.org/docs/latest-v25.x/api/stream.html#event-end) event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the [Three states](https://nodejs.org/docs/latest-v25.x/api/stream.html#three-states) section. + * @since v9.4.0 + */ + readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If + * `size` bytes are not available to be read, `null` will be returned _unless_ the + * stream has ended, in which case all of the data remaining in the internal buffer + * will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the `size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as `Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer` objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling `readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the `Readable`. + * This is used primarily by the mechanism that underlies the `readable.pipe()` method. + * In most typical cases, there will be no reason to use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * import fs from 'node:fs'; + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * import { StringDecoder } from 'node:string_decoder'; + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must + * be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream` module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the `readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * import { OldReader } from './old-api-module.js'; + * import { Readable } from 'node:stream'; + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * ```js + * import { Readable } from 'node:stream'; + * + * async function* splitToWords(source) { + * for await (const chunk of source) { + * const words = String(chunk).split(' '); + * + * for (const word of words) { + * yield word; + * } + * } + * } + * + * const wordsStream = Readable.from(['text passed through', 'composed stream']).compose(splitToWords); + * const words = await wordsStream.toArray(); + * + * console.log(words); // prints ['text', 'passed', 'through', 'composed', 'stream'] + * ``` + * + * `readable.compose(s)` is equivalent to `stream.compose(readable, s)`. + * + * This method also allows for an `AbortSignal` to be provided, which will destroy + * the composed stream when aborted. + * + * See [`stream.compose(...streams)`](https://nodejs.org/docs/latest-v25.x/api/stream.html#streamcomposestreams) for more information. + * @since v19.1.0, v18.13.0 + * @returns a stream composed with the stream `stream`. + */ + compose( + stream: NodeJS.WritableStream | web.WritableStream | web.TransformStream | ((source: any) => void), + options?: Abortable, + ): Duplex; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + */ + iterator(options?: ReadableIteratorOptions): NodeJS.AsyncIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Abortable) => any, options?: ReadableOperatorOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Abortable) => boolean | Promise, + options?: ReadableOperatorOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Abortable) => void | Promise, + options?: Pick, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Abortable): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Abortable) => boolean | Promise, + options?: Pick, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Abortable) => data is T, + options?: Pick, + ): Promise; + find( + fn: (data: any, options?: Abortable) => boolean | Promise, + options?: Pick, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Abortable) => boolean | Promise, + options?: Pick, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap( + fn: (data: any, options?: Abortable) => any, + options?: Pick, + ): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Abortable): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Abortable): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce(fn: (previous: any, data: any, options?: Abortable) => T): Promise; + reduce( + fn: (previous: T, data: any, options?: Abortable) => T, + initial: T, + options?: Abortable, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()` will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * @returns `AsyncIterator` to fully consume the stream. + * @since v10.0.0 + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns + * a promise that fulfills when the stream is finished. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ReadableEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ReadableEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ReadableEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: ReadableEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: ReadableEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: ReadableEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ReadableEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ReadableEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ReadableEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: ReadableEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ReadableEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?: + | (( + this: T, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ) => void) + | undefined; + writev?: + | (( + this: T, + chunks: { + chunk: any; + encoding: BufferEncoding; + }[], + callback: (error?: Error | null) => void, + ) => void) + | undefined; + final?: ((this: T, callback: (error?: Error | null) => void) => void) | undefined; + } + interface WritableEventMap { + "close": []; + "drain": []; + "error": [err: Error]; + "finish": []; + "pipe": [src: Readable]; + "unpipe": [src: Readable]; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + constructor(options?: WritableOptions); + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + writableStream: web.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + */ + static toWeb(streamWritable: NodeJS.WritableStream): web.WritableStream; + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + writable: boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'finish'`. + * @since v18.0.0, v16.17.0 + */ + readonly writableAborted: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: { + chunk: any; + encoding: BufferEncoding; + }[], + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the `highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + /** + * Writes data to the stream, with an explicit encoding for string data. + * @see {@link Writable.write} for full details. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * import fs from 'node:fs'; + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param cb Callback for when the stream is finished. + */ + end(cb?: () => void): this; + /** + * Signals that no more data will be written, with one final chunk of data. + * @see {@link Writable.end} for full details. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param cb Callback for when the stream is finished. + */ + end(chunk: any, cb?: () => void): this; + /** + * Signals that no more data will be written, with one final chunk of data. + * @see {@link Writable.end} for full details. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param cb Callback for when the stream is finished. + */ + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()` buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing `writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using `process.nextTick()`. Doing so allows batching of all `writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Calls `writable.destroy()` with an `AbortError` and returns + * a promise that fulfills when the stream is finished. + * @since v22.4.0, v20.16.0 + */ + [Symbol.asyncDispose](): Promise; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: WritableEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: WritableEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: WritableEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: WritableEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: WritableEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: WritableEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: WritableEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: WritableEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: WritableEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: WritableEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: WritableEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + } + interface DuplexToWebOptions { + type?: web.ReadableStreamType | undefined; + } + interface DuplexEventMap extends ReadableEventMap, WritableEventMap {} + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Stream implements NodeJS.ReadWriteStream { + constructor(options?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | NodeJS.ReadableStream + | NodeJS.WritableStream + | Blob + | string + | Iterable + | AsyncIterable + | ((source: AsyncIterable) => AsyncIterable) + | ((source: AsyncIterable) => Promise) + | Promise + | web.ReadableWritablePair + | web.ReadableStream + | web.WritableStream, + ): Duplex; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + */ + static toWeb(streamDuplex: NodeJS.ReadWriteStream, options?: DuplexToWebOptions): web.ReadableWritablePair; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + duplexStream: web.ReadableWritablePair, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `true`. + * + * This can be changed manually to change the half-open behavior of an existing + * `Duplex` stream instance, but must be changed before the `'end'` event is emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: DuplexEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: DuplexEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: DuplexEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: DuplexEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: DuplexEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: DuplexEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: E, listener: (...args: DuplexEventMap[E]) => void): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: DuplexEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: DuplexEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: DuplexEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: DuplexEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface Duplex extends Readable, Writable {} + /** + * The utility function `duplexPair` returns an Array with two items, + * each being a `Duplex` stream connected to the other side: + * + * ```js + * const [ sideA, sideB ] = duplexPair(); + * ``` + * + * Whatever is written to one stream is made readable on the other. It provides + * behavior analogous to a network connection, where the data written by the client + * becomes readable by the server, and vice-versa. + * + * The Duplex streams are symmetrical; one or the other may be used without any + * difference in behavior. + * @param options A value to pass to both {@link Duplex} constructors, + * to set options such as buffering. + * @since v22.6.0 + */ + function duplexPair(options?: DuplexOptions): [Duplex, Duplex]; + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + transform?: + | ((this: T, chunk: any, encoding: BufferEncoding, callback: TransformCallback) => void) + | undefined; + flush?: ((this: T, callback: TransformCallback) => void) | undefined; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(options?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * A stream to attach a signal to. + * + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the + * stream, and `controller.error(new AbortError())` for webstreams. + * + * ```js + * import fs from 'node:fs'; + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream A stream to attach a signal to. + */ + function addAbortSignal< + T extends NodeJS.ReadableStream | NodeJS.WritableStream | web.ReadableStream | web.WritableStream, + >(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `65536` (64 KiB), or `16` for `objectMode`. + * @since v19.9.0 + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A readable and/or writable stream/webstream. + * + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * import { finished } from 'node:stream'; + * import fs from 'node:fs'; + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`. + * + * The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v25.x/api/stream.html#streamfinishedstream-options). + * + * `stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @returns A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | web.ReadableStream | web.WritableStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | web.ReadableStream | web.WritableStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + import __promisify__ = promises.finished; + export { __promisify__ }; + } + type PipelineSourceFunction = (options?: Abortable) => Iterable | AsyncIterable; + type PipelineSource = + | NodeJS.ReadableStream + | web.ReadableStream + | web.TransformStream + | Iterable + | AsyncIterable + | PipelineSourceFunction; + type PipelineSourceArgument = (T extends (...args: any[]) => infer R ? R : T) extends infer S + ? S extends web.TransformStream ? web.ReadableStream : S + : never; + type PipelineTransformGenerator, O> = ( + source: PipelineSourceArgument, + options?: Abortable, + ) => AsyncIterable; + type PipelineTransformStreams = + | NodeJS.ReadWriteStream + | web.TransformStream; + type PipelineTransform, O> = S extends + PipelineSource | PipelineTransformStreams | ((...args: any[]) => infer I) + ? PipelineTransformStreams | PipelineTransformGenerator + : never; + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationFunction, R> = ( + source: PipelineSourceArgument, + options?: Abortable, + ) => R; + type PipelineDestination, R> = S extends + PipelineSource | PipelineTransform ? + | NodeJS.WritableStream + | web.WritableStream + | web.TransformStream + | PipelineDestinationFunction + : never; + type PipelineCallback> = ( + err: NodeJS.ErrnoException | null, + value: S extends (...args: any[]) => PromiseLike ? R : undefined, + ) => void; + type PipelineResult> = S extends NodeJS.WritableStream ? S : Duplex; + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * import { pipeline } from 'node:stream'; + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * }, + * ); + * ``` + * + * The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v25.x/api/stream.html#streampipelinesource-transforms-destination-options). + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * import fs from 'node:fs'; + * import http from 'node:http'; + * import { pipeline } from 'node:stream'; + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, D extends PipelineDestination>( + source: S, + destination: D, + callback: PipelineCallback, + ): PipelineResult; + function pipeline< + S extends PipelineSource, + T extends PipelineTransform, + D extends PipelineDestination, + >( + source: S, + transform: T, + destination: D, + callback: PipelineCallback, + ): PipelineResult; + function pipeline< + S extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + D extends PipelineDestination, + >( + source: S, + transform1: T1, + transform2: T2, + destination: D, + callback: PipelineCallback, + ): PipelineResult; + function pipeline< + S extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + D extends PipelineDestination, + >( + source: S, + transform1: T1, + transform2: T2, + transform3: T3, + destination: D, + callback: PipelineCallback, + ): PipelineResult; + function pipeline< + S extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + D extends PipelineDestination, + >( + source: S, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: D, + callback: PipelineCallback, + ): PipelineResult; + function pipeline( + streams: ReadonlyArray | PipelineTransform | PipelineDestination>, + callback: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + ...streams: [ + ...[PipelineSource, ...PipelineTransform[], PipelineDestination], + callback: ((err: NodeJS.ErrnoException | null) => void), + ] + ): NodeJS.WritableStream; + namespace pipeline { + import __promisify__ = promises.pipeline; + export { __promisify__ }; + } + type ComposeSource = + | NodeJS.ReadableStream + | web.ReadableStream + | Iterable + | AsyncIterable + | (() => AsyncIterable); + type ComposeTransformStreams = NodeJS.ReadWriteStream | web.TransformStream; + type ComposeTransformGenerator = (source: AsyncIterable) => AsyncIterable; + type ComposeTransform, O> = S extends + ComposeSource | ComposeTransformStreams | ComposeTransformGenerator + ? ComposeTransformStreams | ComposeTransformGenerator + : never; + type ComposeTransformSource = ComposeSource | ComposeTransform; + type ComposeDestination> = S extends ComposeTransformSource ? + | NodeJS.WritableStream + | web.WritableStream + | web.TransformStream + | ((source: AsyncIterable) => void) + : never; + /** + * Combines two or more streams into a `Duplex` stream that writes to the + * first stream and reads from the last. Each provided stream is piped into + * the next, using `stream.pipeline`. If any of the streams error then all + * are destroyed, including the outer `Duplex` stream. + * + * Because `stream.compose` returns a new stream that in turn can (and + * should) be piped into other streams, it enables composition. In contrast, + * when passing streams to `stream.pipeline`, typically the first stream is + * a readable stream and the last a writable stream, forming a closed + * circuit. + * + * If passed a `Function` it must be a factory method taking a `source` + * `Iterable`. + * + * ```js + * import { compose, Transform } from 'node:stream'; + * + * const removeSpaces = new Transform({ + * transform(chunk, encoding, callback) { + * callback(null, String(chunk).replace(' ', '')); + * }, + * }); + * + * async function* toUpper(source) { + * for await (const chunk of source) { + * yield String(chunk).toUpperCase(); + * } + * } + * + * let res = ''; + * for await (const buf of compose(removeSpaces, toUpper).end('hello world')) { + * res += buf; + * } + * + * console.log(res); // prints 'HELLOWORLD' + * ``` + * + * `stream.compose` can be used to convert async iterables, generators and + * functions into streams. + * + * * `AsyncIterable` converts into a readable `Duplex`. Cannot yield + * `null`. + * * `AsyncGeneratorFunction` converts into a readable/writable transform `Duplex`. + * Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * * `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined`. + * + * ```js + * import { compose } from 'node:stream'; + * import { finished } from 'node:stream/promises'; + * + * // Convert AsyncIterable into readable Duplex. + * const s1 = compose(async function*() { + * yield 'Hello'; + * yield 'World'; + * }()); + * + * // Convert AsyncGenerator into transform Duplex. + * const s2 = compose(async function*(source) { + * for await (const chunk of source) { + * yield String(chunk).toUpperCase(); + * } + * }); + * + * let res = ''; + * + * // Convert AsyncFunction into writable Duplex. + * const s3 = compose(async function(source) { + * for await (const chunk of source) { + * res += chunk; + * } + * }); + * + * await finished(compose(s1, s2, s3)); + * + * console.log(res); // prints 'HELLOWORLD' + * ``` + * + * For convenience, the `readable.compose(stream)` method is available on + * `Readable` and `Duplex` streams as a wrapper for this function. + * @since v16.9.0 + * @experimental + */ + /* eslint-disable @definitelytyped/no-unnecessary-generics */ + function compose(stream: ComposeSource | ComposeDestination): Duplex; + function compose< + S extends ComposeSource | ComposeTransform, + D extends ComposeTransform | ComposeDestination, + >( + source: S, + destination: D, + ): Duplex; + function compose< + S extends ComposeSource | ComposeTransform, + T extends ComposeTransform, + D extends ComposeTransform | ComposeDestination, + >(source: S, transform: T, destination: D): Duplex; + function compose< + S extends ComposeSource | ComposeTransform, + T1 extends ComposeTransform, + T2 extends ComposeTransform, + D extends ComposeTransform | ComposeDestination, + >(source: S, transform1: T1, transform2: T2, destination: D): Duplex; + function compose< + S extends ComposeSource | ComposeTransform, + T1 extends ComposeTransform, + T2 extends ComposeTransform, + T3 extends ComposeTransform, + D extends ComposeTransform | ComposeDestination, + >(source: S, transform1: T1, transform2: T2, transform3: T3, destination: D): Duplex; + function compose< + S extends ComposeSource | ComposeTransform, + T1 extends ComposeTransform, + T2 extends ComposeTransform, + T3 extends ComposeTransform, + T4 extends ComposeTransform, + D extends ComposeTransform | ComposeDestination, + >(source: S, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: D): Duplex; + function compose( + ...streams: [ + ComposeSource, + ...ComposeTransform[], + ComposeDestination, + ] + ): Duplex; + /* eslint-enable @definitelytyped/no-unnecessary-generics */ + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0, v16.14.0 + */ + function isErrored( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | web.ReadableStream | web.WritableStream, + ): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + * @returns Only returns `null` if `stream` is not a valid `Readable`, `Duplex` or `ReadableStream`. + */ + function isReadable(stream: NodeJS.ReadableStream | web.ReadableStream): boolean | null; + /** + * Returns whether the stream is writable. + * @since v20.0.0 + * @returns Only returns `null` if `stream` is not a valid `Writable`, `Duplex` or `WritableStream`. + */ + function isWritable(stream: NodeJS.WritableStream | web.WritableStream): boolean | null; + } + global { + namespace NodeJS { + // These interfaces are vestigial, and correspond roughly to the "streams2" interfaces + // from early versions of Node.js, but they are still used widely across the ecosystem. + // Accordingly, they are commonly used as "in-types" for @types/node APIs, so that + // eg. streams returned from older libraries will still be considered valid input to + // functions which accept stream arguments. + // It's not possible to change or remove these without astronomical levels of breakage. + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + interface ReadWriteStream extends ReadableStream, WritableStream {} + } + } + export = Stream; +} +declare module "stream" { + import stream = require("node:stream"); + export = stream; +} diff --git a/node_modules/@types/node/stream/consumers.d.ts b/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000..27a474c --- /dev/null +++ b/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,114 @@ +declare module "node:stream/consumers" { + import { Blob, NonSharedBuffer } from "node:buffer"; + import { ReadableStream } from "node:stream/web"; + /** + * ```js + * import { arrayBuffer } from 'node:stream/consumers'; + * import { Readable } from 'node:stream'; + * import { TextEncoder } from 'node:util'; + * + * const encoder = new TextEncoder(); + * const dataArray = encoder.encode('hello world from consumers!'); + * + * const readable = Readable.from(dataArray); + * const data = await arrayBuffer(readable); + * console.log(`from readable: ${data.byteLength}`); + * // Prints: from readable: 76 + * ``` + * @since v16.7.0 + * @returns Fulfills with an `ArrayBuffer` containing the full contents of the stream. + */ + function arrayBuffer(stream: ReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * ```js + * import { blob } from 'node:stream/consumers'; + * + * const dataBlob = new Blob(['hello world from consumers!']); + * + * const readable = dataBlob.stream(); + * const data = await blob(readable); + * console.log(`from readable: ${data.size}`); + * // Prints: from readable: 27 + * ``` + * @since v16.7.0 + * @returns Fulfills with a `Blob` containing the full contents of the stream. + */ + function blob(stream: ReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * ```js + * import { buffer } from 'node:stream/consumers'; + * import { Readable } from 'node:stream'; + * import { Buffer } from 'node:buffer'; + * + * const dataBuffer = Buffer.from('hello world from consumers!'); + * + * const readable = Readable.from(dataBuffer); + * const data = await buffer(readable); + * console.log(`from readable: ${data.length}`); + * // Prints: from readable: 27 + * ``` + * @since v16.7.0 + * @returns Fulfills with a `Buffer` containing the full contents of the stream. + */ + function buffer(stream: ReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * ```js + * import { bytes } from 'node:stream/consumers'; + * import { Readable } from 'node:stream'; + * import { Buffer } from 'node:buffer'; + * + * const dataBuffer = Buffer.from('hello world from consumers!'); + * + * const readable = Readable.from(dataBuffer); + * const data = await bytes(readable); + * console.log(`from readable: ${data.length}`); + * // Prints: from readable: 27 + * ``` + * @since v25.6.0 + * @returns Fulfills with a `Uint8Array` containing the full contents of the stream. + */ + function bytes( + stream: ReadableStream | NodeJS.ReadableStream | AsyncIterable, + ): Promise; + /** + * ```js + * import { json } from 'node:stream/consumers'; + * import { Readable } from 'node:stream'; + * + * const items = Array.from( + * { + * length: 100, + * }, + * () => ({ + * message: 'hello world from consumers!', + * }), + * ); + * + * const readable = Readable.from(JSON.stringify(items)); + * const data = await json(readable); + * console.log(`from readable: ${data.length}`); + * // Prints: from readable: 100 + * ``` + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a + * UTF-8 encoded string that is then passed through `JSON.parse()`. + */ + function json(stream: ReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * ```js + * import { text } from 'node:stream/consumers'; + * import { Readable } from 'node:stream'; + * + * const readable = Readable.from('Hello world from consumers!'); + * const data = await text(readable); + * console.log(`from readable: ${data.length}`); + * // Prints: from readable: 27 + * ``` + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a UTF-8 encoded string. + */ + function text(stream: ReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; +} +declare module "stream/consumers" { + export * from "node:stream/consumers"; +} diff --git a/node_modules/@types/node/stream/promises.d.ts b/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..c4bd3ea --- /dev/null +++ b/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,211 @@ +declare module "node:stream/promises" { + import { Abortable } from "node:events"; + import { + FinishedOptions as _FinishedOptions, + PipelineDestination, + PipelineSource, + PipelineTransform, + } from "node:stream"; + import { ReadableStream, WritableStream } from "node:stream/web"; + interface FinishedOptions extends _FinishedOptions { + /** + * If true, removes the listeners registered by this function before the promise is fulfilled. + * @default false + */ + cleanup?: boolean | undefined; + } + /** + * ```js + * import { finished } from 'node:stream/promises'; + * import { createReadStream } from 'node:fs'; + * + * const rs = createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * The `finished` API also provides a [callback version](https://nodejs.org/docs/latest-v25.x/api/stream.html#streamfinishedstream-options-callback). + * + * `stream.finished()` leaves dangling event listeners (in particular + * `'error'`, `'end'`, `'finish'` and `'close'`) after the returned promise is + * resolved or rejected. The reason for this is so that unexpected `'error'` + * events (due to incorrect stream implementations) do not cause unexpected + * crashes. If this is unwanted behavior then `options.cleanup` should be set to + * `true`: + * + * ```js + * await finished(rs, { cleanup: true }); + * ``` + * @since v15.0.0 + * @returns Fulfills when the stream is no longer readable or writable. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | ReadableStream | WritableStream, + options?: FinishedOptions, + ): Promise; + interface PipelineOptions extends Abortable { + end?: boolean | undefined; + } + type PipelineResult> = S extends (...args: any[]) => PromiseLike + ? Promise + : Promise; + /** + * ```js + * import { pipeline } from 'node:stream/promises'; + * import { createReadStream, createWriteStream } from 'node:fs'; + * import { createGzip } from 'node:zlib'; + * + * await pipeline( + * createReadStream('archive.tar'), + * createGzip(), + * createWriteStream('archive.tar.gz'), + * ); + * console.log('Pipeline succeeded.'); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, as the last argument. + * When the signal is aborted, `destroy` will be called on the underlying pipeline, + * with an `AbortError`. + * + * ```js + * import { pipeline } from 'node:stream/promises'; + * import { createReadStream, createWriteStream } from 'node:fs'; + * import { createGzip } from 'node:zlib'; + * + * const ac = new AbortController(); + * const { signal } = ac; + * setImmediate(() => ac.abort()); + * try { + * await pipeline( + * createReadStream('archive.tar'), + * createGzip(), + * createWriteStream('archive.tar.gz'), + * { signal }, + * ); + * } catch (err) { + * console.error(err); // AbortError + * } + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * import { pipeline } from 'node:stream/promises'; + * import { createReadStream, createWriteStream } from 'node:fs'; + * + * await pipeline( + * createReadStream('lowercase.txt'), + * async function* (source, { signal }) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield await processChunk(chunk, { signal }); + * } + * }, + * createWriteStream('uppercase.txt'), + * ); + * console.log('Pipeline succeeded.'); + * ``` + * + * Remember to handle the `signal` argument passed into the async generator. + * Especially in the case where the async generator is the source for the + * pipeline (i.e. first argument) or the pipeline will never complete. + * + * ```js + * import { pipeline } from 'node:stream/promises'; + * import fs from 'node:fs'; + * await pipeline( + * async function* ({ signal }) { + * await someLongRunningfn({ signal }); + * yield 'asd'; + * }, + * fs.createWriteStream('uppercase.txt'), + * ); + * console.log('Pipeline succeeded.'); + * ``` + * + * The `pipeline` API provides [callback version](https://nodejs.org/docs/latest-v25.x/api/stream.html#streampipelinesource-transforms-destination-callback): + * @since v15.0.0 + * @returns Fulfills when the pipeline is complete. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelineResult; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelineResult; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelineResult; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelineResult; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelineResult; + function pipeline( + streams: readonly [PipelineSource, ...PipelineTransform[], PipelineDestination], + options?: PipelineOptions, + ): Promise; + function pipeline( + ...streams: [PipelineSource, ...PipelineTransform[], PipelineDestination] + ): Promise; + function pipeline( + ...streams: [ + PipelineSource, + ...PipelineTransform[], + PipelineDestination, + options: PipelineOptions, + ] + ): Promise; +} +declare module "stream/promises" { + export * from "node:stream/promises"; +} diff --git a/node_modules/@types/node/stream/web.d.ts b/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..13d55a0 --- /dev/null +++ b/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,296 @@ +declare module "node:stream/web" { + import { TextDecoderCommon, TextDecoderOptions, TextEncoderCommon } from "node:util"; + type CompressionFormat = "brotli" | "deflate" | "deflate-raw" | "gzip"; + type ReadableStreamController = ReadableStreamDefaultController | ReadableByteStreamController; + type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; + type ReadableStreamReaderMode = "byob"; + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + type ReadableStreamType = "bytes"; + interface GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategyInit { + highWaterMark: number; + } + interface QueuingStrategySize { + (chunk: T): number; + } + interface ReadableStreamBYOBReaderReadOptions { + min?: number; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + interface ReadableStreamGetReaderOptions { + mode?: ReadableStreamReaderMode; + } + interface ReadableStreamIteratorOptions { + preventCancel?: boolean; + } + interface ReadableStreamReadDoneResult { + done: true; + value: T | undefined; + } + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableWritablePair { + readable: ReadableStream; + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + preventClose?: boolean; + signal?: AbortSignal; + } + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: UnderlyingSourceCancelCallback; + pull?: (controller: ReadableByteStreamController) => void | PromiseLike; + start?: (controller: ReadableByteStreamController) => any; + type: "bytes"; + } + interface UnderlyingDefaultSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: (controller: ReadableStreamDefaultController) => void | PromiseLike; + start?: (controller: ReadableStreamDefaultController) => any; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSource { + autoAllocateChunkSize?: number; + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: ReadableStreamType; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + interface CompressionStream extends GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + var CompressionStream: { + prototype: CompressionStream; + new(format: CompressionFormat): CompressionStream; + }; + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface DecompressionStream extends GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + var DecompressionStream: { + prototype: DecompressionStream; + new(format: CompressionFormat): DecompressionStream; + }; + interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: NodeJS.NonSharedArrayBufferView): void; + error(e?: any): void; + } + var ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + } + var ReadableStream: { + prototype: ReadableStream; + new( + underlyingSource: UnderlyingByteSource, + strategy?: { highWaterMark?: number }, + ): ReadableStream; + new(underlyingSource: UnderlyingDefaultSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + from(iterable: Iterable | AsyncIterable): ReadableStream; + }; + interface ReadableStreamAsyncIterator extends NodeJS.AsyncIterator { + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + read( + view: T, + options?: ReadableStreamBYOBReaderReadOptions, + ): Promise>; + releaseLock(): void; + } + var ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; + }; + interface ReadableStreamBYOBRequest { + readonly view: NodeJS.NonSharedArrayBufferView | null; + respond(bytesWritten: number): void; + respondWithNewView(view: NodeJS.NonSharedArrayBufferView): void; + } + var ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: R): void; + error(e?: any): void; + } + var ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + var ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + interface TextDecoderStream extends GenericTransformStream, TextDecoderCommon { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + var TextDecoderStream: { + prototype: TextDecoderStream; + new(label?: string, options?: TextDecoderOptions): TextDecoderStream; + }; + interface TextEncoderStream extends GenericTransformStream, TextEncoderCommon { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + var TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + var TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk: O): void; + error(reason?: any): void; + terminate(): void; + } + var TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(e?: any): void; + } + var WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk: W): Promise; + } + var WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; +} +declare module "stream/web" { + export * from "node:stream/web"; +} diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..568e3f6 --- /dev/null +++ b/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,27 @@ +declare module "node:string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: string | NodeJS.ArrayBufferView): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: string | NodeJS.ArrayBufferView): string; + } +} +declare module "string_decoder" { + export * from "node:string_decoder"; +} diff --git a/node_modules/@types/node/test.d.ts b/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000..a3ec5e2 --- /dev/null +++ b/node_modules/@types/node/test.d.ts @@ -0,0 +1,2202 @@ +declare module "node:test" { + import { AssertMethodNames } from "node:assert"; + import { Readable, ReadableEventMap } from "node:stream"; + import { TestEvent } from "node:test/reporters"; + import { URL } from "node:url"; + import TestFn = test.TestFn; + import TestOptions = test.TestOptions; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a suite, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { test }; + export { suite as describe, test as it }; + } + namespace test { + /** + * **Note:** `shard` is used to horizontally parallelize test running across + * machines or processes, ideal for large-scale executions across varied + * environments. It's incompatible with `watch` mode, tailored for rapid + * code iteration by automatically rerunning tests on file changes. + * + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite. This supports the same options as {@link test}. + * @param fn The suite function declaring nested tests and suites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as calling {@link suite} with `options.skip` set to `true`. + * @since v20.13.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as calling {@link suite} with `options.todo` set to `true`. + * @since v20.13.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as calling {@link suite} with `options.only` set to `true`. + * @since v20.13.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + // added in v25.5.0, undocumented + function expectFailure(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function expectFailure(name?: string, fn?: SuiteFn): Promise; + function expectFailure(options?: TestOptions, fn?: SuiteFn): Promise; + function expectFailure(fn?: SuiteFn): Promise; + } + /** + * Shorthand for skipping a test. This is the same as calling {@link test} with `options.skip` set to `true`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`. This is the same as calling {@link test} with `options.todo` set to `true`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`. This is the same as calling {@link test} with `options.only` set to `true`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + // added in v25.5.0, undocumented + function expectFailure(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function expectFailure(name?: string, fn?: TestFn): Promise; + function expectFailure(options?: TestOptions, fn?: TestFn): Promise; + function expectFailure(fn?: TestFn): Promise; + /** + * The type of a function passed to {@link test}. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a suite test function. The argument to this function is a {@link SuiteContext} object. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `total` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many tests would run asynchronously (they are still managed by the single-threaded event loop). + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * Specifies the current working directory to be used by the test runner. + * Serves as the base path for resolving files according to the + * [test runner execution model](https://nodejs.org/docs/latest-v25.x/api/test.html#test-runner-execution-model). + * @since v23.0.0 + * @default process.cwd() + */ + cwd?: string | undefined; + /** + * An array containing the list of files to run. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v25.x/api/test.html#test-runner-execution-model). + */ + files?: readonly string[] | undefined; + /** + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false + */ + forceExit?: boolean | undefined; + /** + * An array containing the list of glob patterns to match test files. + * This option cannot be used together with `files`. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v25.x/api/test.html#test-runner-execution-model). + * @since v22.6.0 + */ + globPatterns?: readonly string[] | undefined; + /** + * Sets inspector port of test child process. + * This can be a number, or a function that takes no arguments and returns a + * number. If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. This option is ignored + * if the `isolation` option is set to `'none'` as no child processes are + * spawned. + * @default undefined + */ + inspectPort?: number | (() => number) | undefined; + /** + * Configures the type of test isolation. If set to + * `'process'`, each test file is run in a separate child process. If set to + * `'none'`, all test files run in the current process. + * @default 'process' + * @since v22.8.0 + */ + isolation?: "process" | "none" | undefined; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean | undefined; + /** + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined + */ + setup?: ((reporter: TestsStream) => void | Promise) | undefined; + /** + * An array of CLI flags to pass to the `node` executable when + * spawning the subprocesses. This option has no effect when `isolation` is `'none`'. + * @since v22.10.0 + * @default [] + */ + execArgv?: readonly string[] | undefined; + /** + * An array of CLI flags to pass to each test file when spawning the + * subprocesses. This option has no effect when `isolation` is `'none'`. + * @since v22.10.0 + * @default [] + */ + argv?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * If provided, only run tests whose name matches the provided pattern. + * Strings are interpreted as JavaScript regular expressions. + * @default undefined + */ + testNamePatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * A String, RegExp or a RegExp Array, that can be used to exclude running tests whose + * name matches the provided pattern. Test name patterns are interpreted as JavaScript + * regular expressions. For each test that is executed, any corresponding test hooks, + * such as `beforeEach()`, are also run. + * @default undefined + * @since v22.1.0 + */ + testSkipPatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * The number of milliseconds after which the test execution will fail. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + /** + * A file path where the test runner will + * store the state of the tests to allow rerunning only the failed tests on a next run. + * @since v24.7.0 + * @default undefined + */ + rerunFailuresFilePath?: string | undefined; + /** + * enable [code coverage](https://nodejs.org/docs/latest-v25.x/api/test.html#collecting-code-coverage) collection. + * @since v22.10.0 + * @default false + */ + coverage?: boolean | undefined; + /** + * Excludes specific files from code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageExcludeGlobs?: string | readonly string[] | undefined; + /** + * Includes specific files in code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageIncludeGlobs?: string | readonly string[] | undefined; + /** + * Require a minimum percent of covered lines. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + lineCoverage?: number | undefined; + /** + * Require a minimum percent of covered branches. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + branchCoverage?: number | undefined; + /** + * Require a minimum percent of covered functions. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + functionCoverage?: number | undefined; + /** + * Specify environment variables to be passed along to the test process. + * This options is not compatible with `isolation='none'`. These variables will override + * those from the main process, and are not merged with `process.env`. + * @since v25.6.0 + */ + env?: NodeJS.ProcessEnv | undefined; + } + interface TestsStreamEventMap extends ReadableEventMap { + "data": [data: TestEvent]; + "test:coverage": [data: EventData.TestCoverage]; + "test:complete": [data: EventData.TestComplete]; + "test:dequeue": [data: EventData.TestDequeue]; + "test:diagnostic": [data: EventData.TestDiagnostic]; + "test:enqueue": [data: EventData.TestEnqueue]; + "test:fail": [data: EventData.TestFail]; + "test:pass": [data: EventData.TestPass]; + "test:plan": [data: EventData.TestPlan]; + "test:start": [data: EventData.TestStart]; + "test:stderr": [data: EventData.TestStderr]; + "test:stdout": [data: EventData.TestStdout]; + "test:summary": [data: EventData.TestSummary]; + "test:watch:drained": []; + "test:watch:restarted": []; + } + /** + * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. + * @since v18.9.0, v16.19.0 + */ + interface TestsStream extends Readable { + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: TestsStreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: TestsStreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: TestsStreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: TestsStreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + namespace EventData { + interface Error extends globalThis.Error { + cause: unknown; + } + interface LocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test was run through the REPL. + */ + file?: string; + /** + * The line number where the test is defined, or `undefined` if the test was run through the REPL. + */ + line?: number; + } + interface TestDiagnostic extends LocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The severity level of the diagnostic message. + * Possible values are: + * * `'info'`: Informational messages. + * * `'warn'`: Warnings. + * * `'error'`: Errors. + */ + level: "info" | "warn" | "error"; + } + interface TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of branches representing branch coverage. + */ + branches: Array<{ + /** + * The line number where the branch is defined. + */ + line: number; + /** + * The number of times the branch was taken. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing whether or not the coverage for + * each coverage type. + * @since v22.9.0 + */ + thresholds: { + /** + * The function coverage threshold. + */ + function: number; + /** + * The branch coverage threshold. + */ + branch: number; + /** + * The line coverage threshold. + */ + line: number; + }; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestComplete extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error?: Error; + /** + * The type of the test, used to denote whether this is a suite. + */ + type?: "suite" | "test"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestDequeue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestEnqueue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestFail extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since v20.0.0, v19.9.0, v18.17.0 + */ + type?: "suite" | "test"; + /** + * The attempt number of the test run, + * present only when using the `--test-rerun-failures` flag. + * @since v24.7.0 + */ + attempt?: number; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPass extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite" | "test"; + /** + * The attempt number of the test run, + * present only when using the `--test-rerun-failures` flag. + * @since v24.7.0 + */ + attempt?: number; + /** + * The attempt number the test passed on, + * present only when using the `--test-rerun-failures` flag. + * @since v24.7.0 + */ + passed_on_attempt?: number; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPlan extends LocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; + } + interface TestStart extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestStderr { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stderr`. + */ + message: string; + } + interface TestStdout { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stdout`. + */ + message: string; + } + interface TestSummary { + /** + * An object containing the counts of various test results. + */ + counts: { + /** + * The total number of cancelled tests. + */ + cancelled: number; + /** + * The total number of passed tests. + */ + passed: number; + /** + * The total number of skipped tests. + */ + skipped: number; + /** + * The total number of suites run. + */ + suites: number; + /** + * The total number of tests run, excluding suites. + */ + tests: number; + /** + * The total number of TODO tests. + */ + todo: number; + /** + * The total number of top level tests and suites. + */ + topLevel: number; + }; + /** + * The duration of the test run in milliseconds. + */ + duration_ms: number; + /** + * The path of the test file that generated the + * summary. If the summary corresponds to multiple files, this value is + * `undefined`. + */ + file: string | undefined; + /** + * Indicates whether or not the test run is considered + * successful or not. If any error condition occurs, such as a failing test or + * unmet coverage threshold, this value will be set to `false`. + */ + success: boolean; + } + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + interface TestContext { + /** + * An object containing assertion methods bound to the test context. + * The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans. + * + * **Note:** Some of the functions from `node:assert` contain type assertions. If these are called via the + * TestContext `assert` object, then the context parameter in the test's function signature **must be explicitly typed** + * (ie. the parameter must have a type annotation), otherwise an error will be raised by the TypeScript compiler: + * ```ts + * import { test, type TestContext } from 'node:test'; + * + * // The test function's context parameter must have a type annotation. + * test('example', (t: TestContext) => { + * t.assert.deepStrictEqual(actual, expected); + * }); + * + * // Omitting the type annotation will result in a compilation error. + * test('example', t => { + * t.assert.deepStrictEqual(actual, expected); // Error: 't' needs an explicit type annotation. + * }); + * ``` + * @since v22.2.0, v20.15.0 + */ + readonly assert: TestContextAssert; + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v20.1.0, v18.17.0 + */ + before(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The absolute path of the test file that created the current test. If a test file imports + * additional modules that generate tests, the imported tests will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the test and each of its ancestors, separated by `>`. + * @since v22.3.0 + */ + readonly fullName: string; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Indicated whether the test succeeded. + * @since v21.7.0, v20.12.0 + */ + readonly passed: boolean; + /** + * The failure reason for the test/case; wrapped and available via `context.error.cause`. + * @since v21.7.0, v20.12.0 + */ + readonly error: EventData.Error | null; + /** + * Number of times the test has been attempted. + * @since v21.7.0, v20.12.0 + */ + readonly attempt: number; + /** + * This function is used to set the number of assertions and subtests that are expected to run + * within the test. If the number of assertions and subtests that run does not match the + * expected count, the test will fail. + * + * > Note: To make sure assertions are tracked, `t.assert` must be used instead of `assert` directly. + * + * ```js + * test('top level test', (t) => { + * t.plan(2); + * t.assert.ok('some relevant assertion here'); + * t.test('subtest', () => {}); + * }); + * ``` + * + * When working with asynchronous code, the `plan` function can be used to ensure that the + * correct number of assertions are run: + * + * ```js + * test('planning with streams', (t, done) => { + * function* generate() { + * yield 'a'; + * yield 'b'; + * yield 'c'; + * } + * const expected = ['a', 'b', 'c']; + * t.plan(expected.length); + * const stream = Readable.from(generate()); + * stream.on('data', (chunk) => { + * t.assert.strictEqual(chunk, expected.shift()); + * }); + * + * stream.on('end', () => { + * done(); + * }); + * }); + * ``` + * + * When using the `wait` option, you can control how long the test will wait for the expected assertions. + * For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions + * to complete within the specified timeframe: + * + * ```js + * test('plan with wait: 2000 waits for async assertions', (t) => { + * t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete. + * + * const asyncActivity = () => { + * setTimeout(() => { + * * t.assert.ok(true, 'Async assertion completed within the wait time'); + * }, 1000); // Completes after 1 second, within the 2-second wait time. + * }; + * + * asyncActivity(); // The test will pass because the assertion is completed in time. + * }); + * ``` + * + * Note: If a `wait` timeout is specified, it begins counting down only after the test function finishes executing. + * @since v22.2.0 + */ + plan(count: number, options?: TestContextPlanOptions): void; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. This first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * This method polls a `condition` function until that function either returns + * successfully or the operation times out. + * @since v22.14.0 + * @param condition An assertion function that is invoked + * periodically until it completes successfully or the defined polling timeout + * elapses. Successful completion is defined as not throwing or rejecting. This + * function does not accept any arguments, and is allowed to return any value. + * @param options An optional configuration object for the polling operation. + * @returns Fulfilled with the value returned by `condition`. + */ + waitFor(condition: () => T, options?: TestContextWaitForOptions): Promise>; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + interface TestContextAssert extends Pick { + /** + * This function serializes `value` and writes it to the file specified by `path`. + * + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json'); + * }); + * ``` + * + * This function differs from `context.assert.snapshot()` in the following ways: + * + * * The snapshot file path is explicitly provided by the user. + * * Each snapshot file is limited to a single snapshot value. + * * No additional escaping is performed by the test runner. + * + * These differences allow snapshot files to better support features such as syntax + * highlighting. + * @since v22.14.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * `path`. Otherwise, the serialized value is compared to the contents of the + * existing snapshot file. + * @param path The file where the serialized `value` is written. + * @param options Optional configuration options. + */ + fileSnapshot(value: any, path: string, options?: AssertSnapshotOptions): void; + /** + * This function implements assertions for snapshot testing. + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.snapshot({ value1: 1, value2: 2 }); + * }); + * + * test('snapshot test with custom serialization', (t) => { + * t.assert.snapshot({ value3: 3, value4: 4 }, { + * serializers: [(value) => JSON.stringify(value)] + * }); + * }); + * ``` + * @since v22.3.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * the snapshot file. Otherwise, the serialized value is compared to the + * corresponding value in the existing snapshot file. + */ + snapshot(value: any, options?: AssertSnapshotOptions): void; + /** + * A custom assertion function registered with `assert.register()`. + */ + [name: string]: (...args: any[]) => void; + } + interface AssertSnapshotOptions { + /** + * An array of synchronous functions used to serialize `value` into a string. + * `value` is passed as the only argument to the first serializer function. + * The return value of each serializer is passed as input to the next serializer. + * Once all serializers have run, the resulting value is coerced to a string. + * + * If no serializers are provided, the test runner's default serializers are used. + */ + serializers?: ReadonlyArray<(value: any) => any> | undefined; + } + interface TestContextPlanOptions { + /** + * The wait time for the plan: + * * If `true`, the plan waits indefinitely for all assertions and subtests to run. + * * If `false`, the plan performs an immediate check after the test function completes, + * without waiting for any pending assertions or subtests. + * Any assertions or subtests that complete after this check will not be counted towards the plan. + * * If a number, it specifies the maximum wait time in milliseconds + * before timing out while waiting for expected assertions and subtests to be matched. + * If the timeout is reached, the test will fail. + * @default false + */ + wait?: boolean | number | undefined; + } + interface TestContextWaitForOptions { + /** + * The number of milliseconds to wait after an unsuccessful + * invocation of `condition` before trying again. + * @default 50 + */ + interval?: number | undefined; + /** + * The poll timeout in milliseconds. If `condition` has not + * succeeded by the time this elapses, an error occurs. + * @default 1000 + */ + timeout?: number | undefined; + } + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + interface SuiteContext { + /** + * The absolute path of the test file that created the current suite. If a test file imports + * additional modules that generate suites, the imported suites will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the suite and each of its ancestors, separated by `>`. + * @since v22.3.0, v20.16.0 + */ + readonly fullName: string; + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + /** + * The number of assertions and subtests expected to be run in the test. + * If the number of assertions run in the test does not match the number + * specified in the plan, the test will fail. + * @default undefined + * @since v22.2.0 + */ + plan?: number | undefined; + // added in v25.5.0, undocumented + expectFailure?: boolean | undefined; + } + /** + * This function creates a hook that runs before executing a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * // Some relevant assertion here + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after executing a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * // Some relevant assertion here + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs before each test in the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * // Some relevant assertion here + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * // Some relevant assertion here + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. The first argument is the context in which the hook is called. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any; + /** + * The hook function. The first argument is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type TestContextHookFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + interface MockModuleOptions { + /** + * If false, each call to `require()` or `import()` generates a new mock module. + * If true, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache. + * @default false + */ + cache?: boolean | undefined; + /** + * The value to use as the mocked module's default export. + * + * If this value is not provided, ESM mocks do not include a default export. + * If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. + * If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`. + */ + defaultExport?: any; + /** + * An object whose keys and values are used to create the named exports of the mock module. + * + * If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. + * Therefore, if a mock is created with both named exports and a non-object default export, + * the mock will throw an exception when used as a CJS or builtin module. + */ + namedExports?: object | undefined; + } + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. + * @since v19.1.0, v18.13.0 + */ + interface MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param original An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn undefined>( + original?: F, + options?: MockFunctionOptions, + ): Mock; + fn undefined, Implementation extends Function = F>( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function is used to mock the exports of ECMAScript modules, CommonJS modules, JSON modules, and + * Node.js builtin modules. Any references to the original module prior to mocking are not impacted. In + * order to enable module mocking, Node.js must be started with the + * [`--experimental-test-module-mocks`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--experimental-test-module-mocks) + * command-line flag. + * + * The following example demonstrates how a mock is created for a module. + * + * ```js + * test('mocks a builtin module in both module systems', async (t) => { + * // Create a mock of 'node:readline' with a named export named 'fn', which + * // does not exist in the original 'node:readline' module. + * const mock = t.mock.module('node:readline', { + * namedExports: { fn() { return 42; } }, + * }); + * + * let esmImpl = await import('node:readline'); + * let cjsImpl = require('node:readline'); + * + * // cursorTo() is an export of the original 'node:readline' module. + * assert.strictEqual(esmImpl.cursorTo, undefined); + * assert.strictEqual(cjsImpl.cursorTo, undefined); + * assert.strictEqual(esmImpl.fn(), 42); + * assert.strictEqual(cjsImpl.fn(), 42); + * + * mock.restore(); + * + * // The mock is restored, so the original builtin module is returned. + * esmImpl = await import('node:readline'); + * cjsImpl = require('node:readline'); + * + * assert.strictEqual(typeof esmImpl.cursorTo, 'function'); + * assert.strictEqual(typeof cjsImpl.cursorTo, 'function'); + * assert.strictEqual(esmImpl.fn, undefined); + * assert.strictEqual(cjsImpl.fn, undefined); + * }); + * ``` + * @since v22.3.0 + * @experimental + * @param specifier A string identifying the module to mock. + * @param options Optional configuration options for the mock module. + */ + module(specifier: string | URL, options?: MockModuleOptions): MockModuleContext; + /** + * Creates a mock for a property value on an object. This allows you to track and control access to a specific property, + * including how many times it is read (getter) or written (setter), and to restore the original value after mocking. + * + * ```js + * test('mocks a property value', (t) => { + * const obj = { foo: 42 }; + * const prop = t.mock.property(obj, 'foo', 100); + * + * assert.strictEqual(obj.foo, 100); + * assert.strictEqual(prop.mock.accessCount(), 1); + * assert.strictEqual(prop.mock.accesses[0].type, 'get'); + * assert.strictEqual(prop.mock.accesses[0].value, 100); + * + * obj.foo = 200; + * assert.strictEqual(prop.mock.accessCount(), 2); + * assert.strictEqual(prop.mock.accesses[1].type, 'set'); + * assert.strictEqual(prop.mock.accesses[1].value, 200); + * + * prop.mock.restore(); + * assert.strictEqual(obj.foo, 42); + * }); + * ``` + * @since v24.3.0 + * @param object The object whose value is being mocked. + * @param propertyName The identifier of the property on `object` to mock. + * @param value An optional value used as the mock value + * for `object[propertyName]`. **Default:** The original property value. + * @returns A proxy to the mocked object. The mocked object contains a + * special `mock` property, which is an instance of [`MockPropertyContext`][], and + * can be used for inspecting and changing the behavior of the mocked property. + */ + property< + MockedObject extends object, + PropertyName extends keyof MockedObject, + >( + object: MockedObject, + property: PropertyName, + value?: MockedObject[PropertyName], + ): MockedObject & { mock: MockPropertyContext }; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + readonly timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + interface MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: MockFunctionCall[]; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: F): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: F, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + /** + * @since v22.3.0 + * @experimental + */ + interface MockModuleContext { + /** + * Resets the implementation of the mock module. + * @since v22.3.0 + */ + restore(): void; + } + /** + * @since v24.3.0 + */ + class MockPropertyContext { + /** + * A getter that returns a copy of the internal array used to track accesses (get/set) to + * the mocked property. Each entry in the array is an object with the following properties: + */ + readonly accesses: Array<{ + type: "get" | "set"; + value: PropertyType; + stack: Error; + }>; + /** + * This function returns the number of times that the property was accessed. + * This function is more efficient than checking `ctx.accesses.length` because + * `ctx.accesses` is a getter that creates a copy of the internal access tracking array. + * @returns The number of times that the property was accessed (read or written). + */ + accessCount(): number; + /** + * This function is used to change the value returned by the mocked property getter. + * @param value The new value to be set as the mocked property value. + */ + mockImplementation(value: PropertyType): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onAccess` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.property()`, calls the + * mock property, changes the mock implementation to a different value for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * const obj = { foo: 1 }; + * + * const prop = t.mock.property(obj, 'foo', 5); + * + * assert.strictEqual(obj.foo, 5); + * prop.mock.mockImplementationOnce(25); + * assert.strictEqual(obj.foo, 25); + * assert.strictEqual(obj.foo, 5); + * }); + * ``` + * @param value The value to be used as the mock's + * implementation for the invocation number specified by `onAccess`. + * @param onAccess The invocation number that will use `value`. If + * the specified invocation has already occurred then an exception is thrown. + * **Default:** The number of the next invocation. + */ + mockImplementationOnce(value: PropertyType, onAccess?: number): void; + /** + * Resets the access history of the mocked property. + */ + resetAccesses(): void; + /** + * Resets the implementation of the mock property to its original behavior. The + * mock can still be used after calling this function. + */ + restore(): void; + } + interface MockTimersOptions { + apis: ReadonlyArray<"setInterval" | "setTimeout" | "setImmediate" | "Date">; + now?: number | Date | undefined; + } + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The MockTimers API also allows for mocking of the `Date` constructor and + * `setImmediate`/`clearImmediate` functions. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + */ + interface MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * **Note:** Mocking `Date` will affect the behavior of the mocked timers + * as they use the same internal clock. + * + * Example usage without setting initial time: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); + * ``` + * + * The above example enables mocking for the `Date` constructor, `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. + * + * Example usage with initial time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: 1000 }); + * ``` + * + * Example usage with initial Date object as time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: new Date() }); + * ``` + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. + * + * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * The `Date` constructor from `globalThis` will be mocked. + * + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. + * @since v20.4.0 + */ + enable(options?: MockTimersOptions): void; + /** + * Sets the current Unix timestamp that will be used as reference for any mocked + * `Date` objects. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * const now = Date.now(); + * const setTime = 1000; + * // Date.now is not mocked + * assert.deepStrictEqual(Date.now(), now); + * + * context.mock.timers.enable({ apis: ['Date'] }); + * context.mock.timers.setTime(setTime); + * // Date.now is now 1000 + * assert.strictEqual(Date.now(), setTime); + * }); + * ``` + * @since v21.2.0, v20.11.0 + */ + setTime(milliseconds: number): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Advancing time using `.tick` will also advance the time for any `Date` object + * created after the mock was enabled (if `Date` was also set to be mocked). + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * assert.strictEqual(Date.now(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * assert.strictEqual(fn.mock.callCount(), 1); + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. If the `Date` object is also + * mocked, it will also advance the `Date` object to the furthest timer's time. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * assert.deepStrictEqual(results, [3, 2, 1]); + * // The Date object is also advanced to the furthest timer's time + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + /** + * An object whose methods are used to configure available assertions on the + * `TestContext` objects in the current process. The methods from `node:assert` + * and snapshot testing functions are available by default. + * + * It is possible to apply the same configuration to all files by placing common + * configuration code in a module + * preloaded with `--require` or `--import`. + * @since v22.14.0 + */ + namespace assert { + /** + * Defines a new assertion function with the provided name and function. If an + * assertion already exists with the same name, it is overwritten. + * @since v22.14.0 + */ + function register(name: string, fn: (this: TestContext, ...args: any[]) => void): void; + } + /** + * @since v22.3.0 + */ + namespace snapshot { + /** + * This function is used to customize the default serialization mechanism used by the test runner. + * + * By default, the test runner performs serialization by calling `JSON.stringify(value, null, 2)` on the provided value. + * `JSON.stringify()` does have limitations regarding circular structures and supported data types. + * If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers. + * + * Serializers are called in order, with the output of the previous serializer passed as input to the next. + * The final result must be a string value. + * @since v22.3.0 + * @param serializers An array of synchronous functions used as the default serializers for snapshot tests. + */ + function setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): void; + /** + * This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. + * By default, the snapshot filename is the same as the entry point filename with `.snapshot` appended. + * @since v22.3.0 + * @param fn A function used to compute the location of the snapshot file. + * The function receives the path of the test file as its only argument. If the + * test is not associated with a file (for example in the REPL), the input is + * undefined. `fn()` must return a string specifying the location of the snapshot file. + */ + function setResolveSnapshotPath(fn: (path: string | undefined) => string): void; + } + } + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + export = test; +} diff --git a/node_modules/@types/node/test/reporters.d.ts b/node_modules/@types/node/test/reporters.d.ts new file mode 100644 index 0000000..e04d669 --- /dev/null +++ b/node_modules/@types/node/test/reporters.d.ts @@ -0,0 +1,58 @@ +declare module "node:test/reporters" { + import { Transform, TransformOptions } from "node:stream"; + import { EventData } from "node:test"; + type TestEvent = + | { type: "test:coverage"; data: EventData.TestCoverage } + | { type: "test:complete"; data: EventData.TestComplete } + | { type: "test:dequeue"; data: EventData.TestDequeue } + | { type: "test:diagnostic"; data: EventData.TestDiagnostic } + | { type: "test:enqueue"; data: EventData.TestEnqueue } + | { type: "test:fail"; data: EventData.TestFail } + | { type: "test:pass"; data: EventData.TestPass } + | { type: "test:plan"; data: EventData.TestPlan } + | { type: "test:start"; data: EventData.TestStart } + | { type: "test:stderr"; data: EventData.TestStderr } + | { type: "test:stdout"; data: EventData.TestStdout } + | { type: "test:summary"; data: EventData.TestSummary } + | { type: "test:watch:drained"; data: undefined } + | { type: "test:watch:restarted"; data: undefined }; + interface ReporterConstructorWrapper Transform> { + new(...args: ConstructorParameters): InstanceType; + (...args: ConstructorParameters): InstanceType; + } + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + * @since v20.0.0 + */ + function dot(source: AsyncIterable): NodeJS.AsyncIterator; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + * @since v20.0.0 + */ + function tap(source: AsyncIterable): NodeJS.AsyncIterator; + class SpecReporter extends Transform { + constructor(); + } + /** + * The `spec` reporter outputs the test results in a human-readable format. + * @since v20.0.0 + */ + const spec: ReporterConstructorWrapper; + /** + * The `junit` reporter outputs test results in a jUnit XML format. + * @since v21.0.0 + */ + function junit(source: AsyncIterable): NodeJS.AsyncIterator; + class LcovReporter extends Transform { + constructor(options?: Omit); + } + /** + * The `lcov` reporter outputs test coverage when used with the + * [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--experimental-test-coverage) flag. + * @since v22.0.0 + */ + const lcov: ReporterConstructorWrapper; + export { dot, junit, lcov, spec, tap, TestEvent }; +} diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..5b74b89 --- /dev/null +++ b/node_modules/@types/node/timers.d.ts @@ -0,0 +1,149 @@ +declare module "node:timers" { + import { Abortable } from "node:events"; + import * as promises from "node:timers/promises"; + export interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + global { + namespace NodeJS { + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by + * `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` + * functions that can be used to control this default behavior. + */ + interface Immediate extends RefCounted, Disposable { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + unref(): this; + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0, v18.18.0 + */ + [Symbol.dispose](): void; + _onImmediate(...args: any[]): void; + } + // Legacy interface used in Node.js v9 and prior + // TODO: remove in a future major version bump + /** @deprecated Use `NodeJS.Timeout` instead. */ + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setTimeout()` and + * `setInterval()`. It can be passed to either `clearTimeout()` or + * `clearInterval()` in order to cancel the scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or + * `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + interface Timeout extends RefCounted, Disposable, Timer { + /** + * Cancels the timeout. + * @since v0.9.1 + * @legacy Use `clearTimeout()` instead. + * @returns a reference to `timeout` + */ + close(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + ref(): this; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @returns a reference to `timeout` + */ + refresh(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling + * `timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + unref(): this; + /** + * Coerce a `Timeout` to a primitive. The primitive can be used to + * clear the `Timeout`. The primitive can only be used in the + * same thread where the timeout was created. Therefore, to use it + * across `worker_threads` it must first be passed to the correct + * thread. This allows enhanced compatibility with browser + * `setTimeout()` and `setInterval()` implementations. + * @since v14.9.0, v12.19.0 + */ + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0, v18.18.0 + */ + [Symbol.dispose](): void; + _onTimeout(...args: any[]): void; + } + } + } + import clearImmediate = globalThis.clearImmediate; + import clearInterval = globalThis.clearInterval; + import clearTimeout = globalThis.clearTimeout; + import setImmediate = globalThis.setImmediate; + import setInterval = globalThis.setInterval; + import setTimeout = globalThis.setTimeout; + export { clearImmediate, clearInterval, clearTimeout, promises, setImmediate, setInterval, setTimeout }; +} +declare module "timers" { + export * from "node:timers"; +} diff --git a/node_modules/@types/node/timers/promises.d.ts b/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..8e178ea --- /dev/null +++ b/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,93 @@ +declare module "node:timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'node:timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param delay The number of milliseconds to wait before fulfilling the + * promise. **Default:** `1`. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'node:timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```js + * import { + * setInterval, + * } from 'node:timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + * @param delay The number of milliseconds to wait between iterations. + * **Default:** `1`. + * @param value A value with which the iterator returns. + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): NodeJS.AsyncIterator; + interface Scheduler { + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent + * to calling `timersPromises.setTimeout(delay, undefined, options)` except that + * the `ref` option is not supported. + * + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * @since v17.3.0, v16.14.0 + * @experimental + * @param delay The number of milliseconds to wait before resolving the + * promise. + */ + wait(delay: number, options?: { signal?: AbortSignal }): Promise; + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.yield()` is equivalent to calling + * `timersPromises.setImmediate()` with no arguments. + * @since v17.3.0, v16.14.0 + * @experimental + */ + yield(): Promise; + } + const scheduler: Scheduler; +} +declare module "timers/promises" { + export * from "node:timers/promises"; +} diff --git a/node_modules/@types/node/tls.d.ts b/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..3efd2ae --- /dev/null +++ b/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1193 @@ +declare module "node:tls" { + import { NonSharedBuffer } from "node:buffer"; + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate extends NodeJS.Dict { + /** + * Country code. + */ + C?: string | string[]; + /** + * Street. + */ + ST?: string | string[]; + /** + * Locality. + */ + L?: string | string[]; + /** + * Organization. + */ + O?: string | string[]; + /** + * Organizational unit. + */ + OU?: string | string[]; + /** + * Common name. + */ + CN?: string | string[]; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: NonSharedBuffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: NonSharedBuffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve, if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + } + interface TLSSocketEventMap extends net.SocketEventMap { + "keylog": [line: NonSharedBuffer]; + "OCSPResponse": [response: NonSharedBuffer]; + "secure": []; + "secureConnect": []; + "session": [session: NonSharedBuffer]; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * String containing the server name requested via SNI (Server Name Indication) TLS extension. + */ + servername: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): NonSharedBuffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): NonSharedBuffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): NonSharedBuffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): NonSharedBuffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setKeyCert()` method sets the private key and certificate to use for the socket. + * This is mainly useful if you wish to select a server certificate from a TLS server's `ALPNCallback`. + * @since v22.5.0, v20.17.0 + * @param context An object containing at least `key` and `cert` properties from the {@link createSecureContext()} `options`, + * or a TLS context object created with {@link createSecureContext()} itself. + */ + setKeyCert(context: SecureContextOptions | SecureContext): void; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): NonSharedBuffer; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: TLSSocketEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: TLSSocketEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: TLSSocketEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: TLSSocketEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: TLSSocketEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: TLSSocketEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: E, listener: (...args: TLSSocketEventMap[E]) => void): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: TLSSocketEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: TLSSocketEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: TLSSocketEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: TLSSocketEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings, or a single `Buffer`, `TypedArray`, or `DataView` containing the supported + * ALPN protocols. Buffers should have the format `[len][name][len][name]...` + * e.g. `'\x08http/1.1\x08http/1.0'`, where the `len` byte is the length of the + * next protocol name. Passing an array is usually much simpler, e.g. + * `['http/1.1', 'http/1.0']`. Protocols earlier in the list have higher + * preference than those later. + */ + ALPNProtocols?: readonly string[] | NodeJS.ArrayBufferView | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication. + */ + requestOCSP?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?: ((socket: TLSSocket, identity: string) => NodeJS.ArrayBufferView | null) | undefined; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: NodeJS.ArrayBufferView; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?: ((hint: string | null) => PSKCallbackNegotation | null) | undefined; + } + interface ServerEventMap extends net.ServerEventMap { + "connection": [socket: net.Socket]; + "keylog": [line: NonSharedBuffer, tlsSocket: TLSSocket]; + "newSession": [sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void]; + "OCSPRequest": [ + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ]; + "resumeSession": [sessionId: Buffer, callback: (err: Error | null, sessionData?: Buffer) => void]; + "secureConnection": [tlsSocket: TLSSocket]; + "tlsClientError": [exception: Error, tlsSocket: TLSSocket]; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions | SecureContext): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): NonSharedBuffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + // #region InternalEventEmitter + addListener(eventName: E, listener: (...args: ServerEventMap[E]) => void): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ServerEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ServerEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: ServerEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: ServerEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: ServerEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: E, listener: (...args: ServerEventMap[E]) => void): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: ServerEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Treat intermediate (non-self-signed) + * certificates in the trust CA certificate list as trusted. + * @since v22.9.0, v20.18.0 + */ + allowPartialTrustChain?: boolean | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + * @deprecated + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + * @deprecated + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + * @deprecated + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom `options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * `{@link createServer}` sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array containing the CA certificates from various sources, depending on `type`: + * + * * `"default"`: return the CA certificates that will be used by the Node.js TLS clients by default. + * * When `--use-bundled-ca` is enabled (default), or `--use-openssl-ca` is not enabled, + * this would include CA certificates from the bundled Mozilla CA store. + * * When `--use-system-ca` is enabled, this would also include certificates from the system's + * trusted store. + * * When `NODE_EXTRA_CA_CERTS` is used, this would also include certificates loaded from the specified + * file. + * * `"system"`: return the CA certificates that are loaded from the system's trusted store, according + * to rules set by `--use-system-ca`. This can be used to get the certificates from the system + * when `--use-system-ca` is not enabled. + * * `"bundled"`: return the CA certificates from the bundled Mozilla CA store. This would be the same + * as `tls.rootCertificates`. + * * `"extra"`: return the CA certificates loaded from `NODE_EXTRA_CA_CERTS`. It's an empty array if + * `NODE_EXTRA_CA_CERTS` is not set. + * @since v22.15.0 + * @param type The type of CA certificates that will be returned. Valid values + * are `"default"`, `"system"`, `"bundled"` and `"extra"`. + * **Default:** `"default"`. + * @returns An array of PEM-encoded certificates. The array may contain duplicates + * if the same certificate is repeatedly stored in multiple sources. + */ + function getCACertificates(type?: "default" | "system" | "bundled" | "extra"): string[]; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of `{@link createSecureContext}`. + * + * Not all supported ciphers are enabled by default. See + * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v25.x/api/tls.html#modifying-the-default-tls-cipher-suite). + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * Sets the default CA certificates used by Node.js TLS clients. If the provided + * certificates are parsed successfully, they will become the default CA + * certificate list returned by {@link getCACertificates} and used + * by subsequent TLS connections that don't specify their own CA certificates. + * The certificates will be deduplicated before being set as the default. + * + * This function only affects the current Node.js thread. Previous + * sessions cached by the HTTPS agent won't be affected by this change, so + * this method should be called before any unwanted cachable TLS connections are + * made. + * + * To use system CA certificates as the default: + * + * ```js + * import tls from 'node:tls'; + * tls.setDefaultCACertificates(tls.getCACertificates('system')); + * ``` + * + * This function completely replaces the default CA certificate list. To add additional + * certificates to the existing defaults, get the current certificates and append to them: + * + * ```js + * import tls from 'node:tls'; + * const currentCerts = tls.getCACertificates('default'); + * const additionalCerts = ['-----BEGIN CERTIFICATE-----\n...']; + * tls.setDefaultCACertificates([...currentCerts, ...additionalCerts]); + * ``` + * @since v24.5.0 + * @param certs An array of CA certificates in PEM format. + */ + function setDefaultCACertificates(certs: ReadonlyArray): void; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is `'auto'`. See `{@link createSecureContext()}` for further + * information. + * @since v0.11.13 + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the `maxVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless + * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using + * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the highest maximum is used. + * @since v11.4.0 + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the `minVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless + * changed using CLI options. Using `--tls-min-v1.0` sets the default to + * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using + * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the lowest minimum is used. + * @since v11.4.0 + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the `ciphers` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless + * changed using CLI options using `--tls-default-ciphers`. + * @since v19.8.0 + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 + */ + const rootCertificates: readonly string[]; +} +declare module "tls" { + export * from "node:tls"; +} diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..5fa7a39 --- /dev/null +++ b/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,103 @@ +declare module "node:trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + * @since v10.0.0 + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); + * t1.enable(); + * t2.enable(); + * + * // Prints 'node,node.perf,v8' + * console.log(trace_events.getEnabledCategories()); + * + * t2.disable(); // Will only disable emission of the 'node.perf' category + * + * // Prints 'node,v8' + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + * @since v10.0.0 + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + * @since v10.0.0 + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * import trace_events from 'node:trace_events'; + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "trace_events" { + export * from "node:trace_events"; +} diff --git a/node_modules/@types/node/ts5.6/buffer.buffer.d.ts b/node_modules/@types/node/ts5.6/buffer.buffer.d.ts new file mode 100644 index 0000000..118041b --- /dev/null +++ b/node_modules/@types/node/ts5.6/buffer.buffer.d.ts @@ -0,0 +1,462 @@ +declare module "node:buffer" { + global { + interface BufferConstructor { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBufferLike): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it must be an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBuffer = Buffer; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type AllowSharedBuffer = Buffer; + } +} diff --git a/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts b/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts new file mode 100644 index 0000000..f148cc4 --- /dev/null +++ b/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts @@ -0,0 +1,71 @@ +// Interface declaration for Float16Array, required in @types/node v24+. +// These definitions are specific to TS <=5.6. + +// This needs all of the "common" properties/methods of the TypedArrays, +// otherwise the type unions `TypedArray` and `ArrayBufferView` will be +// empty objects. +interface Float16Array extends Pick { + readonly BYTES_PER_ELEMENT: number; + readonly buffer: ArrayBufferLike; + readonly byteLength: number; + readonly byteOffset: number; + readonly length: number; + readonly [Symbol.toStringTag]: "Float16Array"; + at(index: number): number | undefined; + copyWithin(target: number, start: number, end?: number): this; + every(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): boolean; + fill(value: number, start?: number, end?: number): this; + filter(predicate: (value: number, index: number, array: Float16Array) => any, thisArg?: any): Float16Array; + find(predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any): number | undefined; + findIndex(predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any): number; + findLast( + predicate: (value: number, index: number, array: Float16Array) => value is S, + thisArg?: any, + ): S | undefined; + findLast( + predicate: (value: number, index: number, array: Float16Array) => unknown, + thisArg?: any, + ): number | undefined; + findLastIndex(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): number; + forEach(callbackfn: (value: number, index: number, array: Float16Array) => void, thisArg?: any): void; + includes(searchElement: number, fromIndex?: number): boolean; + indexOf(searchElement: number, fromIndex?: number): number; + join(separator?: string): string; + lastIndexOf(searchElement: number, fromIndex?: number): number; + map(callbackfn: (value: number, index: number, array: Float16Array) => number, thisArg?: any): Float16Array; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + ): number; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + initialValue: number, + ): number; + reduce( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float16Array) => U, + initialValue: U, + ): U; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + ): number; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + initialValue: number, + ): number; + reduceRight( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float16Array) => U, + initialValue: U, + ): U; + reverse(): Float16Array; + set(array: ArrayLike, offset?: number): void; + slice(start?: number, end?: number): Float16Array; + some(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): boolean; + sort(compareFn?: (a: number, b: number) => number): this; + subarray(begin?: number, end?: number): Float16Array; + toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; + toReversed(): Float16Array; + toSorted(compareFn?: (a: number, b: number) => number): Float16Array; + toString(): string; + valueOf(): Float16Array; + with(index: number, value: number): Float16Array; + [index: number]: number; +} diff --git a/node_modules/@types/node/ts5.6/globals.typedarray.d.ts b/node_modules/@types/node/ts5.6/globals.typedarray.d.ts new file mode 100644 index 0000000..57a1ab4 --- /dev/null +++ b/node_modules/@types/node/ts5.6/globals.typedarray.d.ts @@ -0,0 +1,36 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float16Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + type NonSharedUint8Array = Uint8Array; + type NonSharedUint8ClampedArray = Uint8ClampedArray; + type NonSharedUint16Array = Uint16Array; + type NonSharedUint32Array = Uint32Array; + type NonSharedInt8Array = Int8Array; + type NonSharedInt16Array = Int16Array; + type NonSharedInt32Array = Int32Array; + type NonSharedBigUint64Array = BigUint64Array; + type NonSharedBigInt64Array = BigInt64Array; + type NonSharedFloat16Array = Float16Array; + type NonSharedFloat32Array = Float32Array; + type NonSharedFloat64Array = Float64Array; + type NonSharedDataView = DataView; + type NonSharedTypedArray = TypedArray; + type NonSharedArrayBufferView = ArrayBufferView; + } +} diff --git a/node_modules/@types/node/ts5.6/index.d.ts b/node_modules/@types/node/ts5.6/index.d.ts new file mode 100644 index 0000000..a157660 --- /dev/null +++ b/node_modules/@types/node/ts5.6/index.d.ts @@ -0,0 +1,117 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.2 through 5.6. + +// Reference required TypeScript libraries: +/// +/// + +// TypeScript library polyfills required for TypeScript <=5.6: +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript <=5.6: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts b/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts new file mode 100644 index 0000000..110b1eb --- /dev/null +++ b/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts @@ -0,0 +1,72 @@ +// Interface declaration for Float16Array, required in @types/node v24+. +// These definitions are specific to TS 5.7. + +// This needs all of the "common" properties/methods of the TypedArrays, +// otherwise the type unions `TypedArray` and `ArrayBufferView` will be +// empty objects. +interface Float16Array { + readonly BYTES_PER_ELEMENT: number; + readonly buffer: TArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; + readonly length: number; + readonly [Symbol.toStringTag]: "Float16Array"; + at(index: number): number | undefined; + copyWithin(target: number, start: number, end?: number): this; + entries(): ArrayIterator<[number, number]>; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; + fill(value: number, start?: number, end?: number): this; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Float16Array; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; + findLast( + predicate: (value: number, index: number, array: this) => value is S, + thisArg?: any, + ): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; + includes(searchElement: number, fromIndex?: number): boolean; + indexOf(searchElement: number, fromIndex?: number): number; + join(separator?: string): string; + keys(): ArrayIterator; + lastIndexOf(searchElement: number, fromIndex?: number): number; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Float16Array; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + ): number; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + initialValue: number, + ): number; + reduce( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, + initialValue: U, + ): U; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + ): number; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + initialValue: number, + ): number; + reduceRight( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, + initialValue: U, + ): U; + reverse(): this; + set(array: ArrayLike, offset?: number): void; + slice(start?: number, end?: number): Float16Array; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; + sort(compareFn?: (a: number, b: number) => number): this; + subarray(begin?: number, end?: number): Float16Array; + toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; + toReversed(): Float16Array; + toSorted(compareFn?: (a: number, b: number) => number): Float16Array; + toString(): string; + valueOf(): this; + values(): ArrayIterator; + with(index: number, value: number): Float16Array; + [Symbol.iterator](): ArrayIterator; + [index: number]: number; +} diff --git a/node_modules/@types/node/ts5.7/index.d.ts b/node_modules/@types/node/ts5.7/index.d.ts new file mode 100644 index 0000000..32c541b --- /dev/null +++ b/node_modules/@types/node/ts5.7/index.d.ts @@ -0,0 +1,117 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.7. + +// Reference required TypeScript libraries: +/// +/// + +// TypeScript library polyfills required for TypeScript 5.7: +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/@types/node/tty.d.ts b/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000..39b4a7f --- /dev/null +++ b/node_modules/@types/node/tty.d.ts @@ -0,0 +1,225 @@ +declare module "node:tty" { + import * as net from "node:net"; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to `setRawMode`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + interface WriteStreamEventMap extends net.SocketEventMap { + "resize": []; + } + /** + * Represents the writable side of a TTY. In normal circumstances, `process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type `[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: WriteStreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: WriteStreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: WriteStreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: WriteStreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } +} +declare module "tty" { + export * from "node:tty"; +} diff --git a/node_modules/@types/node/url.d.ts b/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000..8803a03 --- /dev/null +++ b/node_modules/@types/node/url.d.ts @@ -0,0 +1,532 @@ +declare module "node:url" { + import { Blob, NonSharedBuffer } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + interface FileUrlToPathOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + interface PathToFileUrlOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) + * and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the + * [WHATWG URL](https://nodejs.org/docs/latest-v25.x/api/url.html#the-whatwg-url-api) API instead, for example: + * + * ```js + * function getURL(req) { + * const proto = req.headers['x-forwarded-proto'] || 'https'; + * const host = req.headers['x-forwarded-host'] || req.headers.host || 'example.com'; + * return new URL(req.url || '/', `${proto}://${host}`); + * } + * ``` + * + * The example above assumes well-formed headers are forwarded from a reverse + * proxy to your Node.js server. If you are not using a reverse proxy, you should + * use the example below: + * + * ```js + * function getURL(req) { + * return new URL(req.url || '/', 'https://example.com'); + * } + * ``` + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param parseQueryString If `true`, the `query` property will always + * be set to an object returned by the [`querystring`](https://nodejs.org/docs/latest-v25.x/api/querystring.html) module's `parse()` + * method. If `false`, the `query` property on the returned URL object will be an + * unparsed, undecoded string. **Default:** `false`. + * @param slashesDenoteHost If `true`, the first token after the literal + * string `//` and preceding the next `/` will be interpreted as the `host`. + * For instance, given `//foo/bar`, the result would be + * `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + * **Default:** `false`. + */ + function parse( + urlString: string, + parseQueryString?: false, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * import url from 'node:url'; + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'node:url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * + * **Security Considerations:** + * + * This function decodes percent-encoded characters, including encoded dot-segments + * (`%2e` as `.` and `%2e%2e` as `..`), and then normalizes the resulting path. + * This means that encoded directory traversal sequences (such as `%2e%2e`) are + * decoded and processed as actual path traversal, even though encoded slashes + * (`%2F`, `%5C`) are correctly rejected. + * + * **Applications must not rely on `fileURLToPath()` alone to prevent directory + * traversal attacks.** Always perform explicit path validation and security checks + * on the returned path value to ensure it remains within expected boundaries + * before using it for file system operations. + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; + /** + * Like `url.fileURLToPath(...)` except that instead of returning a string + * representation of the path, a `Buffer` is returned. This conversion is + * helpful when the input URL contains percent-encoded segments that are + * not valid UTF-8 / Unicode sequences. + * + * **Security Considerations:** + * + * This function has the same security considerations as `url.fileURLToPath()`. + * It decodes percent-encoded characters, including encoded dot-segments + * (`%2e` as `.` and `%2e%2e` as `..`), and normalizes the path. **Applications + * must not rely on this function alone to prevent directory traversal attacks.** + * Always perform explicit path validation on the returned buffer value before + * using it for file system operations. + * @since v24.3.0 + * @param url The file URL string or URL object to convert to a path. + * @returns The fully-resolved platform-specific Node.js file path + * as a `Buffer`. + */ + function fileURLToPathBuffer(url: string | URL, options?: FileUrlToPathOptions): NonSharedBuffer; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'node:url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string, options?: PathToFileUrlOptions): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'node:url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + /** + * `true` if the serialized URL string should include the username and password, `false` otherwise. + * @default true + */ + auth?: boolean | undefined; + /** + * `true` if the serialized URL string should include the fragment, `false` otherwise. + * @default true + */ + fragment?: boolean | undefined; + /** + * `true` if the serialized URL string should include the search query, `false` otherwise. + * @default true + */ + search?: boolean | undefined; + /** + * `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to + * being Punycode encoded. + * @default false + */ + unicode?: boolean | undefined; + } + // #region web types + type URLPatternInput = string | URLPatternInit; + interface URLPatternComponentResult { + input: string; + groups: Record; + } + interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; + } + interface URLPatternOptions { + ignoreCase?: boolean; + } + interface URLPatternResult { + inputs: URLPatternInput[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; + } + interface URL { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toJSON(): string; + } + var URL: { + prototype: URL; + new(url: string | URL, base?: string | URL): URL; + canParse(input: string | URL, base?: string | URL): boolean; + createObjectURL(blob: Blob): string; + parse(input: string | URL, base?: string | URL): URL | null; + revokeObjectURL(id: string): void; + }; + interface URLPattern { + readonly hasRegExpGroups: boolean; + readonly hash: string; + readonly hostname: string; + readonly password: string; + readonly pathname: string; + readonly port: string; + readonly protocol: string; + readonly search: string; + readonly username: string; + exec(input?: URLPatternInput, baseURL?: string | URL): URLPatternResult | null; + test(input?: URLPatternInput, baseURL?: string | URL): boolean; + } + var URLPattern: { + prototype: URLPattern; + new(input: URLPatternInput, baseURL: string | URL, options?: URLPatternOptions): URLPattern; + new(input?: URLPatternInput, options?: URLPatternOptions): URLPattern; + }; + interface URLSearchParams { + readonly size: number; + append(name: string, value: string): void; + delete(name: string, value?: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string, value?: string): boolean; + set(name: string, value: string): void; + sort(): void; + forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void; + [Symbol.iterator](): URLSearchParamsIterator<[string, string]>; + entries(): URLSearchParamsIterator<[string, string]>; + keys(): URLSearchParamsIterator; + values(): URLSearchParamsIterator; + } + var URLSearchParams: { + prototype: URLSearchParams; + new(init?: string[][] | Record | string | URLSearchParams): URLSearchParams; + }; + interface URLSearchParamsIterator extends NodeJS.Iterator { + [Symbol.iterator](): URLSearchParamsIterator; + } + // #endregion +} +declare module "url" { + export * from "node:url"; +} diff --git a/node_modules/@types/node/util.d.ts b/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000..90f12aa --- /dev/null +++ b/node_modules/@types/node/util.d.ts @@ -0,0 +1,1677 @@ +declare module "node:util" { + export * as types from "node:util/types"; + export type InspectStyle = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "name" + | "regexp" + | "module"; + export interface InspectStyles extends Record string)> { + regexp: { + (value: string): string; + colors: InspectColor[]; + }; + } + export type InspectColorModifier = + | "reset" + | "bold" + | "dim" + | "italic" + | "underline" + | "blink" + | "inverse" + | "hidden" + | "strikethrough" + | "doubleunderline"; + export type InspectColorForeground = + | "black" + | "red" + | "green" + | "yellow" + | "blue" + | "magenta" + | "cyan" + | "white" + | "gray" + | "redBright" + | "greenBright" + | "yellowBright" + | "blueBright" + | "magentaBright" + | "cyanBright" + | "whiteBright"; + export type InspectColorBackground = `bg${Capitalize}`; + export type InspectColor = InspectColorModifier | InspectColorForeground | InspectColorBackground; + export interface InspectColors extends Record {} + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default true + */ + compact?: boolean | number | undefined; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default false + */ + getters?: "get" | "set" | boolean | undefined; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export interface InspectContext extends Required { + stylize(text: string, styleType: InspectStyle): string; + } + import _inspect = inspect; + export interface Inspectable { + [inspect.custom](depth: number, options: InspectContext, inspect: typeof _inspect): any; + } + // TODO: Remove these in a future major + /** @deprecated Use `InspectStyle` instead. */ + export type Style = Exclude; + /** @deprecated Use the `Inspectable` interface instead. */ + export type CustomInspectFunction = (depth: number, options: InspectContext) => any; + /** @deprecated Use `InspectContext` instead. */ + export interface InspectOptionsStylized extends InspectContext {} + /** @deprecated Use `InspectColorModifier` instead. */ + export type Modifiers = InspectColorModifier; + /** @deprecated Use `InspectColorForeground` instead. */ + export type ForegroundColors = InspectColorForeground; + /** @deprecated Use `InspectColorBackground` instead. */ + export type BackgroundColors = InspectColorBackground; + export interface CallSiteObject { + /** + * Returns the name of the function associated with this call site. + */ + functionName: string; + /** + * Returns the name of the resource that contains the script for the + * function for this call site. + */ + scriptName: string; + /** + * Returns the unique id of the script, as in Chrome DevTools protocol + * [`Runtime.ScriptId`](https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-ScriptId). + * @since v22.14.0 + */ + scriptId: string; + /** + * Returns the number, 1-based, of the line for the associate function call. + */ + lineNumber: number; + /** + * Returns the 1-based column offset on the line for the associated function call. + */ + columnNumber: number; + } + export type DiffEntry = [operation: -1 | 0 | 1, value: string]; + /** + * `util.diff()` compares two string or array values and returns an array of difference entries. + * It uses the Myers diff algorithm to compute minimal differences, which is the same algorithm + * used internally by assertion error messages. + * + * If the values are equal, an empty array is returned. + * + * ```js + * const { diff } = require('node:util'); + * + * // Comparing strings + * const actualString = '12345678'; + * const expectedString = '12!!5!7!'; + * console.log(diff(actualString, expectedString)); + * // [ + * // [0, '1'], + * // [0, '2'], + * // [1, '3'], + * // [1, '4'], + * // [-1, '!'], + * // [-1, '!'], + * // [0, '5'], + * // [1, '6'], + * // [-1, '!'], + * // [0, '7'], + * // [1, '8'], + * // [-1, '!'], + * // ] + * // Comparing arrays + * const actualArray = ['1', '2', '3']; + * const expectedArray = ['1', '3', '4']; + * console.log(diff(actualArray, expectedArray)); + * // [ + * // [0, '1'], + * // [1, '2'], + * // [0, '3'], + * // [-1, '4'], + * // ] + * // Equal values return empty array + * console.log(diff('same', 'same')); + * // [] + * ``` + * @since v22.15.0 + * @experimental + * @param actual The first value to compare + * @param expected The second value to compare + * @returns An array of difference entries. Each entry is an array with two elements: + * * Index 0: `number` Operation code: `-1` for delete, `0` for no-op/unchanged, `1` for insert + * * Index 1: `string` The value associated with the operation + */ + export function diff(actual: string | readonly string[], expected: string | readonly string[]): DiffEntry[]; + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using `util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()` returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + export interface GetCallSitesOptions { + /** + * Reconstruct the original location in the stacktrace from the source-map. + * Enabled by default with the flag `--enable-source-maps`. + */ + sourceMap?: boolean | undefined; + } + /** + * Returns an array of call site objects containing the stack of + * the caller function. + * + * Unlike accessing an `error.stack`, the result returned from this API is not + * interfered with `Error.prepareStackTrace`. + * + * ```js + * import { getCallSites } from 'node:util'; + * + * function exampleFunction() { + * const callSites = getCallSites(); + * + * console.log('Call Sites:'); + * callSites.forEach((callSite, index) => { + * console.log(`CallSite ${index + 1}:`); + * console.log(`Function Name: ${callSite.functionName}`); + * console.log(`Script Name: ${callSite.scriptName}`); + * console.log(`Line Number: ${callSite.lineNumber}`); + * console.log(`Column Number: ${callSite.columnNumber}`); + * }); + * // CallSite 1: + * // Function Name: exampleFunction + * // Script Name: /home/example.js + * // Line Number: 5 + * // Column Number: 26 + * + * // CallSite 2: + * // Function Name: anotherFunction + * // Script Name: /home/example.js + * // Line Number: 22 + * // Column Number: 3 + * + * // ... + * } + * + * // A function to simulate another stack layer + * function anotherFunction() { + * exampleFunction(); + * } + * + * anotherFunction(); + * ``` + * + * It is possible to reconstruct the original locations by setting the option `sourceMap` to `true`. + * If the source map is not available, the original location will be the same as the current location. + * When the `--enable-source-maps` flag is enabled, for example when using `--experimental-transform-types`, + * `sourceMap` will be true by default. + * + * ```ts + * import { getCallSites } from 'node:util'; + * + * interface Foo { + * foo: string; + * } + * + * const callSites = getCallSites({ sourceMap: true }); + * + * // With sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 7 + * // Column Number: 26 + * + * // Without sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 2 + * // Column Number: 26 + * ``` + * @param frameCount Number of frames to capture as call site objects. + * **Default:** `10`. Allowable range is between 1 and 200. + * @return An array of call site objects + * @since v22.9.0 + */ + export function getCallSites(frameCount?: number, options?: GetCallSitesOptions): CallSiteObject[]; + export function getCallSites(options: GetCallSitesOptions): CallSiteObject[]; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Enable or disable printing a stack trace on `SIGINT`. The API is only available on the main thread. + * @since 24.6.0 + */ + export function setTraceSigInt(enable: boolean): void; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * Returns the string message for a numeric error code that comes from a Node.js + * API. + * The mapping between error codes and string messages is platform-dependent. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const message = util.getSystemErrorMessage(err.errno); + * console.error(message); // no such file or directory + * }); + * ``` + * @since v22.12.0 + */ + export function getSystemErrorMessage(err: number): string; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and returns a promise that resolves when the `signal` is aborted. + * If `resource` is provided, it weakly references the operation's associated object, + * so if `resource` is garbage collected before the `signal` aborts, + * then returned promise shall remain pending. + * This prevents memory leaks in long-running or non-cancelable operations. + * + * ```js + * import { aborted } from 'node:util'; + * + * // Obtain an object with an abortable signal, like a custom resource or operation. + * const dependent = obtainSomethingAbortable(); + * + * // Pass `dependent` as the resource, indicating the promise should only resolve + * // if `dependent` is still in memory when the signal is aborted. + * aborted(dependent.signal, dependent).then(() => { + * // This code runs when `dependent` is aborted. + * console.log('Dependent resource was aborted.'); + * }); + * + * // Simulate an event that triggers the abort. + * dependent.on('event', () => { + * dependent.abort(); // This will cause the `aborted` promise to resolve. + * }); + * ``` + * @since v19.7.0 + * @param resource Any non-null object tied to the abortable operation and held weakly. + * If `resource` is garbage collected before the `signal` aborts, the promise remains pending, + * allowing Node.js to stop tracking it. + * This helps prevent memory leaks in long-running or non-cancelable operations. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result. + * `util.inspect()` will use the constructor's name and/or `Symbol.toStringTag` + * property to make an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * import util from 'node:util'; + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * import { inspect } from 'node:util'; + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]), + * }; + * console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows `WeakMap` and `WeakSet` entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same + * `WeakSet` entries twice may result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * import { inspect } from 'node:util'; + * import assert from 'node:assert'; + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]), + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1], + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }), + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * import { inspect } from 'node:util'; + * + * const thousand = 1000; + * const million = 1000000; + * const bigNumber = 123456789n; + * const bigDecimal = 1234.12345; + * + * console.log(inspect(thousand, { numericSeparator: true })); + * // 1_000 + * console.log(inspect(million, { numericSeparator: true })); + * // 1_000_000 + * console.log(inspect(bigNumber, { numericSeparator: true })); + * // 123_456_789n + * console.log(inspect(bigDecimal, { numericSeparator: true })); + * // 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MiB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + const custom: unique symbol; + let colors: InspectColors; + let styles: InspectStyles; + let defaultOptions: InspectOptions; + let replDefaults: InspectOptions; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and + * `extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one + * [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from + * `superConstructor`. + * + * This mainly adds some input validation on top of + * `Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('node:util'); + * const EventEmitter = require('node:events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * import EventEmitter from 'node:events'; + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @legacy Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + /** + * The `util.convertProcessSignalToExitCode()` method converts a signal name to its + * corresponding POSIX exit code. Following the POSIX standard, the exit code + * for a process terminated by a signal is calculated as `128 + signal number`. + * + * If `signal` is not a valid signal name, then an error will be thrown. See + * [`signal(7)`](https://man7.org/linux/man-pages/man7/signal.7.html) for a list of valid signals. + * + * ```js + * import { convertProcessSignalToExitCode } from 'node:util'; + * + * console.log(convertProcessSignalToExitCode('SIGTERM')); // 143 (128 + 15) + * console.log(convertProcessSignalToExitCode('SIGKILL')); // 137 (128 + 9) + * ``` + * + * This is particularly useful when working with processes to determine + * the exit code based on the signal that terminated the process. + * @since v25.4.0 + * @param signal A signal name (e.g. `'SIGTERM'`) + * @returns The exit code corresponding to `signal` + */ + export function convertProcessSignalToExitCode(signal: NodeJS.Signals): number; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + /** + * The `util.debuglog().enabled` getter is used to create a test that can be used + * in conditionals based on the existence of the `NODE_DEBUG` environment variable. + * If the `section` name appears within the value of that environment variable, + * then the returned value will be `true`. If not, then the returned value will be + * `false`. + * + * ```js + * import { debuglog } from 'node:util'; + * const enabled = debuglog('foo').enabled; + * if (enabled) { + * console.log('hello from foo [%d]', 123); + * } + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then it will + * output something like: + * + * ```console + * hello from foo [123] + * ``` + */ + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` + * environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to + * `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); + * + * log('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo-bar'); + * + * log('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG` + * environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * import { debuglog } from 'node:util'; + * let log = debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * log = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export { debuglog as debug }; + export interface DeprecateOptions { + /** + * When false do not change the prototype of object + * while emitting the deprecation warning. + * @since v25.2.0 + * @default true + */ + modifyPrototype?: boolean | undefined; + } + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * import { deprecate } from 'node:util'; + * + * export const obsoleteFunction = deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a + * `DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * import { deprecate } from 'node:util'; + * + * const fn1 = deprecate( + * () => 'a value', + * 'deprecation message', + * 'DEP0001', + * ); + * const fn2 = deprecate( + * () => 'a different value', + * 'other dep message', + * 'DEP0001', + * ); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true` _prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the + * `process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation` + * property take precedence over `--trace-deprecation` and + * `process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string, options?: DeprecateOptions): T; + export interface IsDeepStrictEqualOptions { + /** + * If `true`, prototype and constructor + * comparison is skipped during deep strict equality check. + * @since v24.9.0 + * @default false + */ + skipPrototype?: boolean | undefined; + } + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown, options?: IsDeepStrictEqualOptions): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise` + * resolved), and the second argument will be the resolved value. + * + * ```js + * import { callbackify } from 'node:util'; + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` + * event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named + * `reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param fn An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: () => Promise, + ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * promisifiedStat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * + * async function callStat() { + * const stats = await promisifiedStat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * + * callStat(); + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify` + * will return its value, see [Custom promisified functions](https://nodejs.org/docs/latest-v25.x/api/util.html#custom-promisified-functions). + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()` + * will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * import { promisify } from 'node:util'; + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = promisify(foo.bar); + * // TypeError: Cannot read properties of undefined (reading 'a') + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * Stability: 1.1 - Active development + * Given an example `.env` file: + * + * ```js + * import { parseEnv } from 'node:util'; + * + * parseEnv('HELLO=world\nHELLO=oh my\n'); + * // Returns: { HELLO: 'oh my' } + * ``` + * @param content The raw contents of a `.env` file. + * @since v20.12.0 + */ + export function parseEnv(content: string): NodeJS.Dict; + export interface StyleTextOptions { + /** + * When true, `stream` is checked to see if it can handle colors. + * @default true + */ + validateStream?: boolean | undefined; + /** + * A stream that will be validated if it can be colored. + * @default process.stdout + */ + stream?: NodeJS.WritableStream | undefined; + } + /** + * This function returns a formatted text considering the `format` passed + * for printing in a terminal. It is aware of the terminal's capabilities + * and acts according to the configuration set via `NO_COLOR`, + * `NODE_DISABLE_COLORS` and `FORCE_COLOR` environment variables. + * + * ```js + * import { styleText } from 'node:util'; + * import { stderr } from 'node:process'; + * + * const successMessage = styleText('green', 'Success!'); + * console.log(successMessage); + * + * const errorMessage = styleText( + * 'red', + * 'Error! Error!', + * // Validate if process.stderr has TTY + * { stream: stderr }, + * ); + * console.error(errorMessage); + * ``` + * + * `util.inspect.colors` also provides text formats such as `italic`, and + * `underline` and you can combine both: + * + * ```js + * console.log( + * util.styleText(['underline', 'italic'], 'My italic underlined message'), + * ); + * ``` + * + * When passing an array of formats, the order of the format applied + * is left to right so the following style might overwrite the previous one. + * + * ```js + * console.log( + * util.styleText(['red', 'green'], 'text'), // green + * ); + * ``` + * + * The special format value `none` applies no additional styling to the text. + * + * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v25.x/api/util.html#modifiers). + * @param format A text format or an Array of text formats defined in `util.inspect.colors`. + * @param text The text to to be formatted. + * @since v20.12.0 + */ + export function styleText( + format: InspectColor | readonly InspectColor[], + text: string, + options?: StyleTextOptions, + ): string; + /** @deprecated This alias will be removed in a future version. Use the canonical `TextEncoderEncodeIntoResult` instead. */ + // TODO: remove in future major + export interface EncodeIntoResult extends TextEncoderEncodeIntoResult {} + //// parseArgs + /** + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: + */ + export function parseArgs(config?: T): ParsedResults; + /** + * Type of argument used in {@link parseArgs}. + */ + export type ParseArgsOptionsType = "boolean" | "string"; + export interface ParseArgsOptionDescriptor { + /** + * Type of argument. + */ + type: ParseArgsOptionsType; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The value to assign to + * the option if it does not appear in the arguments to be parsed. The value + * must match the type specified by the `type` property. If `multiple` is + * `true`, it must be an array. No default value is applied when the option + * does appear in the arguments to be parsed, even if the provided value + * is falsy. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + export interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionDescriptor; + } + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: readonly string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`. + * @default false + * @since v22.4.0 + */ + allowNegative?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true ? IfTrue + : T extends false ? IfFalse + : IfTrue; + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false ? IfFalse + : T extends true ? IfTrue + : IfFalse; + type ExtractOptionValue = IfDefaultsTrue< + T["strict"], + O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, + string | boolean + >; + type ApplyOptionalModifiers> = ( + & { -readonly [LongOption in keyof O]?: V[LongOption] } + & { [LongOption in keyof O as O[LongOption]["default"] extends {} ? LongOption : never]: V[LongOption] } + ) extends infer P ? { [K in keyof P]: P[K] } : never; // resolve intersection to object + type ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? ApplyOptionalModifiers< + T["options"], + { + [LongOption in keyof T["options"]]: IfDefaultsFalse< + T["options"][LongOption]["multiple"], + Array>, + ExtractOptionValue + >; + } + > + : {}); + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionDescriptor, + > = O["type"] extends "string" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O["type"] extends "boolean" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T["options"] = keyof T["options"], + > = K extends unknown + ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions + : OptionToken + : never; + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + type ParsedPositionalToken = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } + >; + type PreciseParsedResults = IfDefaultsFalse< + T["tokens"], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + type OptionToken = + | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: "option"; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + type Token = + | OptionToken + | { kind: "positional"; index: number; value: string } + | { kind: "option-terminator"; index: number }; + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T ? { + values: { + [longOption: string]: undefined | string | boolean | Array; + }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + /** + * Gets and sets the type portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript'); + * console.log(myMIME.type); + * // Prints: text + * myMIME.type = 'application'; + * console.log(myMIME.type); + * // Prints: application + * console.log(String(myMIME)); + * // Prints: application/javascript + * ``` + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/ecmascript'); + * console.log(myMIME.subtype); + * // Prints: ecmascript + * myMIME.subtype = 'javascript'; + * console.log(myMIME.subtype); + * // Prints: javascript + * console.log(String(myMIME)); + * // Prints: text/javascript + * ``` + */ + subtype: string; + /** + * Gets the essence of the MIME. This property is read only. + * Use `mime.type` or `mime.subtype` to alter the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript;key=value'); + * console.log(myMIME.essence); + * // Prints: text/javascript + * myMIME.type = 'application'; + * console.log(myMIME.essence); + * // Prints: application/javascript + * console.log(String(myMIME)); + * // Prints: application/javascript;key=value + * ``` + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the + * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. + */ + readonly params: MIMEParams; + /** + * The `toString()` method on the `MIMEType` object returns the serialized MIME. + * + * Because of the need for standard compliance, this method does not allow users + * to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * The `MIMEParams` API provides read and write access to the parameters of a `MIMEType`. + * @since v19.1.0, v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + * Each item of the iterator is a JavaScript `Array`. The first item of the array + * is the `name`, the second item of the array is the `value`. + */ + entries(): NodeJS.Iterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // bar + * ``` + */ + keys(): NodeJS.Iterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * params.set('foo', 'def'); + * params.set('baz', 'xyz'); + * console.log(params.toString()); + * // Prints: foo=def;bar=1;baz=xyz + * ``` + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): NodeJS.Iterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator](): NodeJS.Iterator<[name: string, value: string]>; + } + // #region web types + export interface TextDecodeOptions { + stream?: boolean; + } + export interface TextDecoderCommon { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + } + export interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + export interface TextEncoderCommon { + readonly encoding: string; + } + export interface TextEncoderEncodeIntoResult { + read: number; + written: number; + } + export interface TextDecoder extends TextDecoderCommon { + decode(input?: NodeJS.AllowSharedBufferSource, options?: TextDecodeOptions): string; + } + export var TextDecoder: { + prototype: TextDecoder; + new(label?: string, options?: TextDecoderOptions): TextDecoder; + }; + export interface TextEncoder extends TextEncoderCommon { + encode(input?: string): NodeJS.NonSharedUint8Array; + encodeInto(source: string, destination: Uint8Array): TextEncoderEncodeIntoResult; + } + export var TextEncoder: { + prototype: TextEncoder; + new(): TextEncoder; + }; + // #endregion +} +declare module "util" { + export * from "node:util"; +} diff --git a/node_modules/@types/node/util/types.d.ts b/node_modules/@types/node/util/types.d.ts new file mode 100644 index 0000000..818825b --- /dev/null +++ b/node_modules/@types/node/util/types.d.ts @@ -0,0 +1,558 @@ +declare module "node:util/types" { + import { KeyObject, webcrypto } from "node:crypto"; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a BigInt object, e.g. created + * by `Object(BigInt(123))`. + * + * ```js + * util.types.isBigIntObject(Object(BigInt(123))); // Returns true + * util.types.isBigIntObject(BigInt(123)); // Returns false + * util.types.isBigIntObject(123); // Returns false + * ``` + * @since v10.4.0 + */ + function isBigIntObject(object: unknown): object is BigInt; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are + * [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a + * `null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * import native from 'napi_addon.node'; + * import { types } from 'node:util'; + * + * const data = native.myNapi(); + * types.isExternal(data); // returns true + * types.isExternal(0); // returns false + * types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to + * [`napi_create_external()`](https://nodejs.org/docs/latest-v25.x/api/n-api.html#napi_create_external). + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float16Array) instance. + * + * ```js + * util.types.isFloat16Array(new ArrayBuffer()); // Returns false + * util.types.isFloat16Array(new Float16Array()); // Returns true + * util.types.isFloat16Array(new Float32Array()); // Returns false + * ``` + * @since v24.0.0 + */ + function isFloat16Array(object: unknown): object is Float16Array; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) + : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value was returned by the constructor of a + * [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * + * ```js + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()` + * returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` + * for these errors: + * + * ```js + * import { createContext, runInContext } from 'node:vm'; + * import { types } from 'node:util'; + * + * const context = createContext({}); + * const myError = runInContext('new Error()', context); + * console.log(types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true + * ``` + * @since v10.0.0 + * @deprecated The `util.types.isNativeError` API is deprecated. Please use `Error.isError` instead. + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet( + object: T | {}, + ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module "util/types" { + export * from "node:util/types"; +} diff --git a/node_modules/@types/node/v8.d.ts b/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000..c121c61 --- /dev/null +++ b/node_modules/@types/node/v8.d.ts @@ -0,0 +1,980 @@ +declare module "node:v8" { + import { NonSharedBuffer } from "node:buffer"; + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + total_allocated_bytes: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + interface HeapSnapshotOptions { + /** + * If true, expose internals in the heap snapshot. + * @default false + */ + exposeInternals?: boolean | undefined; + /** + * If true, expose numeric values in artificial fields. + * @default false + */ + exposeNumericValues?: boolean | undefined; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * `total_allocated_bytes` The value of total allocated bytes since the Isolate + * creation. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824, + * total_allocated_bytes: 45224088 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * It returns an object with a structure similar to the + * [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html) + * object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html) + * for more information about the properties of the object. + * + * ```js + * // Detailed + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * space_statistics: [ + * { + * name: 'NormalPageSpace0', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace1', + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace2', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace3', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'LargePageSpace', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * ], + * type_names: [], + * detail_level: 'detailed', + * }); + * ``` + * + * ```js + * // Brief + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 128864, + * space_statistics: [], + * type_names: [], + * detail_level: 'brief', + * }); + * ``` + * @since v22.15.0 + * @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics. + * Accepted values are: + * * `'brief'`: Brief statistics contain only the top-level + * allocated and used + * memory statistics for the entire heap. + * * `'detailed'`: Detailed statistics also contain a break + * down per space and page, as well as freelist statistics + * and object type histograms. + */ + function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running `node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * import v8 from 'node:v8'; + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function) + * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain + * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should + * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the + * application. + * + * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects + * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided + * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the + * target objects during the search. + * + * Only objects created in the current execution context are included in the results. + * + * ```js + * import { queryObjects } from 'node:v8'; + * class A { foo = 'bar'; } + * console.log(queryObjects(A)); // 0 + * const a = new A(); + * console.log(queryObjects(A)); // 1 + * // [ "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * + * class B extends A { bar = 'qux'; } + * const b = new B(); + * console.log(queryObjects(B)); // 1 + * // [ "B { foo: 'bar', bar: 'qux' }" ] + * console.log(queryObjects(B, { format: 'summary' })); + * + * // Note that, when there are child classes inheriting from a constructor, + * // the constructor also shows up in the prototype chain of the child + * // classes's prototoype, so the child classes's prototoype would also be + * // included in the result. + * console.log(queryObjects(A)); // 3 + * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * ``` + * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap. + * @since v20.13.0 + */ + function queryObjects(ctor: Function): number | string[]; + function queryObjects(ctor: Function, options: { format: "count" }): number; + function queryObjects(ctor: Function, options: { format: "summary" }): string[]; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * import v8 from 'node:v8'; + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable containing the V8 heap snapshot. + */ + function getHeapSnapshot(options?: HeapSnapshotOptions): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * import { writeHeapSnapshot } from 'node:v8'; + * import { + * Worker, + * isMainThread, + * parentPort, + * } from 'node:worker_threads'; + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v25.0.0 + */ + interface SyncCPUProfileHandle { + /** + * Stopping collecting the profile and return the profile data. + * @since v25.0.0 + */ + stop(): string; + /** + * Stopping collecting the profile and the profile will be discarded. + * @since v25.0.0 + */ + [Symbol.dispose](): void; + } + /** + * @since v24.8.0 + */ + interface CPUProfileHandle { + /** + * Stopping collecting the profile, then return a Promise that fulfills with an error or the + * profile data. + * @since v24.8.0 + */ + stop(): Promise; + /** + * Stopping collecting the profile and the profile will be discarded. + * @since v24.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + /** + * @since v24.9.0 + */ + interface HeapProfileHandle { + /** + * Stopping collecting the profile, then return a Promise that fulfills with an error or the + * profile data. + * @since v24.9.0 + */ + stop(): Promise; + /** + * Stopping collecting the profile and the profile will be discarded. + * @since v24.9.0 + */ + [Symbol.asyncDispose](): Promise; + } + /** + * Starting a CPU profile then return a `SyncCPUProfileHandle` object. + * This API supports `using` syntax. + * + * ```js + * const handle = v8.startCpuProfile(); + * const profile = handle.stop(); + * console.log(profile); + * ``` + * @since v25.0.0 + */ + function startCpuProfile(): SyncCPUProfileHandle; + /** + * V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string. + * If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true; + * otherwise, it returns false. + * + * If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`. + * Sometimes a `Latin-1` string may also be represented as `UTF16`. + * + * ```js + * const { isStringOneByteRepresentation } = require('node:v8'); + * + * const Encoding = { + * latin1: 1, + * utf16le: 2, + * }; + * const buffer = Buffer.alloc(100); + * function writeString(input) { + * if (isStringOneByteRepresentation(input)) { + * buffer.writeUint8(Encoding.latin1); + * buffer.writeUint32LE(input.length, 1); + * buffer.write(input, 5, 'latin1'); + * } else { + * buffer.writeUint8(Encoding.utf16le); + * buffer.writeUint32LE(input.length * 2, 1); + * buffer.write(input, 5, 'utf16le'); + * } + * } + * writeString('hello'); + * writeString('你好'); + * ``` + * @since v23.10.0, v22.15.0 + */ + function isStringOneByteRepresentation(content: string): boolean; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): NonSharedBuffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.ArrayBufferView): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before `.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): NonSharedBuffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.ArrayBufferView): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once. + * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information. + * @since v18.10.0, v16.18.0 + */ + function setHeapSnapshotNearHeapLimit(limit: number): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object. The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * import { GCProfiler } from 'node:v8'; + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + /** + * Stop collecting GC data, and discard the profile. + * @since v25.5.0 + */ + [Symbol.dispose](): void; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; + type StartupSnapshotCallbackFn = (args: any) => any; + /** + * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. + * + * ```bash + * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js + * # This launches a process with the snapshot + * $ node --snapshot-blob snapshot.blob + * ``` + * + * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects + * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot. + * For example, if the `entry.js` contains the following script: + * + * ```js + * 'use strict'; + * + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * import path from 'node:path'; + * import assert from 'node:assert'; + * + * import v8 from 'node:v8'; + * + * class BookShelf { + * storage = new Map(); + * + * // Reading a series of files from directory and store them into storage. + * constructor(directory, books) { + * for (const book of books) { + * this.storage.set(book, fs.readFileSync(path.join(directory, book))); + * } + * } + * + * static compressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gzipSync(content)); + * } + * } + * + * static decompressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gunzipSync(content)); + * } + * } + * } + * + * // __dirname here is where the snapshot script is placed + * // during snapshot building time. + * const shelf = new BookShelf(__dirname, [ + * 'book1.en_US.txt', + * 'book1.es_ES.txt', + * 'book2.zh_CN.txt', + * ]); + * + * assert(v8.startupSnapshot.isBuildingSnapshot()); + * // On snapshot serialization, compress the books to reduce size. + * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf); + * // On snapshot deserialization, decompress the books. + * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf); + * v8.startupSnapshot.setDeserializeMainFunction((shelf) => { + * // process.env and process.argv are refreshed during snapshot + * // deserialization. + * const lang = process.env.BOOK_LANG || 'en_US'; + * const book = process.argv[1]; + * const name = `${book}.${lang}.txt`; + * console.log(shelf.storage.get(name)); + * }, shelf); + * ``` + * + * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process: + * + * ```bash + * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1 + * # Prints content of book1.es_ES.txt deserialized from the snapshot. + * ``` + * + * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot. + * + * @since v18.6.0, v16.17.0 + */ + namespace startupSnapshot { + /** + * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit. + * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. + * @since v18.6.0, v16.17.0 + */ + function addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Add a callback that will be called when the Node.js instance is deserialized from a snapshot. + * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or + * to re-acquire resources that the application needs when the application is restarted from the snapshot. + * @since v18.6.0, v16.17.0 + */ + function addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script. + * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized + * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. + * @since v18.6.0, v16.17.0 + */ + function setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Returns true if the Node.js instance is run to build a snapshot. + * @since v18.6.0, v16.17.0 + */ + function isBuildingSnapshot(): boolean; + } +} +declare module "v8" { + export * from "node:v8"; +} diff --git a/node_modules/@types/node/vm.d.ts b/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000..a349741 --- /dev/null +++ b/node_modules/@types/node/vm.d.ts @@ -0,0 +1,1170 @@ +declare module "node:vm" { + import { NonSharedBuffer } from "node:buffer"; + import { ImportAttributes, ImportPhase } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * @default '' + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + type DynamicModuleLoader = ( + specifier: string, + referrer: T, + importAttributes: ImportAttributes, + phase: ImportPhase, + ) => Module | Promise; + interface ScriptOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is + * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see + * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v25.x/api/vm.html#support-of-dynamic-import-in-compilation-apis). + * @experimental + */ + importModuleDynamically?: + | DynamicModuleLoader + +``` + +Open the above .html file in a browser and you should see + +Node Example + +**[Full online demo](http://kpdecker.github.com/jsdiff)** + +## Compatibility + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/jsdiff.svg)](https://saucelabs.com/u/jsdiff) + +jsdiff supports all ES3 environments with some known issues on IE8 and below. Under these browsers some diff algorithms such as word diff and others may fail due to lack of support for capturing groups in the `split` operation. + +## License + +See [LICENSE](https://github.com/kpdecker/jsdiff/blob/master/LICENSE). diff --git a/node_modules/diff/dist/diff.js b/node_modules/diff/dist/diff.js new file mode 100644 index 0000000..de800a3 --- /dev/null +++ b/node_modules/diff/dist/diff.js @@ -0,0 +1,1548 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.Diff = {})); +}(this, function (exports) { 'use strict'; + + function Diff() {} + Diff.prototype = { + diff: function diff(oldString, newString) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = void 0; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + + + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + castInput: function castInput(value) { + return value; + }, + tokenize: function tokenize(value) { + return value.split(''); + }, + join: function join(chars) { + return chars.join(''); + } + }; + + function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; + } + + function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; + } + + var characterDiff = new Diff(); + function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); + } + + function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + + return defaults; + } + + // + // Ranges and exceptions: + // Latin-1 Supplement, 0080–00FF + // - U+00D7 × Multiplication sign + // - U+00F7 ÷ Division sign + // Latin Extended-A, 0100–017F + // Latin Extended-B, 0180–024F + // IPA Extensions, 0250–02AF + // Spacing Modifier Letters, 02B0–02FF + // - U+02C7 ˇ ˇ Caron + // - U+02D8 ˘ ˘ Breve + // - U+02D9 ˙ ˙ Dot Above + // - U+02DA ˚ ˚ Ring Above + // - U+02DB ˛ ˛ Ogonek + // - U+02DC ˜ ˜ Small Tilde + // - U+02DD ˝ ˝ Double Acute Accent + // Latin Extended Additional, 1E00–1EFF + + var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; + var reWhitespace = /\S/; + var wordDiff = new Diff(); + + wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); + }; + + wordDiff.tokenize = function (value) { + var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; + }; + + function diffWords(oldStr, newStr, options) { + options = generateOptions(options, { + ignoreWhitespace: true + }); + return wordDiff.diff(oldStr, newStr, options); + } + function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff.diff(oldStr, newStr, options); + } + + var lineDiff = new Diff(); + + lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; + }; + + function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); + } + function diffTrimmedLines(oldStr, newStr, callback) { + var options = generateOptions(callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options); + } + + var sentenceDiff = new Diff(); + + sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); + }; + + function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); + } + + var cssDiff = new Diff(); + + cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); + }; + + function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); + } + + function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } + } + + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); + } + + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance"); + } + + var objectPrototypeToString = Object.prototype.toString; + var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a + // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + + jsonDiff.useLongestToken = true; + jsonDiff.tokenize = lineDiff.tokenize; + + jsonDiff.castInput = function (value) { + var _this$options = this.options, + undefinedReplacement = _this$options.undefinedReplacement, + _this$options$stringi = _this$options.stringifyReplacer, + stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { + return typeof v === 'undefined' ? undefinedReplacement : v; + } : _this$options$stringi; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); + }; + + jsonDiff.equals = function (left, right) { + return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); + }; + + function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); + } // This function handles the presence of circular references by bailing out when encountering an + // object that is already on the "stack" of items being processed. Accepts an optional replacer + + function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if (_typeof(obj) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + + var sortedKeys = [], + _key; + + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; + } + + var arrayDiff = new Diff(); + + arrayDiff.tokenize = function (value) { + return value.slice(); + }; + + arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; + }; + + function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); + } + + function parsePatch(uniDiff) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); // Parse diff metadata + + while (i < diffstr.length) { + var line = diffstr[i]; // File header found, end parsing diff metadata + + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } // Diff index + + + var headerMatch = /^(?:Index:|diff(?: -r \w+)+)\s+/.exec(line); + + if (headerMatch) { + index.index = line.substring(headerMatch[0].length).trim(); + } + + i++; + } // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + + + parseFileHeader(index); + parseFileHeader(index); // Parse hunks + + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + + + function parseFileHeader(index) { + var fileHeaderMatch = /^(---|\+\+\+)\s+/.exec(diffstr[i]); + + if (fileHeaderMatch) { + var keyPrefix = fileHeaderMatch[1] === '---' ? 'old' : 'new'; + var data = diffstr[i].substring(3).trim().split('\t', 2); + var fileName = data[0].replace(/\\\\/g, '\\'); + + if (fileName.startsWith('"') && fileName.endsWith('"')) { + fileName = fileName.substr(1, fileName.length - 2); + } + + index[keyPrefix + 'FileName'] = fileName; + index[keyPrefix + 'Header'] = (data[1] || '').trim(); + i++; + } + } // Parses a hunk + // This assumes that we are at the start of a hunk. + + + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [], + linedelimiters: [] + }; + var addCount = 0, + removeCount = 0; + + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } // Handle the empty block count case + + + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } // Perform optional sanity checking + + + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; + } + + // Iterator that traverses in the range of [min, max], stepping + // by distance from a given start position. I.e. for [0, 4], with + // start of 2, this will iterate 2, 3, 1, 4, 0. + function distanceIterator (start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + + + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + + + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } // We tried to fit hunk before text beginning and beyond text length, then + // hunk can't fit on the text. Return undefined + + }; + } + + function applyPatch(source, uniDiff) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } // Apply the diff to the input + + + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { + return line === patchContent; + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL, + addEOFNL; + /** + * Checks if the hunk exactly fits on the provided location + */ + + + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line; + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + + toPos++; + } + } + + return true; + } // Search best fit offsets for each hunk based on the previous ones + + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + var iterator = distanceIterator(toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + + + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } // Apply patch hunks + + + var diffOffset = 0; + + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; + + diffOffset += _hunk.newLines - _hunk.oldLines; + + if (_toPos < 0) { + // Creating a new file + _toPos = 0; + } + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line, + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } // Handle EOFNL insertion/removal + + + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + + return lines.join(''); + } // Wrapper that supports multiple file patches via callbacks. + + function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + var currentIndex = 0; + + function processIndex() { + var index = uniDiff[currentIndex++]; + + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + + processIndex(); + } + + function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = diffLines(oldStr, newStr, options); + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + var _loop = function _loop(i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + var _curRange; + + // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + + (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + var _curRange2; + + // Overlapping + (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); + } else { + var _curRange3; + + // end the range and output + var contextSize = Math.min(lines.length, options.context); + + (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + + if (!oldEOFNewline && noNlBeforeAdds) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } + + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + _loop(i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; + } + function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + var ret = []; + + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; + } + function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); + } + + function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + + return arrayStartsWith(a, b); + } + function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + + return true; + } + + function calcLineCount(hunk) { + var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), + oldLines = _calcOldNewLineCount.oldLines, + newLines = _calcOldNewLineCount.newLines; + + if (oldLines !== undefined) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + + if (newLines !== undefined) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } + } + function merge(mine, theirs, base) { + mine = loadPatch(mine, base); + theirs = loadPatch(theirs, base); + var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. + // Leaving sanity checks on this to the API consumer that may know more about the + // meaning in their own context. + + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + // No header or no change in ours, use theirs (and ours if theirs does not exist) + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + // No header or no change in theirs, use ours + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + // Both changed... figure it out + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + + ret.hunks = []; + var mineIndex = 0, + theirsIndex = 0, + mineOffset = 0, + theirsOffset = 0; + + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { + oldStart: Infinity + }, + theirsCurrent = theirs.hunks[theirsIndex] || { + oldStart: Infinity + }; + + if (hunkBefore(mineCurrent, theirsCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + // Overlap, merge as best we can + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + ret.hunks.push(mergedHunk); + } + } + + return ret; + } + + function loadPatch(param, base) { + if (typeof param === 'string') { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return parsePatch(param)[0]; + } + + if (!base) { + throw new Error('Must provide a base reference or pass in a patch'); + } + + return structuredPatch(undefined, undefined, base, param); + } + + return param; + } + + function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; + } + + function selectField(index, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index.conflict = true; + return { + mine: mine, + theirs: theirs + }; + } + } + + function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; + } + + function cloneHunk(hunk, offset) { + return { + oldStart: hunk.oldStart, + oldLines: hunk.oldLines, + newStart: hunk.newStart + offset, + newLines: hunk.newLines, + lines: hunk.lines + }; + } + + function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + // This will generally result in a conflicted hunk, but there are cases where the context + // is the only overlap where we can successfully merge the content here. + var mine = { + offset: mineOffset, + lines: mineLines, + index: 0 + }, + their = { + offset: theirOffset, + lines: theirLines, + index: 0 + }; // Handle any leading content + + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. + + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], + theirCurrent = their.lines[their.index]; + + if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { + // Both modified ... + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { + var _hunk$lines; + + // Mine inserted + (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); + } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { + var _hunk$lines2; + + // Theirs inserted + (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); + } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { + // Mine removed or edited + removal(hunk, mine, their); + } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { + // Their removed or edited + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + // Context identity + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + // Context mismatch + conflict(hunk, collectChange(mine), collectChange(their)); + } + } // Now push anything that may be remaining + + + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + calcLineCount(hunk); + } + + function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), + theirChanges = collectChange(their); + + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + // Special case for remove changes that are supersets of one another + if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + var _hunk$lines3; + + (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); + + return; + } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + var _hunk$lines4; + + (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); + + return; + } + } else if (arrayEqual(myChanges, theirChanges)) { + var _hunk$lines5; + + (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); + + return; + } + + conflict(hunk, myChanges, theirChanges); + } + + function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), + theirChanges = collectContext(their, myChanges); + + if (theirChanges.merged) { + var _hunk$lines6; + + (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } + } + + function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine: mine, + theirs: their + }); + } + + function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } + } + + function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } + } + + function collectChange(state) { + var ret = [], + operation = state.lines[state.index][0]; + + while (state.index < state.lines.length) { + var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. + + if (operation === '-' && line[0] === '+') { + operation = '+'; + } + + if (operation === line[0]) { + ret.push(line); + state.index++; + } else { + break; + } + } + + return ret; + } + + function collectContext(state, matchChanges) { + var changes = [], + merged = [], + matchIndex = 0, + contextChanges = false, + conflicted = false; + + while (matchIndex < matchChanges.length && state.index < state.lines.length) { + var change = state.lines[state.index], + match = matchChanges[matchIndex]; // Once we've hit our add, then we are done + + if (match[0] === '+') { + break; + } + + contextChanges = contextChanges || change[0] !== ' '; + merged.push(match); + matchIndex++; // Consume any additions in the other block as a conflict to attempt + // to pull in the remaining context after this + + if (change[0] === '+') { + conflicted = true; + + while (change[0] === '+') { + changes.push(change); + change = state.lines[++state.index]; + } + } + + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state.index++; + } else { + conflicted = true; + } + } + + if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { + conflicted = true; + } + + if (conflicted) { + return changes; + } + + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + + return { + merged: merged, + changes: changes + }; + } + + function allRemoves(changes) { + return changes.reduce(function (prev, change) { + return prev && change[0] === '-'; + }, true); + } + + function skipRemoveSuperset(state, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + + if (state.lines[state.index + i] !== ' ' + changeContent) { + return false; + } + } + + state.index += delta; + return true; + } + + function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + lines.forEach(function (line) { + if (typeof line !== 'string') { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + + if (oldLines !== undefined) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = undefined; + } + } + + if (newLines !== undefined) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = undefined; + } + } + } else { + if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { + newLines++; + } + + if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { + oldLines++; + } + } + }); + return { + oldLines: oldLines, + newLines: newLines + }; + } + + // See: http://code.google.com/p/google-diff-match-patch/wiki/API + function convertChangesToDMP(changes) { + var ret = [], + change, + operation; + + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + + return ret; + } + + function convertChangesToXML(changes) { + var ret = []; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + + return ret.join(''); + } + + function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; + } + + /* See LICENSE file for terms of use */ + + exports.Diff = Diff; + exports.diffChars = diffChars; + exports.diffWords = diffWords; + exports.diffWordsWithSpace = diffWordsWithSpace; + exports.diffLines = diffLines; + exports.diffTrimmedLines = diffTrimmedLines; + exports.diffSentences = diffSentences; + exports.diffCss = diffCss; + exports.diffJson = diffJson; + exports.diffArrays = diffArrays; + exports.structuredPatch = structuredPatch; + exports.createTwoFilesPatch = createTwoFilesPatch; + exports.createPatch = createPatch; + exports.applyPatch = applyPatch; + exports.applyPatches = applyPatches; + exports.parsePatch = parsePatch; + exports.merge = merge; + exports.convertChangesToDMP = convertChangesToDMP; + exports.convertChangesToXML = convertChangesToXML; + exports.canonicalize = canonicalize; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/node_modules/diff/dist/diff.min.js b/node_modules/diff/dist/diff.min.js new file mode 100644 index 0000000..0ece867 --- /dev/null +++ b/node_modules/diff/dist/diff.min.js @@ -0,0 +1 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e=e||self).Diff={})}(this,function(e){"use strict";function t(){}function g(e,n,t,r,i){for(var o=0,s=n.length,l=0,a=0;oe.length?t:e}),u.value=e.join(d)}else u.value=e.join(t.slice(l,l+u.count));l+=u.count,u.added||(a+=u.count)}}var c=n[s-1];return 1=c&&h<=r+1)return d([{value:this.join(u),count:u.length}]);function i(){for(var e=-1*p;e<=p;e+=2){var n=void 0,t=v[e-1],r=v[e+1],i=(r?r.newPos:0)-e;t&&(v[e-1]=void 0);var o=t&&t.newPos+1=c&&h<=i+1)return d(g(f,n.components,u,a,f.useLongestToken));v[e]=n}else v[e]=void 0}var l;p++}if(n)!function e(){setTimeout(function(){if(t=v.length-2&&t.length<=p.context){var u=/\n$/.test(c),f=/\n$/.test(h),d=0==t.length&&x.length>a.oldLines;!u&&d&&x.splice(a.oldLines,0,"\\ No newline at end of file"),(u||d)&&f||x.push("\\ No newline at end of file")}m.push(a),y=w=0,x=[]}L+=t.length,S+=t.length}},o=0;oe.length)return!1;for(var t=0;t"):r.removed&&n.push(""),n.push((i=r.value,void 0,i.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""))),r.added?n.push(""):r.removed&&n.push("")}var i;return n.join("")},e.canonicalize=v,Object.defineProperty(e,"__esModule",{value:!0})}); \ No newline at end of file diff --git a/node_modules/diff/lib/convert/dmp.js b/node_modules/diff/lib/convert/dmp.js new file mode 100644 index 0000000..91ff40a --- /dev/null +++ b/node_modules/diff/lib/convert/dmp.js @@ -0,0 +1,32 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.convertChangesToDMP = convertChangesToDMP; + +/*istanbul ignore end*/ +// See: http://code.google.com/p/google-diff-match-patch/wiki/API +function convertChangesToDMP(changes) { + var ret = [], + change, + operation; + + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + + return ret; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L2RtcC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvRE1QIiwiY2hhbmdlcyIsInJldCIsImNoYW5nZSIsIm9wZXJhdGlvbiIsImkiLCJsZW5ndGgiLCJhZGRlZCIsInJlbW92ZWQiLCJwdXNoIiwidmFsdWUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztBQUFBO0FBQ08sU0FBU0EsbUJBQVQsQ0FBNkJDLE9BQTdCLEVBQXNDO0FBQzNDLE1BQUlDLEdBQUcsR0FBRyxFQUFWO0FBQUE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ICAgIG9wZXJhdGlvbiA9IC0xO1xuICAgIH0gZWxzZSB7XG4gICAgICBvcGVyYXRpb24gPSAwO1xuICAgIH1cblxuICAgIHJldC5wdXNoKFtvcGVyYXRpb24sIGNoYW5nZS52YWx1ZV0pO1xuICB9XG4gIHJldHVybiByZXQ7XG59XG4iXX0= diff --git a/node_modules/diff/lib/convert/xml.js b/node_modules/diff/lib/convert/xml.js new file mode 100644 index 0000000..69ec60c --- /dev/null +++ b/node_modules/diff/lib/convert/xml.js @@ -0,0 +1,42 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.convertChangesToXML = convertChangesToXML; + +/*istanbul ignore end*/ +function convertChangesToXML(changes) { + var ret = []; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + + return ret.join(''); +} + +function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L3htbC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvWE1MIiwiY2hhbmdlcyIsInJldCIsImkiLCJsZW5ndGgiLCJjaGFuZ2UiLCJhZGRlZCIsInB1c2giLCJyZW1vdmVkIiwiZXNjYXBlSFRNTCIsInZhbHVlIiwiam9pbiIsInMiLCJuIiwicmVwbGFjZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQU8sU0FBU0EsbUJBQVQsQ0FBNkJDLE9BQTdCLEVBQXNDO0FBQzNDLE1BQUlDLEdBQUcsR0FBRyxFQUFWOztBQUNBLE9BQUssSUFBSUMsQ0FBQyxHQU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_modules/diff/lib/diff/array.js b/node_modules/diff/lib/diff/array.js new file mode 100644 index 0000000..81f42ea --- /dev/null +++ b/node_modules/diff/lib/diff/array.js @@ -0,0 +1,45 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffArrays = diffArrays; +exports.arrayDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +var arrayDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); + +/*istanbul ignore start*/ +exports.arrayDiff = arrayDiff; + +/*istanbul ignore end*/ +arrayDiff.tokenize = function (value) { + return value.slice(); +}; + +arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; +}; + +function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2FycmF5LmpzIl0sIm5hbWVzIjpbImFycmF5RGlmZiIsIkRpZmYiLCJ0b2tlbml6ZSIsInZhbHVlIiwic2xpY2UiLCJqb2luIiwicmVtb3ZlRW1wdHkiLCJkaWZmQXJyYXlzIiwib2xkQXJyIiwibmV3QXJyIiwiY2FsbGJhY2siLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFFTyxJQUFNQSxTQUFTLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBSjtBQUFBLEVBQWxCOzs7Ozs7QUFDUEQsU0FBUyxDQUFDRSxRQUFWLEdBQXFCLFVBQVNDLEtBQVQsRUFBZ0I7QUFDbkMsU0FBT0EsS0FBSyxDQUFDQyxLQUFOLEVBQVA7QUFDRCxDQUZEOztBQUdBSixTQUFTLENBQUNLLElBQVYsR0FBaUJMLFNBQVMsQ0FBQ00sV0FBVixHQUF3QixVQUFTSCxLQUFULEVBQWdCO0FBQ3ZELFNBQU9BLEtBQVA7QUFDRCxDQUZEOztBQUlPLFNBQVNJLFVBQVQsQ0FBb0JDLE1BQXBCLEVBQTRCQyxNQUE1QixFQUFvQ0MsUUFBcEMsRUFBOEM7QUFBRSxTQUFPVixTQUFTLENBQUNXLElBQVYsQ0FBZUgsTUFBZixFQUF1QkMsTUFBdkIsRUFBK0JDLFFBQS9CLENBQVA7QUFBa0QiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRGlmZiBmcm9tICcuL2Jhc2UnO1xuXG5leHBvcnQgY29uc3QgYXJyYXlEaWZmID0gbmV3IERpZmYoKTtcbmFycmF5RGlmZi50b2tlbml6ZSA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIHJldHVybiB2YWx1ZS5zbGljZSgpO1xufTtcbmFycmF5RGlmZi5qb2luID0gYXJyYXlEaWZmLnJlbW92ZUVtcHR5ID0gZnVuY3Rpb24odmFsdWUpIHtcbiAgcmV0dXJuIHZhbHVlO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZBcnJheXMob2xkQXJyLCBuZXdBcnIsIGNhbGxiYWNrKSB7IHJldHVybiBhcnJheURpZmYuZGlmZihvbGRBcnIsIG5ld0FyciwgY2FsbGJhY2spOyB9XG4iXX0= diff --git a/node_modules/diff/lib/diff/base.js b/node_modules/diff/lib/diff/base.js new file mode 100644 index 0000000..ea661fe --- /dev/null +++ b/node_modules/diff/lib/diff/base.js @@ -0,0 +1,304 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = Diff; + +/*istanbul ignore end*/ +function Diff() {} + +Diff.prototype = { + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + diff: function diff(oldString, newString) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = + /*istanbul ignore start*/ + void 0 + /*istanbul ignore end*/ + ; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + + + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + castInput: function castInput(value) { + return value; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + tokenize: function tokenize(value) { + return value.split(''); + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + join: function join(chars) { + return chars.join(''); + } +}; + +function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; +} + +function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2Vz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1pbmFsIGludG8gdGhlIHByaW9yIHN0cmluZyBhbmQgZHJvcCB0aGUgY2hhbmdlLlxuICAvLyBUaGlzIGlzIG9ubHkgYXZhaWxhYmxlIGZvciBzdHJpbmcgbW9kZS5cbiAgbGV0IGxhc3RDb21wb25lbnQgPSBjb21wb25lbnRzW2NvbXBvbmVudExlbiAtIDFdO1xuICBpZiAoY29tcG9uZW50TGVuID4gMVxuICAgICAgJiYgdHlwZW9mIGxhc3RDb21wb25lbnQudmFsdWUgPT09ICdzdHJpbmcnXG4gICAgICAmJiAobGFzdENvbXBvbmVudC5hZGRlZCB8fCBsYXN0Q29tcG9uZW50LnJlbW92ZWQpXG4gICAgICAmJiBkaWZmLmVxdWFscygnJywgbGFzdENvbXBvbmVudC52YWx1ZSkpIHtcbiAgICBjb21wb25lbnRzW2NvbXBvbmVudExlbiAtIDJdLnZhbHVlICs9IGxhc3RDb21wb25lbnQudmFsdWU7XG4gICAgY29tcG9uZW50cy5wb3AoKTtcbiAgfVxuXG4gIHJldHVybiBjb21wb25lbnRzO1xufVxuXG5mdW5jdGlvbiBjbG9uZVBhdGgocGF0aCkge1xuICByZXR1cm4geyBuZXdQb3M6IHBhdGgubmV3UG9zLCBjb21wb25lbnRzOiBwYXRoLmNvbXBvbmVudHMuc2xpY2UoMCkgfTtcbn1cbiJdfQ== diff --git a/node_modules/diff/lib/diff/character.js b/node_modules/diff/lib/diff/character.js new file mode 100644 index 0000000..4722b16 --- /dev/null +++ b/node_modules/diff/lib/diff/character.js @@ -0,0 +1,37 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffChars = diffChars; +exports.characterDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +var characterDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); + +/*istanbul ignore start*/ +exports.characterDiff = characterDiff; + +/*istanbul ignore end*/ +function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2NoYXJhY3Rlci5qcyJdLCJuYW1lcyI6WyJjaGFyYWN0ZXJEaWZmIiwiRGlmZiIsImRpZmZDaGFycyIsIm9sZFN0ciIsIm5ld1N0ciIsIm9wdGlvbnMiLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFFTyxJQUFNQSxhQUFhLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBSjtBQUFBLEVBQXRCOzs7Ozs7QUFDQSxTQUFTQyxTQUFULENBQW1CQyxNQUFuQixFQUEyQkMsTUFBM0IsRUFBbUNDLE9BQW5DLEVBQTRDO0FBQUUsU0FBT0wsYUFBYSxDQUFDTSxJQUFkLENBQW1CSCxNQUFuQixFQUEyQkMsTUFBM0IsRUFBbUNDLE9BQW5DLENBQVA7QUFBcUQiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRGlmZiBmcm9tICcuL2Jhc2UnO1xuXG5leHBvcnQgY29uc3QgY2hhcmFjdGVyRGlmZiA9IG5ldyBEaWZmKCk7XG5leHBvcnQgZnVuY3Rpb24gZGlmZkNoYXJzKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKSB7IHJldHVybiBjaGFyYWN0ZXJEaWZmLmRpZmYob2xkU3RyLCBuZXdTdHIsIG9wdGlvbnMpOyB9XG4iXX0= diff --git a/node_modules/diff/lib/diff/css.js b/node_modules/diff/lib/diff/css.js new file mode 100644 index 0000000..69ba47e --- /dev/null +++ b/node_modules/diff/lib/diff/css.js @@ -0,0 +1,41 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffCss = diffCss; +exports.cssDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +var cssDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); + +/*istanbul ignore start*/ +exports.cssDiff = cssDiff; + +/*istanbul ignore end*/ +cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); +}; + +function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Nzcy5qcyJdLCJuYW1lcyI6WyJjc3NEaWZmIiwiRGlmZiIsInRva2VuaXplIiwidmFsdWUiLCJzcGxpdCIsImRpZmZDc3MiLCJvbGRTdHIiLCJuZXdTdHIiLCJjYWxsYmFjayIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBOzs7OztBQUVPLElBQU1BLE9BQU8sR0FBRztBQUFJQztBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFKO0FBQUEsRUFBaEI7Ozs7OztBQUNQRCxPQUFPLENBQUNFLFFBQVIsR0FBbUIsVUFBU0MsS0FBVCxFQUFnQjtBQUNqQyxTQUFPQSxLQUFLLENBQUNDLEtBQU4sQ0FBWSxlQUFaLENBQVA7QUFDRCxDQUZEOztBQUlPLFNBQVNDLE9BQVQsQ0FBaUJDLE1BQWpCLEVBQXlCQyxNQUF6QixFQUFpQ0MsUUFBakMsRUFBMkM7QUFBRSxTQUFPUixPQUFPLENBQUNTLElBQVIsQ0FBYUgsTUFBYixFQUFxQkMsTUFBckIsRUFBNkJDLFFBQTdCLENBQVA7QUFBZ0QiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRGlmZiBmcm9tICcuL2Jhc2UnO1xuXG5leHBvcnQgY29uc3QgY3NzRGlmZiA9IG5ldyBEaWZmKCk7XG5jc3NEaWZmLnRva2VuaXplID0gZnVuY3Rpb24odmFsdWUpIHtcbiAgcmV0dXJuIHZhbHVlLnNwbGl0KC8oW3t9OjssXXxcXHMrKS8pO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZDc3Mob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKSB7IHJldHVybiBjc3NEaWZmLmRpZmYob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKTsgfVxuIl19 diff --git a/node_modules/diff/lib/diff/json.js b/node_modules/diff/lib/diff/json.js new file mode 100644 index 0000000..715ef08 --- /dev/null +++ b/node_modules/diff/lib/diff/json.js @@ -0,0 +1,163 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffJson = diffJson; +exports.canonicalize = canonicalize; +exports.jsonDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_line = require("./line") +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/*istanbul ignore end*/ +var objectPrototypeToString = Object.prototype.toString; +var jsonDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a +// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + +/*istanbul ignore start*/ +exports.jsonDiff = jsonDiff; + +/*istanbul ignore end*/ +jsonDiff.useLongestToken = true; +jsonDiff.tokenize = +/*istanbul ignore start*/ +_line +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +lineDiff +/*istanbul ignore end*/ +.tokenize; + +jsonDiff.castInput = function (value) { + /*istanbul ignore start*/ + var _this$options = + /*istanbul ignore end*/ + this.options, + undefinedReplacement = _this$options.undefinedReplacement, + _this$options$stringi = _this$options.stringifyReplacer, + stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) + /*istanbul ignore start*/ + { + return ( + /*istanbul ignore end*/ + typeof v === 'undefined' ? undefinedReplacement : v + ); + } : _this$options$stringi; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); +}; + +jsonDiff.equals = function (left, right) { + return ( + /*istanbul ignore start*/ + _base + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + default + /*istanbul ignore end*/ + .prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')) + ); +}; + +function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); +} // This function handles the presence of circular references by bailing out when encountering an +// object that is already on the "stack" of items being processed. Accepts an optional replacer + + +function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if ( + /*istanbul ignore start*/ + _typeof( + /*istanbul ignore end*/ + obj) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + + var sortedKeys = [], + _key; + + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2pzb24uanMiXSwibmFtZXMiOlsib2JqZWN0UHJvdG90eXBlVG9TdHJpbmciLCJPYmplY3QiLCJwcm90b3R5cGUiLCJ0b1N0cmluZyIsImpzb25EaWZmIiwiRGlmZiIsInVzZUxvbmdlc3RUb2tlbiIsInRva2VuaXplIiwibGluZURpZmYiLCJjYXN0SW5wdXQiLCJ2YWx1ZSIsIm9wdGlvbnMiLCJ1bmRlZmluZWRSZXBsYWNlbWVudCIsInN0cmluZ2lmeVJlcGxhY2VyIiwiayIsInYiLCJKU09OIiwic3RyaW5naWZ5IiwiY2Fub25pY2FsaXplIiwiZXF1YWxzIiwibGVmdCIsInJpZ2h0IiwiY2FsbCIsInJlcGxhY2UiLCJkaWZmSnNvbiIsIm9sZE9iaiIsIm5ld09iaiIsImRpZmYiLCJvYmoiLCJzdGFjayIsInJlcGxhY2VtZW50U3RhY2siLCJyZX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tleXMucHVzaChrZXkpO1xuICAgICAgfVxuICAgIH1cbiAgICBzb3J0ZWRLZXlzLnNvcnQoKTtcbiAgICBmb3IgKGkgPSAwOyBpIDwgc29ydGVkS2V5cy5sZW5ndGg7IGkgKz0gMSkge1xuICAgICAga2V5ID0gc29ydGVkS2V5c1tpXTtcbiAgICAgIGNhbm9uaWNhbGl6ZWRPYmpba2V5XSA9IGNhbm9uaWNhbGl6ZShvYmpba2V5XSwgc3RhY2ssIHJlcGxhY2VtZW50U3RhY2ssIHJlcGxhY2VyLCBrZXkpO1xuICAgIH1cbiAgICBzdGFjay5wb3AoKTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnBvcCgpO1xuICB9IGVsc2Uge1xuICAgIGNhbm9uaWNhbGl6ZWRPYmogPSBvYmo7XG4gIH1cbiAgcmV0dXJuIGNhbm9uaWNhbGl6ZWRPYmo7XG59XG4iXX0= diff --git a/node_modules/diff/lib/diff/line.js b/node_modules/diff/lib/diff/line.js new file mode 100644 index 0000000..f323f84 --- /dev/null +++ b/node_modules/diff/lib/diff/line.js @@ -0,0 +1,89 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffLines = diffLines; +exports.diffTrimmedLines = diffTrimmedLines; +exports.lineDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_params = require("../util/params") +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +var lineDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); + +/*istanbul ignore start*/ +exports.lineDiff = lineDiff; + +/*istanbul ignore end*/ +lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; +}; + +function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); +} + +function diffTrimmedLines(oldStr, newStr, callback) { + var options = + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _params + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + generateOptions) + /*istanbul ignore end*/ + (callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2xpbmUuanMiXSwibmFtZXMiOlsibGluZURpZmYiLCJEaWZmIiwidG9rZW5pemUiLCJ2YWx1ZSIsInJldExpbmVzIiwibGluZXNBbmROZXdsaW5lcyIsInNwbGl0IiwibGVuZ3RoIiwicG9wIiwiaSIsImxpbmUiLCJvcHRpb25zIiwibmV3bGluZUlzVG9rZW4iLCJpZ25vcmVXaGl0ZXNwYWNlIiwidHJpbSIsInB1c2giLCJkaWZmTGluZXMiLCJvbGRTdHIiLCJuZXdTdHIiLCJjYWxsYmFjayIsImRpZmYiLCJkaWZmVHJpbW1lZExpbmVzIiwiZ2VuZXJhdGVPcHRpb25zIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7OztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFFTyxJQUFNQSxRQUFRLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQ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cblxuICAvLyBNZXJnZSB0aGUgY29udGVudCBhbmQgbGluZSBzZXBhcmF0b3JzIGludG8gc2luZ2xlIHRva2Vuc1xuICBmb3IgKGxldCBpID0gMDsgaSA8IGxpbmVzQW5kTmV3bGluZXMubGVuZ3RoOyBpKyspIHtcbiAgICBsZXQgbGluZSA9IGxpbmVzQW5kTmV3bGluZXNbaV07XG5cbiAgICBpZiAoaSAlIDIgJiYgIXRoaXMub3B0aW9ucy5uZXdsaW5lSXNUb2tlbikge1xuICAgICAgcmV0TGluZXNbcmV0TGluZXMubGVuZ3RoIC0gMV0gKz0gbGluZTtcbiAgICB9IGVsc2Uge1xuICAgICAgaWYgKHRoaXMub3B0aW9ucy5pZ25vcmVXaGl0ZXNwYWNlKSB7XG4gICAgICAgIGxpbmUgPSBsaW5lLnRyaW0oKTtcbiAgICAgIH1cbiAgICAgIHJldExpbmVzLnB1c2gobGluZSk7XG4gICAgfVxuICB9XG5cbiAgcmV0dXJuIHJldExpbmVzO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZMaW5lcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHsgcmV0dXJuIGxpbmVEaWZmLmRpZmYob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKTsgfVxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZUcmltbWVkTGluZXMob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKSB7XG4gIGxldCBvcHRpb25zID0gZ2VuZXJhdGVPcHRpb25zKGNhbGxiYWNrLCB7aWdub3JlV2hpdGVzcGFjZTogdHJ1ZX0pO1xuICByZXR1cm4gbGluZURpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucyk7XG59XG4iXX0= diff --git a/node_modules/diff/lib/diff/sentence.js b/node_modules/diff/lib/diff/sentence.js new file mode 100644 index 0000000..9ee96e9 --- /dev/null +++ b/node_modules/diff/lib/diff/sentence.js @@ -0,0 +1,41 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffSentences = diffSentences; +exports.sentenceDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +var sentenceDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); + +/*istanbul ignore start*/ +exports.sentenceDiff = sentenceDiff; + +/*istanbul ignore end*/ +sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); +}; + +function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3NlbnRlbmNlLmpzIl0sIm5hbWVzIjpbInNlbnRlbmNlRGlmZiIsIkRpZmYiLCJ0b2tlbml6ZSIsInZhbHVlIiwic3BsaXQiLCJkaWZmU2VudGVuY2VzIiwib2xkU3RyIiwibmV3U3RyIiwiY2FsbGJhY2siLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFHTyxJQUFNQSxZQUFZLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBSjtBQUFBLEVBQXJCOzs7Ozs7QUFDUEQsWUFBWSxDQUFDRSxRQUFiLEdBQXdCLFVBQVNDLEtBQVQsRUFBZ0I7QUFDdEMsU0FBT0EsS0FBSyxDQUFDQyxLQUFOLENBQVksdUJBQVosQ0FBUDtBQUNELENBRkQ7O0FBSU8sU0FBU0MsYUFBVCxDQUF1QkMsTUFBdkIsRUFBK0JDLE1BQS9CLEVBQXVDQyxRQUF2QyxFQUFpRDtBQUFFLFNBQU9SLFlBQVksQ0FBQ1MsSUFBYixDQUFrQkgsTUFBbEIsRUFBMEJDLE1BQTFCLEVBQWtDQyxRQUFsQyxDQUFQO0FBQXFEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcblxuXG5leHBvcnQgY29uc3Qgc2VudGVuY2VEaWZmID0gbmV3IERpZmYoKTtcbnNlbnRlbmNlRGlmZi50b2tlbml6ZSA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIHJldHVybiB2YWx1ZS5zcGxpdCgvKFxcUy4rP1suIT9dKSg/PVxccyt8JCkvKTtcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmU2VudGVuY2VzKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjaykgeyByZXR1cm4gc2VudGVuY2VEaWZmLmRpZmYob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKTsgfVxuIl19 diff --git a/node_modules/diff/lib/diff/word.js b/node_modules/diff/lib/diff/word.js new file mode 100644 index 0000000..0b952e0 --- /dev/null +++ b/node_modules/diff/lib/diff/word.js @@ -0,0 +1,107 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffWords = diffWords; +exports.diffWordsWithSpace = diffWordsWithSpace; +exports.wordDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_params = require("../util/params") +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode +// +// Ranges and exceptions: +// Latin-1 Supplement, 0080–00FF +// - U+00D7 × Multiplication sign +// - U+00F7 ÷ Division sign +// Latin Extended-A, 0100–017F +// Latin Extended-B, 0180–024F +// IPA Extensions, 0250–02AF +// Spacing Modifier Letters, 02B0–02FF +// - U+02C7 ˇ ˇ Caron +// - U+02D8 ˘ ˘ Breve +// - U+02D9 ˙ ˙ Dot Above +// - U+02DA ˚ ˚ Ring Above +// - U+02DB ˛ ˛ Ogonek +// - U+02DC ˜ ˜ Small Tilde +// - U+02DD ˝ ˝ Double Acute Accent +// Latin Extended Additional, 1E00–1EFF +var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; +var reWhitespace = /\S/; +var wordDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); + +/*istanbul ignore start*/ +exports.wordDiff = wordDiff; + +/*istanbul ignore end*/ +wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); +}; + +wordDiff.tokenize = function (value) { + var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; +}; + +function diffWords(oldStr, newStr, options) { + options = + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _params + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + generateOptions) + /*istanbul ignore end*/ + (options, { + ignoreWhitespace: true + }); + return wordDiff.diff(oldStr, newStr, options); +} + +function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff.diff(oldStr, newStr,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0aW9uIGRpZmZXb3JkcyhvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICBvcHRpb25zID0gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiB3b3JkRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3Jkc1dpdGhTcGFjZShvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICByZXR1cm4gd29yZERpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucyk7XG59XG4iXX0= diff --git a/node_modules/diff/lib/index.es6.js b/node_modules/diff/lib/index.es6.js new file mode 100644 index 0000000..6dd2a6f --- /dev/null +++ b/node_modules/diff/lib/index.es6.js @@ -0,0 +1,1519 @@ +function Diff() {} +Diff.prototype = { + diff: function diff(oldString, newString) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = void 0; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + + + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + castInput: function castInput(value) { + return value; + }, + tokenize: function tokenize(value) { + return value.split(''); + }, + join: function join(chars) { + return chars.join(''); + } +}; + +function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; +} + +function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; +} + +var characterDiff = new Diff(); +function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); +} + +function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + + return defaults; +} + +// +// Ranges and exceptions: +// Latin-1 Supplement, 0080–00FF +// - U+00D7 × Multiplication sign +// - U+00F7 ÷ Division sign +// Latin Extended-A, 0100–017F +// Latin Extended-B, 0180–024F +// IPA Extensions, 0250–02AF +// Spacing Modifier Letters, 02B0–02FF +// - U+02C7 ˇ ˇ Caron +// - U+02D8 ˘ ˘ Breve +// - U+02D9 ˙ ˙ Dot Above +// - U+02DA ˚ ˚ Ring Above +// - U+02DB ˛ ˛ Ogonek +// - U+02DC ˜ ˜ Small Tilde +// - U+02DD ˝ ˝ Double Acute Accent +// Latin Extended Additional, 1E00–1EFF + +var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; +var reWhitespace = /\S/; +var wordDiff = new Diff(); + +wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); +}; + +wordDiff.tokenize = function (value) { + var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; +}; + +function diffWords(oldStr, newStr, options) { + options = generateOptions(options, { + ignoreWhitespace: true + }); + return wordDiff.diff(oldStr, newStr, options); +} +function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff.diff(oldStr, newStr, options); +} + +var lineDiff = new Diff(); + +lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; +}; + +function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); +} +function diffTrimmedLines(oldStr, newStr, callback) { + var options = generateOptions(callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options); +} + +var sentenceDiff = new Diff(); + +sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); +}; + +function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); +} + +var cssDiff = new Diff(); + +cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); +}; + +function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); +} + +function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} + +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); +} + +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } +} + +function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); +} + +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance"); +} + +var objectPrototypeToString = Object.prototype.toString; +var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a +// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + +jsonDiff.useLongestToken = true; +jsonDiff.tokenize = lineDiff.tokenize; + +jsonDiff.castInput = function (value) { + var _this$options = this.options, + undefinedReplacement = _this$options.undefinedReplacement, + _this$options$stringi = _this$options.stringifyReplacer, + stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { + return typeof v === 'undefined' ? undefinedReplacement : v; + } : _this$options$stringi; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); +}; + +jsonDiff.equals = function (left, right) { + return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); +}; + +function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); +} // This function handles the presence of circular references by bailing out when encountering an +// object that is already on the "stack" of items being processed. Accepts an optional replacer + +function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if (_typeof(obj) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + + var sortedKeys = [], + _key; + + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; +} + +var arrayDiff = new Diff(); + +arrayDiff.tokenize = function (value) { + return value.slice(); +}; + +arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; +}; + +function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); +} + +function parsePatch(uniDiff) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); // Parse diff metadata + + while (i < diffstr.length) { + var line = diffstr[i]; // File header found, end parsing diff metadata + + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } // Diff index + + + var headerMatch = /^(?:Index:|diff(?: -r \w+)+)\s+/.exec(line); + + if (headerMatch) { + index.index = line.substring(headerMatch[0].length).trim(); + } + + i++; + } // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + + + parseFileHeader(index); + parseFileHeader(index); // Parse hunks + + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + + + function parseFileHeader(index) { + var fileHeaderMatch = /^(---|\+\+\+)\s+/.exec(diffstr[i]); + + if (fileHeaderMatch) { + var keyPrefix = fileHeaderMatch[1] === '---' ? 'old' : 'new'; + var data = diffstr[i].substring(3).trim().split('\t', 2); + var fileName = data[0].replace(/\\\\/g, '\\'); + + if (fileName.startsWith('"') && fileName.endsWith('"')) { + fileName = fileName.substr(1, fileName.length - 2); + } + + index[keyPrefix + 'FileName'] = fileName; + index[keyPrefix + 'Header'] = (data[1] || '').trim(); + i++; + } + } // Parses a hunk + // This assumes that we are at the start of a hunk. + + + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [], + linedelimiters: [] + }; + var addCount = 0, + removeCount = 0; + + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } // Handle the empty block count case + + + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } // Perform optional sanity checking + + + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; +} + +// Iterator that traverses in the range of [min, max], stepping +// by distance from a given start position. I.e. for [0, 4], with +// start of 2, this will iterate 2, 3, 1, 4, 0. +function distanceIterator (start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + + + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + + + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } // We tried to fit hunk before text beginning and beyond text length, then + // hunk can't fit on the text. Return undefined + + }; +} + +function applyPatch(source, uniDiff) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } // Apply the diff to the input + + + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { + return line === patchContent; + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL, + addEOFNL; + /** + * Checks if the hunk exactly fits on the provided location + */ + + + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line; + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + + toPos++; + } + } + + return true; + } // Search best fit offsets for each hunk based on the previous ones + + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + var iterator = distanceIterator(toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + + + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } // Apply patch hunks + + + var diffOffset = 0; + + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; + + diffOffset += _hunk.newLines - _hunk.oldLines; + + if (_toPos < 0) { + // Creating a new file + _toPos = 0; + } + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line, + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } // Handle EOFNL insertion/removal + + + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + + return lines.join(''); +} // Wrapper that supports multiple file patches via callbacks. + +function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + var currentIndex = 0; + + function processIndex() { + var index = uniDiff[currentIndex++]; + + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + + processIndex(); +} + +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = diffLines(oldStr, newStr, options); + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + var _loop = function _loop(i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + var _curRange; + + // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + + (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + var _curRange2; + + // Overlapping + (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); + } else { + var _curRange3; + + // end the range and output + var contextSize = Math.min(lines.length, options.context); + + (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + + if (!oldEOFNewline && noNlBeforeAdds) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } + + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + _loop(i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; +} +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + var ret = []; + + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; +} +function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); +} + +function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + + return arrayStartsWith(a, b); +} +function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + + return true; +} + +function calcLineCount(hunk) { + var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), + oldLines = _calcOldNewLineCount.oldLines, + newLines = _calcOldNewLineCount.newLines; + + if (oldLines !== undefined) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + + if (newLines !== undefined) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } +} +function merge(mine, theirs, base) { + mine = loadPatch(mine, base); + theirs = loadPatch(theirs, base); + var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. + // Leaving sanity checks on this to the API consumer that may know more about the + // meaning in their own context. + + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + // No header or no change in ours, use theirs (and ours if theirs does not exist) + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + // No header or no change in theirs, use ours + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + // Both changed... figure it out + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + + ret.hunks = []; + var mineIndex = 0, + theirsIndex = 0, + mineOffset = 0, + theirsOffset = 0; + + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { + oldStart: Infinity + }, + theirsCurrent = theirs.hunks[theirsIndex] || { + oldStart: Infinity + }; + + if (hunkBefore(mineCurrent, theirsCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + // Overlap, merge as best we can + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + ret.hunks.push(mergedHunk); + } + } + + return ret; +} + +function loadPatch(param, base) { + if (typeof param === 'string') { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return parsePatch(param)[0]; + } + + if (!base) { + throw new Error('Must provide a base reference or pass in a patch'); + } + + return structuredPatch(undefined, undefined, base, param); + } + + return param; +} + +function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; +} + +function selectField(index, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index.conflict = true; + return { + mine: mine, + theirs: theirs + }; + } +} + +function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; +} + +function cloneHunk(hunk, offset) { + return { + oldStart: hunk.oldStart, + oldLines: hunk.oldLines, + newStart: hunk.newStart + offset, + newLines: hunk.newLines, + lines: hunk.lines + }; +} + +function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + // This will generally result in a conflicted hunk, but there are cases where the context + // is the only overlap where we can successfully merge the content here. + var mine = { + offset: mineOffset, + lines: mineLines, + index: 0 + }, + their = { + offset: theirOffset, + lines: theirLines, + index: 0 + }; // Handle any leading content + + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. + + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], + theirCurrent = their.lines[their.index]; + + if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { + // Both modified ... + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { + var _hunk$lines; + + // Mine inserted + (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); + } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { + var _hunk$lines2; + + // Theirs inserted + (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); + } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { + // Mine removed or edited + removal(hunk, mine, their); + } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { + // Their removed or edited + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + // Context identity + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + // Context mismatch + conflict(hunk, collectChange(mine), collectChange(their)); + } + } // Now push anything that may be remaining + + + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + calcLineCount(hunk); +} + +function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), + theirChanges = collectChange(their); + + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + // Special case for remove changes that are supersets of one another + if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + var _hunk$lines3; + + (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); + + return; + } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + var _hunk$lines4; + + (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); + + return; + } + } else if (arrayEqual(myChanges, theirChanges)) { + var _hunk$lines5; + + (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); + + return; + } + + conflict(hunk, myChanges, theirChanges); +} + +function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), + theirChanges = collectContext(their, myChanges); + + if (theirChanges.merged) { + var _hunk$lines6; + + (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } +} + +function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine: mine, + theirs: their + }); +} + +function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } +} + +function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } +} + +function collectChange(state) { + var ret = [], + operation = state.lines[state.index][0]; + + while (state.index < state.lines.length) { + var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. + + if (operation === '-' && line[0] === '+') { + operation = '+'; + } + + if (operation === line[0]) { + ret.push(line); + state.index++; + } else { + break; + } + } + + return ret; +} + +function collectContext(state, matchChanges) { + var changes = [], + merged = [], + matchIndex = 0, + contextChanges = false, + conflicted = false; + + while (matchIndex < matchChanges.length && state.index < state.lines.length) { + var change = state.lines[state.index], + match = matchChanges[matchIndex]; // Once we've hit our add, then we are done + + if (match[0] === '+') { + break; + } + + contextChanges = contextChanges || change[0] !== ' '; + merged.push(match); + matchIndex++; // Consume any additions in the other block as a conflict to attempt + // to pull in the remaining context after this + + if (change[0] === '+') { + conflicted = true; + + while (change[0] === '+') { + changes.push(change); + change = state.lines[++state.index]; + } + } + + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state.index++; + } else { + conflicted = true; + } + } + + if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { + conflicted = true; + } + + if (conflicted) { + return changes; + } + + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + + return { + merged: merged, + changes: changes + }; +} + +function allRemoves(changes) { + return changes.reduce(function (prev, change) { + return prev && change[0] === '-'; + }, true); +} + +function skipRemoveSuperset(state, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + + if (state.lines[state.index + i] !== ' ' + changeContent) { + return false; + } + } + + state.index += delta; + return true; +} + +function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + lines.forEach(function (line) { + if (typeof line !== 'string') { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + + if (oldLines !== undefined) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = undefined; + } + } + + if (newLines !== undefined) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = undefined; + } + } + } else { + if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { + newLines++; + } + + if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { + oldLines++; + } + } + }); + return { + oldLines: oldLines, + newLines: newLines + }; +} + +// See: http://code.google.com/p/google-diff-match-patch/wiki/API +function convertChangesToDMP(changes) { + var ret = [], + change, + operation; + + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + + return ret; +} + +function convertChangesToXML(changes) { + var ret = []; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + + return ret.join(''); +} + +function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; +} + +/* See LICENSE file for terms of use */ + +export { Diff, diffChars, diffWords, diffWordsWithSpace, diffLines, diffTrimmedLines, diffSentences, diffCss, diffJson, diffArrays, structuredPatch, createTwoFilesPatch, createPatch, applyPatch, applyPatches, parsePatch, merge, convertChangesToDMP, convertChangesToXML, canonicalize }; diff --git a/node_modules/diff/lib/index.js b/node_modules/diff/lib/index.js new file mode 100644 index 0000000..ff8ae91 --- /dev/null +++ b/node_modules/diff/lib/index.js @@ -0,0 +1,216 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "Diff", { + enumerable: true, + get: function get() { + return _base.default; + } +}); +Object.defineProperty(exports, "diffChars", { + enumerable: true, + get: function get() { + return _character.diffChars; + } +}); +Object.defineProperty(exports, "diffWords", { + enumerable: true, + get: function get() { + return _word.diffWords; + } +}); +Object.defineProperty(exports, "diffWordsWithSpace", { + enumerable: true, + get: function get() { + return _word.diffWordsWithSpace; + } +}); +Object.defineProperty(exports, "diffLines", { + enumerable: true, + get: function get() { + return _line.diffLines; + } +}); +Object.defineProperty(exports, "diffTrimmedLines", { + enumerable: true, + get: function get() { + return _line.diffTrimmedLines; + } +}); +Object.defineProperty(exports, "diffSentences", { + enumerable: true, + get: function get() { + return _sentence.diffSentences; + } +}); +Object.defineProperty(exports, "diffCss", { + enumerable: true, + get: function get() { + return _css.diffCss; + } +}); +Object.defineProperty(exports, "diffJson", { + enumerable: true, + get: function get() { + return _json.diffJson; + } +}); +Object.defineProperty(exports, "canonicalize", { + enumerable: true, + get: function get() { + return _json.canonicalize; + } +}); +Object.defineProperty(exports, "diffArrays", { + enumerable: true, + get: function get() { + return _array.diffArrays; + } +}); +Object.defineProperty(exports, "applyPatch", { + enumerable: true, + get: function get() { + return _apply.applyPatch; + } +}); +Object.defineProperty(exports, "applyPatches", { + enumerable: true, + get: function get() { + return _apply.applyPatches; + } +}); +Object.defineProperty(exports, "parsePatch", { + enumerable: true, + get: function get() { + return _parse.parsePatch; + } +}); +Object.defineProperty(exports, "merge", { + enumerable: true, + get: function get() { + return _merge.merge; + } +}); +Object.defineProperty(exports, "structuredPatch", { + enumerable: true, + get: function get() { + return _create.structuredPatch; + } +}); +Object.defineProperty(exports, "createTwoFilesPatch", { + enumerable: true, + get: function get() { + return _create.createTwoFilesPatch; + } +}); +Object.defineProperty(exports, "createPatch", { + enumerable: true, + get: function get() { + return _create.createPatch; + } +}); +Object.defineProperty(exports, "convertChangesToDMP", { + enumerable: true, + get: function get() { + return _dmp.convertChangesToDMP; + } +}); +Object.defineProperty(exports, "convertChangesToXML", { + enumerable: true, + get: function get() { + return _xml.convertChangesToXML; + } +}); + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./diff/base")) +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_character = require("./diff/character") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_word = require("./diff/word") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_line = require("./diff/line") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_sentence = require("./diff/sentence") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_css = require("./diff/css") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_json = require("./diff/json") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_array = require("./diff/array") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_apply = require("./patch/apply") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_parse = require("./patch/parse") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_merge = require("./patch/merge") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_create = require("./patch/create") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_dmp = require("./convert/dmp") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_xml = require("./convert/xml") +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9pbmRleC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQWdCQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQTs7QUFDQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBRUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7QUFDQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUVBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBRUE7QUFBQTtBQUFBO0FBQU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FxuXG4gIHN0cnVjdHVyZWRQYXRjaCxcbiAgY3JlYXRlVHdvRmlsZXNQYXRjaCxcbiAgY3JlYXRlUGF0Y2gsXG4gIGFwcGx5UGF0Y2gsXG4gIGFwcGx5UGF0Y2hlcyxcbiAgcGFyc2VQYXRjaCxcbiAgbWVyZ2UsXG4gIGNvbnZlcnRDaGFuZ2VzVG9ETVAsXG4gIGNvbnZlcnRDaGFuZ2VzVG9YTUwsXG4gIGNhbm9uaWNhbGl6ZVxufTtcbiJdfQ== diff --git a/node_modules/diff/lib/patch/apply.js b/node_modules/diff/lib/patch/apply.js new file mode 100644 index 0000000..19bddd8 --- /dev/null +++ b/node_modules/diff/lib/patch/apply.js @@ -0,0 +1,243 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.applyPatch = applyPatch; +exports.applyPatches = applyPatches; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_parse = require("./parse") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_distanceIterator = _interopRequireDefault(require("../util/distance-iterator")) +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +function applyPatch(source, uniDiff) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (typeof uniDiff === 'string') { + uniDiff = + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _parse + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + parsePatch) + /*istanbul ignore end*/ + (uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } // Apply the diff to the input + + + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) + /*istanbul ignore start*/ + { + return ( + /*istanbul ignore end*/ + line === patchContent + ); + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL, + addEOFNL; + /** + * Checks if the hunk exactly fits on the provided location + */ + + + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line; + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + + toPos++; + } + } + + return true; + } // Search best fit offsets for each hunk based on the previous ones + + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + var iterator = + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _distanceIterator + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + default) + /*istanbul ignore end*/ + (toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + + + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } // Apply patch hunks + + + var diffOffset = 0; + + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; + + diffOffset += _hunk.newLines - _hunk.oldLines; + + if (_toPos < 0) { + // Creating a new file + _toPos = 0; + } + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line, + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } // Handle EOFNL insertion/removal + + + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + + return lines.join(''); +} // Wrapper that supports multiple file patches via callbacks. + + +function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _parse + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + parsePatch) + /*istanbul ignore end*/ + (uniDiff); + } + + var currentIndex = 0; + + function processIndex() { + var index = uniDiff[currentIndex++]; + + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + + processIndex(); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9hcHBseS5qcyJdLCJuYW1lcyI6WyJhcHBseVBhdGNoIiwic291cmNlIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJwYXJzZVBhdGNoIiwiQXJyYXkiLCJpc0FycmF5IiwibGVuZ3RoIiwiRXJyb3IiLCJsaW5lcyIsInNwbGl0IiwiZGVsa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gICAgICAgICByZXR1cm4gb3B0aW9ucy5jb21wbGV0ZShlcnIpO1xuICAgICAgICB9XG5cbiAgICAgICAgcHJvY2Vzc0luZGV4KCk7XG4gICAgICB9KTtcbiAgICB9KTtcbiAgfVxuICBwcm9jZXNzSW5kZXgoKTtcbn1cbiJdfQ== diff --git a/node_modules/diff/lib/patch/create.js b/node_modules/diff/lib/patch/create.js new file mode 100644 index 0000000..d1717fe --- /dev/null +++ b/node_modules/diff/lib/patch/create.js @@ -0,0 +1,247 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.structuredPatch = structuredPatch; +exports.createTwoFilesPatch = createTwoFilesPatch; +exports.createPatch = createPatch; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_line = require("../diff/line") +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +/*istanbul ignore end*/ +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _line + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + diffLines) + /*istanbul ignore end*/ + (oldStr, newStr, options); + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + /*istanbul ignore start*/ + var _loop = function _loop( + /*istanbul ignore end*/ + i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + /*istanbul ignore start*/ + var _curRange; + + /*istanbul ignore end*/ + // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + + /*istanbul ignore start*/ + (_curRange = + /*istanbul ignore end*/ + curRange).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _curRange + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + /*istanbul ignore start*/ + var _curRange2; + + /*istanbul ignore end*/ + // Overlapping + + /*istanbul ignore start*/ + (_curRange2 = + /*istanbul ignore end*/ + curRange).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _curRange2 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + contextLines(lines))); + } else { + /*istanbul ignore start*/ + var _curRange3; + + /*istanbul ignore end*/ + // end the range and output + var contextSize = Math.min(lines.length, options.context); + + /*istanbul ignore start*/ + (_curRange3 = + /*istanbul ignore end*/ + curRange).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _curRange3 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + + if (!oldEOFNewline && noNlBeforeAdds) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } + + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + /*istanbul ignore start*/ + _loop( + /*istanbul ignore end*/ + i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; +} + +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + var ret = []; + + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; +} + +function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9jcmVhdGUuanMiXSwibmFtZXMiOlsic3RydWN0dXJlZFBhdGNoIiwib2xkRmlsZU5hbWUiLCJuZXdGaWxlTmFtZSIsIm9sZFN0ciIsIm5ld1N0ciIsIm9sZEhlYWRlciIsIm5ld0hlYWRlciIsIm9wdGlvbnMiLCJjb250ZXh0IiwiZGlmZiIsImRpZmZMaW5lcyIsInB1c2giLCJ2YWx1ZSIsImxpbmVzIiwiY29udGV4dExpbmVzIiwibWFwIiwiZW50cnkiLCJodW5rcyIsIm9sZFJhbmdlU3RhcnQiLCJuZXdSYW5nZVN0YXJ0IiwiY3VyUmFuZ2UiLCJvbGRMaW5lIiwibmV3TGluZSIsImkiLCJjdXJyZW50IiwicmVwbGFjZSIsInNwbGl0IiwiYWRkZWQiLCJyZW1vdmVkIiwicHJldiIsInNsaWNlIiwibGVuZ3RoIiwiY29udGV4dFNpemUiLCJNYXRoIiwibWluIiwiaHVuayIsIm9sZFN0YXJ0Iiwib2xkTGluZXMiLCJuZXdTdGFydCIsIm5ld0xpbmVzIiwib2xkRU9GTmV3bGluZSIsInRlc3QiLCJuZXdFT0ZOZXdsaW5lIiwibm9ObEJlZm9yZUFkZHMiLCJzcGxpY2UiLCJjcmVhdGVUd29GaWxlc1BhdGNoIiwicmV0IiwiYXBwbHkiLCJqb2luIiwiY3JlYXRlUGF0Y2giLCJmaWxlTmFtZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBOzs7Ozs7Ozs7OztBQUVPLFNBQVNBLGVBQVQsQ0FBeUJDLFdBQXpCLEVBQXNDQyxXQUF0QyxFQUFtREMsTUFBb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qb2luKCdcXG4nKSArICdcXG4nO1xufVxuXG5leHBvcnQgZnVuY3Rpb24gY3JlYXRlUGF0Y2goZmlsZU5hbWUsIG9sZFN0ciwgbmV3U3RyLCBvbGRIZWFkZXIsIG5ld0hlYWRlciwgb3B0aW9ucykge1xuICByZXR1cm4gY3JlYXRlVHdvRmlsZXNQYXRjaChmaWxlTmFtZSwgZmlsZU5hbWUsIG9sZFN0ciwgbmV3U3RyLCBvbGRIZWFkZXIsIG5ld0hlYWRlciwgb3B0aW9ucyk7XG59XG4iXX0= diff --git a/node_modules/diff/lib/patch/merge.js b/node_modules/diff/lib/patch/merge.js new file mode 100644 index 0000000..bbd429a --- /dev/null +++ b/node_modules/diff/lib/patch/merge.js @@ -0,0 +1,609 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.calcLineCount = calcLineCount; +exports.merge = merge; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_create = require("./create") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_parse = require("./parse") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_array = require("../util/array") +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +/*istanbul ignore end*/ +function calcLineCount(hunk) { + /*istanbul ignore start*/ + var _calcOldNewLineCount = + /*istanbul ignore end*/ + calcOldNewLineCount(hunk.lines), + oldLines = _calcOldNewLineCount.oldLines, + newLines = _calcOldNewLineCount.newLines; + + if (oldLines !== undefined) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + + if (newLines !== undefined) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } +} + +function merge(mine, theirs, base) { + mine = loadPatch(mine, base); + theirs = loadPatch(theirs, base); + var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. + // Leaving sanity checks on this to the API consumer that may know more about the + // meaning in their own context. + + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + // No header or no change in ours, use theirs (and ours if theirs does not exist) + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + // No header or no change in theirs, use ours + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + // Both changed... figure it out + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + + ret.hunks = []; + var mineIndex = 0, + theirsIndex = 0, + mineOffset = 0, + theirsOffset = 0; + + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { + oldStart: Infinity + }, + theirsCurrent = theirs.hunks[theirsIndex] || { + oldStart: Infinity + }; + + if (hunkBefore(mineCurrent, theirsCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + // Overlap, merge as best we can + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + ret.hunks.push(mergedHunk); + } + } + + return ret; +} + +function loadPatch(param, base) { + if (typeof param === 'string') { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return ( + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _parse + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + parsePatch) + /*istanbul ignore end*/ + (param)[0] + ); + } + + if (!base) { + throw new Error('Must provide a base reference or pass in a patch'); + } + + return ( + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _create + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + structuredPatch) + /*istanbul ignore end*/ + (undefined, undefined, base, param) + ); + } + + return param; +} + +function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; +} + +function selectField(index, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index.conflict = true; + return { + mine: mine, + theirs: theirs + }; + } +} + +function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; +} + +function cloneHunk(hunk, offset) { + return { + oldStart: hunk.oldStart, + oldLines: hunk.oldLines, + newStart: hunk.newStart + offset, + newLines: hunk.newLines, + lines: hunk.lines + }; +} + +function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + // This will generally result in a conflicted hunk, but there are cases where the context + // is the only overlap where we can successfully merge the content here. + var mine = { + offset: mineOffset, + lines: mineLines, + index: 0 + }, + their = { + offset: theirOffset, + lines: theirLines, + index: 0 + }; // Handle any leading content + + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. + + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], + theirCurrent = their.lines[their.index]; + + if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { + // Both modified ... + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { + /*istanbul ignore start*/ + var _hunk$lines; + + /*istanbul ignore end*/ + // Mine inserted + + /*istanbul ignore start*/ + (_hunk$lines = + /*istanbul ignore end*/ + hunk.lines).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _hunk$lines + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + collectChange(mine))); + } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { + /*istanbul ignore start*/ + var _hunk$lines2; + + /*istanbul ignore end*/ + // Theirs inserted + + /*istanbul ignore start*/ + (_hunk$lines2 = + /*istanbul ignore end*/ + hunk.lines).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _hunk$lines2 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + collectChange(their))); + } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { + // Mine removed or edited + removal(hunk, mine, their); + } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { + // Their removed or edited + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + // Context identity + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + // Context mismatch + conflict(hunk, collectChange(mine), collectChange(their)); + } + } // Now push anything that may be remaining + + + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + calcLineCount(hunk); +} + +function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), + theirChanges = collectChange(their); + + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + // Special case for remove changes that are supersets of one another + if ( + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _array + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + arrayStartsWith) + /*istanbul ignore end*/ + (myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + /*istanbul ignore start*/ + var _hunk$lines3; + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines3 = + /*istanbul ignore end*/ + hunk.lines).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _hunk$lines3 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + myChanges)); + + return; + } else if ( + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _array + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + arrayStartsWith) + /*istanbul ignore end*/ + (theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + /*istanbul ignore start*/ + var _hunk$lines4; + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines4 = + /*istanbul ignore end*/ + hunk.lines).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _hunk$lines4 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + theirChanges)); + + return; + } + } else if ( + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _array + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + arrayEqual) + /*istanbul ignore end*/ + (myChanges, theirChanges)) { + /*istanbul ignore start*/ + var _hunk$lines5; + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines5 = + /*istanbul ignore end*/ + hunk.lines).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _hunk$lines5 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + myChanges)); + + return; + } + + conflict(hunk, myChanges, theirChanges); +} + +function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), + theirChanges = collectContext(their, myChanges); + + if (theirChanges.merged) { + /*istanbul ignore start*/ + var _hunk$lines6; + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines6 = + /*istanbul ignore end*/ + hunk.lines).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _hunk$lines6 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } +} + +function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine: mine, + theirs: their + }); +} + +function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } +} + +function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } +} + +function collectChange(state) { + var ret = [], + operation = state.lines[state.index][0]; + + while (state.index < state.lines.length) { + var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. + + if (operation === '-' && line[0] === '+') { + operation = '+'; + } + + if (operation === line[0]) { + ret.push(line); + state.index++; + } else { + break; + } + } + + return ret; +} + +function collectContext(state, matchChanges) { + var changes = [], + merged = [], + matchIndex = 0, + contextChanges = false, + conflicted = false; + + while (matchIndex < matchChanges.length && state.index < state.lines.length) { + var change = state.lines[state.index], + match = matchChanges[matchIndex]; // Once we've hit our add, then we are done + + if (match[0] === '+') { + break; + } + + contextChanges = contextChanges || change[0] !== ' '; + merged.push(match); + matchIndex++; // Consume any additions in the other block as a conflict to attempt + // to pull in the remaining context after this + + if (change[0] === '+') { + conflicted = true; + + while (change[0] === '+') { + changes.push(change); + change = state.lines[++state.index]; + } + } + + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state.index++; + } else { + conflicted = true; + } + } + + if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { + conflicted = true; + } + + if (conflicted) { + return changes; + } + + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + + return { + merged: merged, + changes: changes + }; +} + +function allRemoves(changes) { + return changes.reduce(function (prev, change) { + return prev && change[0] === '-'; + }, true); +} + +function skipRemoveSuperset(state, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + + if (state.lines[state.index + i] !== ' ' + changeContent) { + return false; + } + } + + state.index += delta; + return true; +} + +function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + lines.forEach(function (line) { + if (typeof line !== 'string') { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + + if (oldLines !== undefined) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = undefined; + } + } + + if (newLines !== undefined) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = undefined; + } + } + } else { + if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { + newLines++; + } + + if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { + oldLines++; + } + } + }); + return { + oldLines: oldLines, + newLines: newLines + }; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9tZXJnZS5qcyJdLCJuYW1lcyI6WyJjYWxjTGluZUNvdW50IiwiaHVuayIsImNhbGNPbGROZXd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0gZWxzZSB7XG4gICAgICAgICAgbmV3TGluZXMgPSB1bmRlZmluZWQ7XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICB9IGVsc2Uge1xuICAgICAgaWYgKG5ld0xpbmVzICE9PSB1bmRlZmluZWQgJiYgKGxpbmVbMF0gPT09ICcrJyB8fCBsaW5lWzBdID09PSAnICcpKSB7XG4gICAgICAgIG5ld0xpbmVzKys7XG4gICAgICB9XG4gICAgICBpZiAob2xkTGluZXMgIT09IHVuZGVmaW5lZCAmJiAobGluZVswXSA9PT0gJy0nIHx8IGxpbmVbMF0gPT09ICcgJykpIHtcbiAgICAgICAgb2xkTGluZXMrKztcbiAgICAgIH1cbiAgICB9XG4gIH0pO1xuXG4gIHJldHVybiB7b2xkTGluZXMsIG5ld0xpbmVzfTtcbn1cbiJdfQ== diff --git a/node_modules/diff/lib/patch/parse.js b/node_modules/diff/lib/patch/parse.js new file mode 100644 index 0000000..51bae56 --- /dev/null +++ b/node_modules/diff/lib/patch/parse.js @@ -0,0 +1,156 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parsePatch = parsePatch; + +/*istanbul ignore end*/ +function parsePatch(uniDiff) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); // Parse diff metadata + + while (i < diffstr.length) { + var line = diffstr[i]; // File header found, end parsing diff metadata + + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } // Diff index + + + var headerMatch = /^(?:Index:|diff(?: -r \w+)+)\s+/.exec(line); + + if (headerMatch) { + index.index = line.substring(headerMatch[0].length).trim(); + } + + i++; + } // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + + + parseFileHeader(index); + parseFileHeader(index); // Parse hunks + + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + + + function parseFileHeader(index) { + var fileHeaderMatch = /^(---|\+\+\+)\s+/.exec(diffstr[i]); + + if (fileHeaderMatch) { + var keyPrefix = fileHeaderMatch[1] === '---' ? 'old' : 'new'; + var data = diffstr[i].substring(3).trim().split('\t', 2); + var fileName = data[0].replace(/\\\\/g, '\\'); + + if (fileName.startsWith('"') && fileName.endsWith('"')) { + fileName = fileName.substr(1, fileName.length - 2); + } + + index[keyPrefix + 'FileName'] = fileName; + index[keyPrefix + 'Header'] = (data[1] || '').trim(); + i++; + } + } // Parses a hunk + // This assumes that we are at the start of a hunk. + + + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [], + linedelimiters: [] + }; + var addCount = 0, + removeCount = 0; + + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } // Handle the empty block count case + + + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } // Perform optional sanity checking + + + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9wYXJzZS5qcyJdLCJuYW1lcyI6WyJwYXJzZVBhdGNoIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJkaWZmc3RyIiwic3BsaXQiLCJkZWxpbWl0ZXJzIiwibWF0Y2giLCJsaXN0IiwiaSIsInBhcnNlSW5kZXgiLCJpbmRleCIsInB1c2giLCJsZW5ndGgiLCJsaW5lIiwidGVzdCIsImhlYWRlck1hdGNoIiwiZXhlYyIsInN1YnN0cmluZyIsInRyaW0iLCJwYXJzZUZpbGVIZWFkZXIiLCJodW5rcyIsInBhcnNlSHVuayIsInN0cmljdCIsIkVycm9yIiwiSlNPTiIsInN0cmluZ2lmeSIsImZpbGVIZWFkZXJNYXRjaCIsImtleVByZWZpeCIsImRhdGEiLCJmaWxlTmFtZSIsInJlcGxhY2UiLCJzdGFydHNXaXRoIiwiZW5kc1dpdGgiLCJzdWJzdHIiLCJjaHVua0hlYWRlckluZGV4IiwiY2h1bmtIZWFkZXJMaW5lIiwiY2h1bmtIZWFkZXIiLCJodW5rIiwib2xkU3RhcnQiLCJvbGRMaW5lcyIsIm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md0aCkge1xuICAgIHBhcnNlSW5kZXgoKTtcbiAgfVxuXG4gIHJldHVybiBsaXN0O1xufVxuIl19 diff --git a/node_modules/diff/lib/util/array.js b/node_modules/diff/lib/util/array.js new file mode 100644 index 0000000..aecf67a --- /dev/null +++ b/node_modules/diff/lib/util/array.js @@ -0,0 +1,32 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.arrayEqual = arrayEqual; +exports.arrayStartsWith = arrayStartsWith; + +/*istanbul ignore end*/ +function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + + return arrayStartsWith(a, b); +} + +function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + + return true; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2FycmF5LmpzIl0sIm5hbWVzIjpbImFycmF5RXF1YWwiLCJhIiwiYiIsImxlbmd0aCIsImFycmF5U3RhcnRzV2l0aCIsImFycmF5Iiwic3RhcnQiLCJpIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQU8sU0FBU0EsVUFBVCxDQUFvQkMsQ0FBcEIsRUFBdUJDLENBQXZCLEVBQTBCO0FBQy9CLE1BQUlELENBQUMsQ0FBQ0UsTUFBRixLQUFhRCxDQUFDLENBQUNDLE1BQW5CLEVBQTJCO0FBQ3pCLFdBQU8sS0FBUDtBQUNEOztBQUVELFNBQU9DLGVBQWUsQ0FBQ0gsQ0FBRCxFQUFJQyxDQUFKLENBQXRCO0FBQ0Q7O0FBRU0sU0FBU0UsZUFBVCxDQUF5QkMsS0FBekIsRUFBZ0NDLEtBQWhDLEVBQXVDO0FBQzVDLE1BQUlBLEtBQUssQ0FBQ0gsTUFBTixHQUFlRSxLQUFLLENBQUNGLE1BQXpCLEVBQWlDO0FBQy9CLFdBQU8sS0FBUDtBQUNEOztBQUVELE9BQUssSUFBSUksQ0FBQyxHQUFHLENBQWIsRUFBZ0JBLENBQUMsR0FBR0QsS0FBSyxDQUFDSCxNQUExQixFQUFrQ0ksQ0FBQyxFQUFuQyxFQUF1QztBQUNyQyxRQUFJRCxLQUFLLENBQUNDLENBQUQsQ0FBTCxLQUFhRixLQUFLLENBQUNFLENBQUQsQ0FBdEIsRUFBMkI7QUFDekIsYUFBTyxLQUFQO0FBQ0Q7QUFDRjs7QUFFRCxTQUFPLElBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBmdW5jdGlvbiBhcnJheUVxdWFsKGEsIGIpIHtcbiAgaWYgKGEubGVuZ3RoICE9PSBiLmxlbmd0aCkge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIHJldHVybiBhcnJheVN0YXJ0c1dpdGgoYSwgYik7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBhcnJheVN0YXJ0c1dpdGgoYXJyYXksIHN0YXJ0KSB7XG4gIGlmIChzdGFydC5sZW5ndGggPiBhcnJheS5sZW5ndGgpIHtcbiAgICByZXR1cm4gZmFsc2U7XG4gIH1cblxuICBmb3IgKGxldCBpID0gMDsgaSA8IHN0YXJ0Lmxlbmd0aDsgaSsrKSB7XG4gICAgaWYgKHN0YXJ0W2ldICE9PSBhcnJheVtpXSkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiB0cnVlO1xufVxuIl19 diff --git a/node_modules/diff/lib/util/distance-iterator.js b/node_modules/diff/lib/util/distance-iterator.js new file mode 100644 index 0000000..5edbaf8 --- /dev/null +++ b/node_modules/diff/lib/util/distance-iterator.js @@ -0,0 +1,57 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; + +/*istanbul ignore end*/ +// Iterator that traverses in the range of [min, max], stepping +// by distance from a given start position. I.e. for [0, 4], with +// start of 2, this will iterate 2, 3, 1, 4, 0. +function +/*istanbul ignore start*/ +_default +/*istanbul ignore end*/ +(start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + + + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + + + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } // We tried to fit hunk before text beginning and beyond text length, then + // hunk can't fit on the text. Return undefined + + }; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2Rpc3RhbmNlLWl0ZXJhdG9yLmpzIl0sIm5hbWVzIjpbInN0YXJ0IiwibWluTGluZSIsIm1heExpbmUiLCJ3YW50Rm9yd2FyZCIsImJhY2t3YXJkRXhoYXVzdGVkIiwiZm9yd2FyZEV4aGF1c3RlZCIsImxvY2FsT2Zmc2V0IiwiaXRlcmF0b3IiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztBQUFBO0FBQ0E7QUFDQTtBQUNlO0FBQUE7QUFBQTtBQUFBO0FBQUEsQ0FBU0EsS0FBVCxFQUFnQkMsT0FBaEIsRUFBeUJDLE9BQXpCLEVBQWtDO0FBQy9DLE1BQUlDLFdBQVcsR0FBRyxJQUFsQjtBQUFBLE1BQ0lDLGlCQUFpQixHQUFHLEtBRHhCO0FBQUEsTUFFSUMsZ0JBQWdCLEdBQUcsS0FGdkI7QUFBQSxNQUdJQyxXQUFXLEdBQUcsQ0FIbEI7QUFLQSxTQUFPLFNBQVNDLFFBQVQsR0FBb0I7QUFDekIsUUFBSU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9IHN0YXJ0IC0gbG9jYWxPZmZzZXQpIHtcbiAgICAgICAgcmV0dXJuIC1sb2NhbE9mZnNldCsrO1xuICAgICAgfVxuXG4gICAgICBiYWNrd2FyZEV4aGF1c3RlZCA9IHRydWU7XG4gICAgICByZXR1cm4gaXRlcmF0b3IoKTtcbiAgICB9XG5cbiAgICAvLyBXZSB0cmllZCB0byBmaXQgaHVuayBiZWZvcmUgdGV4dCBiZWdpbm5pbmcgYW5kIGJleW9uZCB0ZXh0IGxlbmd0aCwgdGhlblxuICAgIC8vIGh1bmsgY2FuJ3QgZml0IG9uIHRoZSB0ZXh0LiBSZXR1cm4gdW5kZWZpbmVkXG4gIH07XG59XG4iXX0= diff --git a/node_modules/diff/lib/util/params.js b/node_modules/diff/lib/util/params.js new file mode 100644 index 0000000..e838eb2 --- /dev/null +++ b/node_modules/diff/lib/util/params.js @@ -0,0 +1,24 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.generateOptions = generateOptions; + +/*istanbul ignore end*/ +function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + + return defaults; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL3BhcmFtcy5qcyJdLCJuYW1lcyI6WyJnZW5lcmF0ZU9wdGlvbnMiLCJvcHRpb25zIiwiZGVmYXVsdHMiLCJjYWxsYmFjayIsIm5hbWUiLCJoYXNPd25Qcm9wZXJ0eSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQU8sU0FBU0EsZUFBVCxDQUF5QkMsT0FBekIsRUFBa0NDLFFBQWxDLEVBQTRDO0FBQ2pELE1BQUksT0FBT0QsT0FBUCxLQUFtQixVQUF2QixFQUFtQztBQUNqQ0MsSUFBQUEsUUFBUSxDQUFDQyxRQUFULEdBQW9CRixPQUFwQjtBQUNELEdBRkQsTUFFTyxJQUFJQSxPQUFKLEVBQWE7QUFDbEIsU0FBSyxJQUFJRyxJQUFULElBQWlCSCxPQUFqQixFQUEwQjtBQUN4QjtBQUNBLFVBQUlBLE9BQU8sQ0FBQ0ksY0FBUixDQUF1QkQsSUFBdkIsQ0FBSixFQUFrQztBQUNoQ0YsUUFBQUEsUUFBUSxDQUFDRSxJQUFELENBQVIsR0FBaUJILE9BQU8sQ0FBQ0csSUFBRCxDQUF4QjtBQUNEO0FBQ0Y7QUFDRjs7QUFDRCxTQUFPRixRQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIGRlZmF1bHRzKSB7XG4gIGlmICh0eXBlb2Ygb3B0aW9ucyA9PT0gJ2Z1bmN0aW9uJykge1xuICAgIGRlZmF1bHRzLmNhbGxiYWNrID0gb3B0aW9ucztcbiAgfSBlbHNlIGlmIChvcHRpb25zKSB7XG4gICAgZm9yIChsZXQgbmFtZSBpbiBvcHRpb25zKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9wdGlvbnMuaGFzT3duUHJvcGVydHkobmFtZSkpIHtcbiAgICAgICAgZGVmYXVsdHNbbmFtZV0gPSBvcHRpb25zW25hbWVdO1xuICAgICAgfVxuICAgIH1cbiAgfVxuICByZXR1cm4gZGVmYXVsdHM7XG59XG4iXX0= diff --git a/node_modules/diff/package.json b/node_modules/diff/package.json new file mode 100644 index 0000000..2390039 --- /dev/null +++ b/node_modules/diff/package.json @@ -0,0 +1,74 @@ +{ + "name": "diff", + "version": "4.0.4", + "description": "A javascript text diff implementation.", + "keywords": [ + "diff", + "javascript" + ], + "maintainers": [ + "Kevin Decker (http://incaseofstairs.com)" + ], + "bugs": { + "email": "kpdecker@gmail.com", + "url": "http://github.com/kpdecker/jsdiff/issues" + }, + "license": "BSD-3-Clause", + "repository": { + "type": "git", + "url": "git://github.com/kpdecker/jsdiff.git" + }, + "engines": { + "node": ">=0.3.1" + }, + "main": "./lib/index.js", + "module": "./lib/index.es6.js", + "browser": "./dist/diff.js", + "scripts": { + "clean": "rm -rf lib/ dist/", + "build:node": "yarn babel --out-dir lib --source-maps=inline src", + "test": "grunt" + }, + "devDependencies": { + "@babel/cli": "^7.2.3", + "@babel/core": "^7.2.2", + "@babel/plugin-transform-modules-commonjs": "^7.2.0", + "@babel/preset-env": "^7.2.3", + "@babel/register": "^7.0.0", + "babel-eslint": "^10.0.1", + "babel-loader": "^8.0.5", + "chai": "^4.2.0", + "colors": "^1.3.3", + "eslint": "^5.12.0", + "grunt": "^1.0.3", + "grunt-babel": "^8.0.0", + "grunt-clean": "^0.4.0", + "grunt-cli": "^1.3.2", + "grunt-contrib-clean": "^2.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^4.0.0", + "grunt-contrib-watch": "^1.1.0", + "grunt-eslint": "^21.0.0", + "grunt-exec": "^3.0.0", + "grunt-karma": "^3.0.1", + "grunt-mocha-istanbul": "^5.0.2", + "grunt-mocha-test": "^0.13.3", + "grunt-webpack": "^3.1.3", + "istanbul": "github:kpdecker/istanbul", + "karma": "^3.1.4", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "karma-mocha-reporter": "^2.0.0", + "karma-sauce-launcher": "^2.0.2", + "karma-sourcemap-loader": "^0.3.6", + "karma-webpack": "^3.0.5", + "mocha": "^5.2.0", + "rollup": "^1.0.2", + "rollup-plugin-babel": "^4.2.0", + "semver": "^5.6.0", + "webpack": "^4.28.3", + "webpack-dev-server": "^3.1.14" + }, + "optionalDependencies": {}, + "packageManager": "yarn@1.22.22+sha1.ac34549e6aa8e7ead463a7407e1c7390f61a6610" +} diff --git a/node_modules/diff/release-notes.md b/node_modules/diff/release-notes.md new file mode 100644 index 0000000..edc4cd3 --- /dev/null +++ b/node_modules/diff/release-notes.md @@ -0,0 +1,261 @@ +# Release Notes + +## Development + +[Commits](https://github.com/kpdecker/jsdiff/compare/v4.0.1...master) + +## v4.0.1 - January 6th, 2019 +- Fix main reference path - b826104 + +[Commits](https://github.com/kpdecker/jsdiff/compare/v4.0.0...v4.0.1) + +## v4.0.0 - January 5th, 2019 +- [#94](https://github.com/kpdecker/jsdiff/issues/94) - Missing "No newline at end of file" when comparing two texts that do not end in newlines ([@federicotdn](https://api.github.com/users/federicotdn)) +- [#227](https://github.com/kpdecker/jsdiff/issues/227) - Licence +- [#199](https://github.com/kpdecker/jsdiff/issues/199) - Import statement for jsdiff +- [#159](https://github.com/kpdecker/jsdiff/issues/159) - applyPatch affecting wrong line number with with new lines +- [#8](https://github.com/kpdecker/jsdiff/issues/8) - A new state "replace" +- Drop ie9 from karma targets - 79c31bd +- Upgrade deps. Convert from webpack to rollup - 2c1a29c +- Make ()[]"' as word boundaries between each other - f27b899 +- jsdiff: Replaced phantomJS by chrome - ec3114e +- Add yarn.lock to .npmignore - 29466d8 + +Compatibility notes: +- Bower and Component packages no longer supported + + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.5.0...v4.0.0) + +## v3.5.0 - March 4th, 2018 +- Omit redundant slice in join method of diffArrays - 1023590 +- Support patches with empty lines - fb0f208 +- Accept a custom JSON replacer function for JSON diffing - 69c7f0a +- Optimize parch header parser - 2aec429 +- Fix typos - e89c832 + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.4.0...v3.5.0) + +## v3.4.0 - October 7th, 2017 +- [#183](https://github.com/kpdecker/jsdiff/issues/183) - Feature request: ability to specify a custom equality checker for `diffArrays` +- [#173](https://github.com/kpdecker/jsdiff/issues/173) - Bug: diffArrays gives wrong result on array of booleans +- [#158](https://github.com/kpdecker/jsdiff/issues/158) - diffArrays will not compare the empty string in array? +- comparator for custom equality checks - 30e141e +- count oldLines and newLines when there are conflicts - 53bf384 +- Fix: diffArrays can compare falsey items - 9e24284 +- Docs: Replace grunt with npm test - 00e2f94 + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.3.1...v3.4.0) + +## v3.3.1 - September 3rd, 2017 +- [#141](https://github.com/kpdecker/jsdiff/issues/141) - Cannot apply patch because my file delimiter is "/r/n" instead of "/n" +- [#192](https://github.com/kpdecker/jsdiff/pull/192) - Fix: Bad merge when adding new files (#189) +- correct spelling mistake - 21fa478 + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.3.0...v3.3.1) + +## v3.3.0 - July 5th, 2017 +- [#114](https://github.com/kpdecker/jsdiff/issues/114) - /patch/merge not exported +- Gracefully accept invalid newStart in hunks, same as patch(1) does. - d8a3635 +- Use regex rather than starts/ends with for parsePatch - 6cab62c +- Add browser flag - e64f674 +- refactor: simplified code a bit more - 8f8e0f2 +- refactor: simplified code a bit - b094a6f +- fix: some corrections re ignoreCase option - 3c78fd0 +- ignoreCase option - 3cbfbb5 +- Sanitize filename while parsing patches - 2fe8129 +- Added better installation methods - aced50b +- Simple export of functionality - 8690f31 + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.2.0...v3.3.0) + +## v3.2.0 - December 26th, 2016 +- [#156](https://github.com/kpdecker/jsdiff/pull/156) - Add `undefinedReplacement` option to `diffJson` ([@ewnd9](https://api.github.com/users/ewnd9)) +- [#154](https://github.com/kpdecker/jsdiff/pull/154) - Add `examples` and `images` to `.npmignore`. ([@wtgtybhertgeghgtwtg](https://api.github.com/users/wtgtybhertgeghgtwtg)) +- [#153](https://github.com/kpdecker/jsdiff/pull/153) - feat(structuredPatch): Pass options to diffLines ([@Kiougar](https://api.github.com/users/Kiougar)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.1.0...v3.2.0) + +## v3.1.0 - November 27th, 2016 +- [#146](https://github.com/kpdecker/jsdiff/pull/146) - JsDiff.diffArrays to compare arrays ([@wvanderdeijl](https://api.github.com/users/wvanderdeijl)) +- [#144](https://github.com/kpdecker/jsdiff/pull/144) - Split file using all possible line delimiter instead of hard-coded "/n" and join lines back using the original delimiters ([@soulbeing](https://api.github.com/users/soulbeing)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.0.1...v3.1.0) + +## v3.0.1 - October 9th, 2016 +- [#139](https://github.com/kpdecker/jsdiff/pull/139) - Make README.md look nicer in npmjs.com ([@takenspc](https://api.github.com/users/takenspc)) +- [#135](https://github.com/kpdecker/jsdiff/issues/135) - parsePatch combines patches from multiple files into a single IUniDiff when there is no "Index" line ([@ramya-rao-a](https://api.github.com/users/ramya-rao-a)) +- [#124](https://github.com/kpdecker/jsdiff/issues/124) - IE7/IE8 failure since 2.0.0 ([@boneskull](https://api.github.com/users/boneskull)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.0.0...v3.0.1) + +## v3.0.0 - August 23rd, 2016 +- [#130](https://github.com/kpdecker/jsdiff/pull/130) - Add callback argument to applyPatches `patched` option ([@piranna](https://api.github.com/users/piranna)) +- [#120](https://github.com/kpdecker/jsdiff/pull/120) - Correctly handle file names containing spaces ([@adius](https://api.github.com/users/adius)) +- [#119](https://github.com/kpdecker/jsdiff/pull/119) - Do single reflow ([@wifiextender](https://api.github.com/users/wifiextender)) +- [#117](https://github.com/kpdecker/jsdiff/pull/117) - Make more usable with long strings. ([@abnbgist](https://api.github.com/users/abnbgist)) + +Compatibility notes: +- applyPatches patch callback now is async and requires the callback be called to continue operation + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.3...v3.0.0) + +## v2.2.3 - May 31st, 2016 +- [#118](https://github.com/kpdecker/jsdiff/pull/118) - Add a fix for applying 0-length destination patches ([@chaaz](https://api.github.com/users/chaaz)) +- [#115](https://github.com/kpdecker/jsdiff/pull/115) - Fixed grammar in README ([@krizalys](https://api.github.com/users/krizalys)) +- [#113](https://github.com/kpdecker/jsdiff/pull/113) - fix typo ([@vmazare](https://api.github.com/users/vmazare)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.2...v2.2.3) + +## v2.2.2 - March 13th, 2016 +- [#102](https://github.com/kpdecker/jsdiff/issues/102) - diffJson with dates, returns empty curly braces ([@dr-dimitru](https://api.github.com/users/dr-dimitru)) +- [#97](https://github.com/kpdecker/jsdiff/issues/97) - Whitespaces & diffWords ([@faiwer](https://api.github.com/users/faiwer)) +- [#92](https://github.com/kpdecker/jsdiff/pull/92) - Fixes typo in the readme ([@bg451](https://api.github.com/users/bg451)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.1...v2.2.2) + +## v2.2.1 - November 12th, 2015 +- [#89](https://github.com/kpdecker/jsdiff/pull/89) - add in display selector to readme ([@FranDias](https://api.github.com/users/FranDias)) +- [#88](https://github.com/kpdecker/jsdiff/pull/88) - Split diffs based on file headers instead of 'Index:' metadata ([@piranna](https://api.github.com/users/piranna)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.0...v2.2.1) + +## v2.2.0 - October 29th, 2015 +- [#80](https://github.com/kpdecker/jsdiff/pull/80) - Fix a typo: applyPath -> applyPatch ([@fluxxu](https://api.github.com/users/fluxxu)) +- [#83](https://github.com/kpdecker/jsdiff/pull/83) - Add basic fuzzy matching to applyPatch ([@piranna](https://github.com/piranna)) +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.0...v2.2.0) + +## v2.2.0 - October 29th, 2015 +- [#80](https://github.com/kpdecker/jsdiff/pull/80) - Fix a typo: applyPath -> applyPatch ([@fluxxu](https://api.github.com/users/fluxxu)) +- [#83](https://github.com/kpdecker/jsdiff/pull/83) - Add basic fuzzy matching to applyPatch ([@piranna](https://github.com/piranna)) +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.3...v2.2.0) + +## v2.1.3 - September 30th, 2015 +- [#78](https://github.com/kpdecker/jsdiff/pull/78) - fix: error throwing when apply patch to empty string ([@21paradox](https://api.github.com/users/21paradox)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.2...v2.1.3) + +## v2.1.2 - September 23rd, 2015 +- [#76](https://github.com/kpdecker/jsdiff/issues/76) - diff headers give error ([@piranna](https://api.github.com/users/piranna)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.1...v2.1.2) + +## v2.1.1 - September 9th, 2015 +- [#73](https://github.com/kpdecker/jsdiff/issues/73) - Is applyPatches() exposed in the API? ([@davidparsson](https://api.github.com/users/davidparsson)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.0...v2.1.1) + +## v2.1.0 - August 27th, 2015 +- [#72](https://github.com/kpdecker/jsdiff/issues/72) - Consider using options object API for flag permutations ([@kpdecker](https://api.github.com/users/kpdecker)) +- [#70](https://github.com/kpdecker/jsdiff/issues/70) - diffWords treats \n at the end as significant whitespace ([@nesQuick](https://api.github.com/users/nesQuick)) +- [#69](https://github.com/kpdecker/jsdiff/issues/69) - Missing count ([@wfalkwallace](https://api.github.com/users/wfalkwallace)) +- [#68](https://github.com/kpdecker/jsdiff/issues/68) - diffLines seems broken ([@wfalkwallace](https://api.github.com/users/wfalkwallace)) +- [#60](https://github.com/kpdecker/jsdiff/issues/60) - Support multiple diff hunks ([@piranna](https://api.github.com/users/piranna)) +- [#54](https://github.com/kpdecker/jsdiff/issues/54) - Feature Request: 3-way merge ([@mog422](https://api.github.com/users/mog422)) +- [#42](https://github.com/kpdecker/jsdiff/issues/42) - Fuzz factor for applyPatch ([@stuartpb](https://api.github.com/users/stuartpb)) +- Move whitespace ignore out of equals method - 542063c +- Include source maps in babel output - 7f7ab21 +- Merge diff/line and diff/patch implementations - 1597705 +- Drop map utility method - 1ddc939 +- Documentation for parsePatch and applyPatches - 27c4b77 + +Compatibility notes: +- The undocumented ignoreWhitespace flag has been removed from the Diff equality check directly. This implementation may be copied to diff utilities if dependencies existed on this functionality. + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.2...v2.1.0) + +## v2.0.2 - August 8th, 2015 +- [#67](https://github.com/kpdecker/jsdiff/issues/67) - cannot require from npm module in node ([@commenthol](https://api.github.com/users/commenthol)) +- Convert to chai since we don’t support IE8 - a96bbad + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.1...v2.0.2) + +## v2.0.1 - August 7th, 2015 +- Add release build at proper step - 57542fd + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.0...v2.0.1) + +## v2.0.0 - August 7th, 2015 +- [#66](https://github.com/kpdecker/jsdiff/issues/66) - Add karma and sauce tests ([@kpdecker](https://api.github.com/users/kpdecker)) +- [#65](https://github.com/kpdecker/jsdiff/issues/65) - Create component repository for bower ([@kpdecker](https://api.github.com/users/kpdecker)) +- [#64](https://github.com/kpdecker/jsdiff/issues/64) - Automatically call removeEmpty for all tokenizer calls ([@kpdecker](https://api.github.com/users/kpdecker)) +- [#62](https://github.com/kpdecker/jsdiff/pull/62) - Allow access to structured object representation of patch data ([@bittrance](https://api.github.com/users/bittrance)) +- [#61](https://github.com/kpdecker/jsdiff/pull/61) - Use svg instead of png to get better image quality ([@PeterDaveHello](https://api.github.com/users/PeterDaveHello)) +- [#29](https://github.com/kpdecker/jsdiff/issues/29) - word tokenizer works only for 7 bit ascii ([@plasmagunman](https://api.github.com/users/plasmagunman)) + +Compatibility notes: +- `this.removeEmpty` is now called automatically for all instances. If this is not desired, this may be overridden on a per instance basis. +- The library has been refactored to use some ES6 features. The external APIs should remain the same, but bower projects that directly referenced the repository will now have to point to the [components/jsdiff](https://github.com/components/jsdiff) repository. + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.4.0...v2.0.0) + +## v1.4.0 - May 6th, 2015 +- [#57](https://github.com/kpdecker/jsdiff/issues/57) - createPatch -> applyPatch failed. ([@mog422](https://api.github.com/users/mog422)) +- [#56](https://github.com/kpdecker/jsdiff/pull/56) - Two files patch ([@rgeissert](https://api.github.com/users/rgeissert)) +- [#14](https://github.com/kpdecker/jsdiff/issues/14) - Flip added and removed order? ([@jakesandlund](https://api.github.com/users/jakesandlund)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.2...v1.4.0) + +## v1.3.2 - March 30th, 2015 +- [#53](https://github.com/kpdecker/jsdiff/pull/53) - Updated README.MD with Bower installation instructions ([@ofbriggs](https://api.github.com/users/ofbriggs)) +- [#49](https://github.com/kpdecker/jsdiff/issues/49) - Cannot read property 'oldlines' of undefined ([@nwtn](https://api.github.com/users/nwtn)) +- [#44](https://github.com/kpdecker/jsdiff/issues/44) - invalid-meta jsdiff is missing "main" entry in bower.json + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.1...v1.3.2) + +## v1.3.1 - March 13th, 2015 +- [#52](https://github.com/kpdecker/jsdiff/pull/52) - Fix for #51 Wrong result of JsDiff.diffLines ([@felicienfrancois](https://api.github.com/users/felicienfrancois)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.0...v1.3.1) + +## v1.3.0 - March 2nd, 2015 +- [#47](https://github.com/kpdecker/jsdiff/pull/47) - Adding Diff Trimmed Lines ([@JamesGould123](https://api.github.com/users/JamesGould123)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.2...v1.3.0) + +## v1.2.2 - January 26th, 2015 +- [#45](https://github.com/kpdecker/jsdiff/pull/45) - Fix AMD module loading ([@pedrocarrico](https://api.github.com/users/pedrocarrico)) +- [#43](https://github.com/kpdecker/jsdiff/pull/43) - added a bower file ([@nbrustein](https://api.github.com/users/nbrustein)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.1...v1.2.2) + +## v1.2.1 - December 26th, 2014 +- [#41](https://github.com/kpdecker/jsdiff/pull/41) - change condition of using node export system. ([@ironhee](https://api.github.com/users/ironhee)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.0...v1.2.1) + +## v1.2.0 - November 29th, 2014 +- [#37](https://github.com/kpdecker/jsdiff/pull/37) - Add support for sentences. ([@vmariano](https://api.github.com/users/vmariano)) +- [#28](https://github.com/kpdecker/jsdiff/pull/28) - Implemented diffJson ([@papandreou](https://api.github.com/users/papandreou)) +- [#27](https://github.com/kpdecker/jsdiff/issues/27) - Slow to execute over diffs with a large number of changes ([@termi](https://api.github.com/users/termi)) +- Allow for optional async diffing - 19385b9 +- Fix diffChars implementation - eaa44ed + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.1.0...v1.2.0) + +## v1.1.0 - November 25th, 2014 +- [#33](https://github.com/kpdecker/jsdiff/pull/33) - AMD and global exports ([@ovcharik](https://api.github.com/users/ovcharik)) +- [#32](https://github.com/kpdecker/jsdiff/pull/32) - Add support for component ([@vmariano](https://api.github.com/users/vmariano)) +- [#31](https://github.com/kpdecker/jsdiff/pull/31) - Don't rely on Array.prototype.map ([@papandreou](https://api.github.com/users/papandreou)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.8...v1.1.0) + +## v1.0.8 - December 22nd, 2013 +- [#24](https://github.com/kpdecker/jsdiff/pull/24) - Handle windows newlines on non windows machines. ([@benogle](https://api.github.com/users/benogle)) +- [#23](https://github.com/kpdecker/jsdiff/pull/23) - Prettied up the API formatting a little, and added basic node and web examples ([@airportyh](https://api.github.com/users/airportyh)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.7...v1.0.8) + +## v1.0.7 - September 11th, 2013 + +- [#22](https://github.com/kpdecker/jsdiff/pull/22) - Added variant of WordDiff that doesn't ignore whitespace differences ([@papandreou](https://api.github.com/users/papandreou) + +- Add 0.10 to travis tests - 243a526 + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.6...v1.0.7) + +## v1.0.6 - August 30th, 2013 + +- [#19](https://github.com/kpdecker/jsdiff/pull/19) - Explicitly define contents of npm package ([@sindresorhus](https://api.github.com/users/sindresorhus) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.5...v1.0.6) diff --git a/node_modules/diff/runtime.js b/node_modules/diff/runtime.js new file mode 100644 index 0000000..82ea7e6 --- /dev/null +++ b/node_modules/diff/runtime.js @@ -0,0 +1,3 @@ +require('@babel/register')({ + ignore: ['lib', 'node_modules'] +}); diff --git a/node_modules/eventemitter3/LICENSE b/node_modules/eventemitter3/LICENSE new file mode 100644 index 0000000..abcbd54 --- /dev/null +++ b/node_modules/eventemitter3/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Arnout Kazemier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/eventemitter3/README.md b/node_modules/eventemitter3/README.md new file mode 100644 index 0000000..e45aa10 --- /dev/null +++ b/node_modules/eventemitter3/README.md @@ -0,0 +1,85 @@ +# EventEmitter3 + +[![Version npm](https://img.shields.io/npm/v/eventemitter3.svg?style=flat-square)](https://www.npmjs.com/package/eventemitter3)[![CI](https://img.shields.io/github/actions/workflow/status/primus/eventemitter3/ci.yml?branch=master&label=CI&style=flat-square)](https://github.com/primus/eventemitter3/actions?query=workflow%3ACI+branch%3Amaster)[![Coverage Status](https://img.shields.io/coveralls/primus/eventemitter3/master.svg?style=flat-square)](https://coveralls.io/r/primus/eventemitter3?branch=master) + +EventEmitter3 is a high performance EventEmitter. It has been micro-optimized +for various of code paths making this, one of, if not the fastest EventEmitter +available for Node.js and browsers. The module is API compatible with the +EventEmitter that ships by default with Node.js but there are some slight +differences: + +- Domain support has been removed. +- We do not `throw` an error when you emit an `error` event and nobody is + listening. +- The `newListener` and `removeListener` events have been removed as they + are useful only in some uncommon use-cases. +- The `setMaxListeners`, `getMaxListeners`, `prependListener` and + `prependOnceListener` methods are not available. +- Support for custom context for events so there is no need to use `fn.bind`. +- The `removeListener` method removes all matching listeners, not only the + first. + +It's a drop in replacement for existing EventEmitters, but just faster. Free +performance, who wouldn't want that? The EventEmitter is written in EcmaScript 3 +so it will work in the oldest browsers and node versions that you need to +support. + +## Installation + +```bash +$ npm install --save eventemitter3 +``` + +## CDN + +Recommended CDN: + +```text +https://unpkg.com/eventemitter3@latest/dist/eventemitter3.umd.min.js +``` + +## Usage + +After installation the only thing you need to do is require the module: + +```js +var EventEmitter = require('eventemitter3'); +``` + +And you're ready to create your own EventEmitter instances. For the API +documentation, please follow the official Node.js documentation: + +http://nodejs.org/api/events.html + +### Contextual emits + +We've upgraded the API of the `EventEmitter.on`, `EventEmitter.once` and +`EventEmitter.removeListener` to accept an extra argument which is the `context` +or `this` value that should be set for the emitted events. This means you no +longer have the overhead of an event that required `fn.bind` in order to get a +custom `this` value. + +```js +var EE = new EventEmitter() + , context = { foo: 'bar' }; + +function emitted() { + console.log(this === context); // true +} + +EE.once('event-name', emitted, context); +EE.on('another-event', emitted, context); +EE.removeListener('another-event', emitted, context); +``` + +### Tests and benchmarks + +To run tests run `npm test`. To run the benchmarks run `npm run benchmark`. + +Tests and benchmarks are not included in the npm package. If you want to play +with them you have to clone the GitHub repository. Note that you will have to +run an additional `npm i` in the benchmarks folder before `npm run benchmark`. + +## License + +[MIT](LICENSE) diff --git a/node_modules/eventemitter3/dist/eventemitter3.esm.js b/node_modules/eventemitter3/dist/eventemitter3.esm.js new file mode 100644 index 0000000..70759d0 --- /dev/null +++ b/node_modules/eventemitter3/dist/eventemitter3.esm.js @@ -0,0 +1,355 @@ +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var eventemitter3 = {exports: {}}; + +var hasRequiredEventemitter3; + +function requireEventemitter3 () { + if (hasRequiredEventemitter3) return eventemitter3.exports; + hasRequiredEventemitter3 = 1; + (function (module) { + + var has = Object.prototype.hasOwnProperty + , prefix = '~'; + + /** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ + function Events() {} + + // + // We try to not inherit from `Object.prototype`. In some engines creating an + // instance in this way is faster than calling `Object.create(null)` directly. + // If `Object.create(null)` is not supported we prefix the event names with a + // character to make sure that the built-in object properties are not + // overridden or used as an attack vector. + // + if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; + } + + /** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + + /** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ + function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + + return emitter; + } + + /** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; + } + + /** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } + + /** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ + EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; + }; + + /** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; + }; + + /** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + + /** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; + }; + + /** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; + + /** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; + + /** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + + return this; + }; + + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; + }; + + // + // Alias methods names because people roll like that. + // + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + + // + // Expose the prefix. + // + EventEmitter.prefixed = prefix; + + // + // Allow `EventEmitter` to be imported as module namespace. + // + EventEmitter.EventEmitter = EventEmitter; + + // + // Expose the module. + // + { + module.exports = EventEmitter; + } + } (eventemitter3)); + return eventemitter3.exports; +} + +var eventemitter3Exports = requireEventemitter3(); +var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports); + +export { EventEmitter, EventEmitter as default }; diff --git a/node_modules/eventemitter3/dist/eventemitter3.esm.min.js b/node_modules/eventemitter3/dist/eventemitter3.esm.min.js new file mode 100644 index 0000000..82c1ec0 --- /dev/null +++ b/node_modules/eventemitter3/dist/eventemitter3.esm.min.js @@ -0,0 +1 @@ +function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t,n={exports:{}};var r=(t||(t=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function s(e,t,r,s,i){if("function"!=typeof r)throw new TypeError("The listener must be a function");var c=new o(r,s||e,i),f=n?n+t:t;return e._events[f]?e._events[f].fn?e._events[f]=[e._events[f],c]:e._events[f].push(c):(e._events[f]=c,e._eventsCount++),e}function i(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function c(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),c.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},c.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,s=r.length,i=new Array(s);o { + static prefixed: string | boolean; + + /** + * Return an array listing the events for which the emitter has registered + * listeners. + */ + eventNames(): Array>; + + /** + * Return the listeners registered for a given event. + */ + listeners>( + event: T + ): Array>; + + /** + * Return the number of listeners listening to a given event. + */ + listenerCount(event: EventEmitter.EventNames): number; + + /** + * Calls each of the listeners registered for a given event. + */ + emit>( + event: T, + ...args: EventEmitter.EventArgs + ): boolean; + + /** + * Add a listener for a given event. + */ + on>( + event: T, + fn: EventEmitter.EventListener, + context?: Context + ): this; + addListener>( + event: T, + fn: EventEmitter.EventListener, + context?: Context + ): this; + + /** + * Add a one-time listener for a given event. + */ + once>( + event: T, + fn: EventEmitter.EventListener, + context?: Context + ): this; + + /** + * Remove the listeners of a given event. + */ + removeListener>( + event: T, + fn?: EventEmitter.EventListener, + context?: Context, + once?: boolean + ): this; + off>( + event: T, + fn?: EventEmitter.EventListener, + context?: Context, + once?: boolean + ): this; + + /** + * Remove all listeners, or those of the specified event. + */ + removeAllListeners(event?: EventEmitter.EventNames): this; +} + +declare namespace EventEmitter { + export interface ListenerFn { + (...args: Args): void; + } + + export interface EventEmitterStatic { + new < + EventTypes extends ValidEventTypes = string | symbol, + Context = any + >(): EventEmitter; + } + + /** + * `object` should be in either of the following forms: + * ``` + * interface EventTypes { + * 'event-with-parameters': any[] + * 'event-with-example-handler': (...args: any[]) => void + * } + * ``` + */ + export type ValidEventTypes = string | symbol | object; + + export type EventNames = T extends string | symbol + ? T + : keyof T; + + export type ArgumentMap = { + [K in keyof T]: T[K] extends (...args: any[]) => void + ? Parameters + : T[K] extends any[] + ? T[K] + : any[]; + }; + + export type EventListener< + T extends ValidEventTypes, + K extends EventNames + > = T extends string | symbol + ? (...args: any[]) => void + : ( + ...args: ArgumentMap>[Extract] + ) => void; + + export type EventArgs< + T extends ValidEventTypes, + K extends EventNames + > = Parameters>; + + export const EventEmitter: EventEmitterStatic; +} + +export { EventEmitter } +export default EventEmitter; diff --git a/node_modules/eventemitter3/index.js b/node_modules/eventemitter3/index.js new file mode 100644 index 0000000..6ea485c --- /dev/null +++ b/node_modules/eventemitter3/index.js @@ -0,0 +1,336 @@ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ +function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + + return emitter; +} + +/** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ +function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ +EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; +}; + +/** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ +EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); +}; + +/** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); +}; + +/** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} diff --git a/node_modules/eventemitter3/index.mjs b/node_modules/eventemitter3/index.mjs new file mode 100644 index 0000000..89bb405 --- /dev/null +++ b/node_modules/eventemitter3/index.mjs @@ -0,0 +1,4 @@ +import EventEmitter from './index.js' + +export { EventEmitter } +export default EventEmitter diff --git a/node_modules/eventemitter3/package.json b/node_modules/eventemitter3/package.json new file mode 100644 index 0000000..29a040d --- /dev/null +++ b/node_modules/eventemitter3/package.json @@ -0,0 +1,62 @@ +{ + "name": "eventemitter3", + "version": "5.0.4", + "description": "EventEmitter3 focuses on performance while maintaining a Node.js AND browser compatible interface.", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./index.mjs", + "require": "./index.js" + }, + "./package.json": "./package.json" + }, + "main": "index.js", + "types": "index.d.ts", + "scripts": { + "rollup": "rm -rf dist && rollup -c", + "benchmark": "find benchmarks/run -name '*.js' -exec benchmarks/start.sh {} \\;", + "test": "c8 --reporter=lcov --reporter=text mocha test/test.js", + "test-esm": "mocha test/test.mjs", + "prepublishOnly": "npm run rollup" + }, + "files": [ + "index.js", + "index.mjs", + "index.d.ts", + "dist" + ], + "repository": { + "type": "git", + "url": "git://github.com/primus/eventemitter3.git" + }, + "keywords": [ + "EventEmitter", + "EventEmitter2", + "EventEmitter3", + "Events", + "addEventListener", + "addListener", + "emit", + "emits", + "emitter", + "event", + "once", + "pub/sub", + "publish", + "reactor", + "subscribe" + ], + "author": "Arnout Kazemier", + "license": "MIT", + "bugs": { + "url": "https://github.com/primus/eventemitter3/issues" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "^29.0.0", + "@rollup/plugin-terser": "^0.4.0", + "assume": "^2.2.0", + "c8": "^10.1.3", + "mocha": "^11.7.5", + "rollup": "^4.5.2" + } +} diff --git a/node_modules/fast-xml-builder/CHANGELOG.md b/node_modules/fast-xml-builder/CHANGELOG.md new file mode 100644 index 0000000..566bd12 --- /dev/null +++ b/node_modules/fast-xml-builder/CHANGELOG.md @@ -0,0 +1,16 @@ +**1.1.4** (2026-03-16) +- support maxNestedTags option + +**1.1.3** (2026-03-13) +- declare Matcher & Expression as unknown so user is not forced to install path-expression-matcher + +**1.1.2** (2026-03-11) +- fix typings + +**1.1.1** (2026-03-11) +- upgrade path-expression-matcher to 1.1.3 + +**1.1.0** (2026-03-10) + +- Integrate [path-expression-matcher](https://github.com/NaturalIntelligence/path-expression-matcher) + diff --git a/node_modules/fast-xml-builder/LICENSE b/node_modules/fast-xml-builder/LICENSE new file mode 100644 index 0000000..0311839 --- /dev/null +++ b/node_modules/fast-xml-builder/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Natural Intelligence + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/fast-xml-builder/README.md b/node_modules/fast-xml-builder/README.md new file mode 100644 index 0000000..fadf696 --- /dev/null +++ b/node_modules/fast-xml-builder/README.md @@ -0,0 +1,23 @@ +# fast-xml-builder +Build XML from JSON + + +XML Builder was the part of [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) for years. But considering that any bug in parser may false-alarm the users who are only using builder, we have decided to split it into a separate package. + +## Installation + +```bash +npm install fast-xml-builder +``` + +## Usage + +```javascript +import XMLBuilder from 'fast-xml-builder'; + +const builder = new XMLBuilder(); +const xml = builder.build({ name: 'value' }); +``` + +fast-xml-builder fully support the response generated by fast-xml-parser. So you can use the maximum options as you are using for fast-xml-parser like `preserveOrder`, `ignoreAttributes`, `attributeNamePrefix`, `textNodeName`, `cdataTagName`, `cdataPositionChar`, `format`, `indentBy`, `suppressEmptyNode` and many more. Any change in parser will reflect here time to time. + diff --git a/node_modules/fast-xml-builder/lib/fxb.cjs b/node_modules/fast-xml-builder/lib/fxb.cjs new file mode 100644 index 0000000..2a5cd86 --- /dev/null +++ b/node_modules/fast-xml-builder/lib/fxb.cjs @@ -0,0 +1 @@ +(()=>{"use strict";var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{default:()=>f});class i{constructor(t,e={}){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let i=0,s="";for(;i0&&(this.path[this.path.length-1].values=void 0);const s=this.path.length;this.siblingStacks[s]||(this.siblingStacks[s]=new Map);const n=this.siblingStacks[s],o=i?`${i}:${t}`:t,r=n.get(o)||0;let a=0;for(const t of n.values())a+=t;n.set(o,r+1);const h={tag:t,position:a,counter:r};null!=i&&(h.namespace=i),null!=e&&(h.values=e),this.path.push(h)}pop(){if(0===this.path.length)return;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0===this.path.length)return;const e=this.path[this.path.length-1];return e.values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const i=t||this.separator;return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i)}toArray(){return this.path.map(t=>t.tag)}reset(){this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e=0&&e>=0;){const s=t[i];if("deep-wildcard"===s.type){if(i--,i<0)return!0;const s=t[i];let n=!1;for(let t=e;t>=0;t--){const o=t===this.path.length-1;if(this._matchSegment(s,this.path[t],o)){e=t-1,i--,n=!0;break}}if(!n)return!1}else{const t=e===this.path.length-1;if(!this._matchSegment(s,this.path[e],t))return!1;e--,i--}}return i<0}_matchSegment(t,e,i){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!i)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue){const i=e.values[t.attrName];if(String(i)!==String(t.attrValue))return!1}}if(void 0!==t.position){if(!i)return!1;const s=e.counter??0;if("first"===t.position&&0!==s)return!1;if("odd"===t.position&&s%2!=1)return!1;if("even"===t.position&&s%2!=0)return!1;if("nth"===t.position&&s!==t.positionValue)return!1}return!0}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}}function n(t,e){let n="";e.format&&e.indentBy.length>0&&(n="\n");const r=[];if(e.stopNodes&&Array.isArray(e.stopNodes))for(let t=0;te.maxNestedTags)throw new Error("Maximum nested tags exceeded");if(!Array.isArray(t)){if(null!=t){let i=t.toString();return i=c(i,e),i}return""}for(let f=0;f`,d=!1,s.pop();continue}if(m===e.commentPropName){h+=i+`\x3c!--${g[m][0][e.textNodeName]}--\x3e`,d=!0,s.pop();continue}if("?"===m[0]){const t=u(g[":@"],e,N),n="?xml"===m?"":i;let o=g[m][0][e.textNodeName];o=0!==o.length?" "+o:"",h+=n+`<${m}${o}${t}?>`,d=!0,s.pop();continue}let y=i;""!==y&&(y+=e.indentBy);const x=i+`<${m}${u(g[":@"],e,N)}`;let P;P=N?a(g[m],e):o(g[m],e,y,s,n),-1!==e.unpairedTags.indexOf(m)?e.suppressUnpairedNode?h+=x+">":h+=x+"/>":P&&0!==P.length||!e.suppressEmptyNode?P&&P.endsWith(">")?h+=x+`>${P}${i}`:(h+=x+">",P&&""!==i&&(P.includes("/>")||P.includes("`):h+=x+"/>",d=!0,s.pop()}return h}function r(t,e){if(!t||e.ignoreAttributes)return null;const i={};let s=!1;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n.startsWith(e.attributeNamePrefix)?n.substr(e.attributeNamePrefix.length):n]=t[n],s=!0);return s?i:null}function a(t,e){if(!Array.isArray(t))return null!=t?t.toString():"";let i="";for(let s=0;s${s}`:i+=`<${o}${t}/>`}}}return i}function h(t,e){let i="";if(t&&!e.ignoreAttributes)for(let s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=t[s];!0===n&&e.suppressBooleanAttributes?i+=` ${s.substr(e.attributeNamePrefix.length)}`:i+=` ${s.substr(e.attributeNamePrefix.length)}="${n}"`}return i}function p(t){const e=Object.keys(t);for(let i=0;i0&&e.processEntities)for(let i=0;i","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1,maxNestedTags:100,jPath:!0};function f(t){if(this.options=Object.assign({},d,t),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(let t=0;t{for(const i of e){if("string"==typeof i&&t===i)return!0;if(i instanceof RegExp&&i.test(t))return!0}}:()=>!1,this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=b),this.processTextOrObjNode=g,this.options.format?(this.indentate=m,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function g(t,e,i,s){const n=this.extractAttributes(t);if(s.push(e,n),this.checkStopNode(s)){const n=this.buildRawContent(t),o=this.buildAttributesForStopNode(t);return s.pop(),this.buildObjectNode(n,e,o,i)}const o=this.j2x(t,i+1,s);return s.pop(),void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,o.attrStr,i,s):this.buildObjectNode(o.val,e,o.attrStr,i)}function m(t){return this.options.indentBy.repeat(t)}function b(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}f.prototype.build=function(t){if(this.options.preserveOrder)return n(t,this.options);{Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t});const e=new s;return this.j2x(t,0,e).val}},f.prototype.j2x=function(t,e,i){let s="",n="";if(this.options.maxNestedTags&&i.getDepth()>=this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");const o=this.options.jPath?i.toString():i,r=this.checkStopNode(i);for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a))if(void 0===t[a])this.isAttribute(a)&&(n+="");else if(null===t[a])this.isAttribute(a)||a===this.options.cdataPropName?n+="":"?"===a[0]?n+=this.indentate(e)+"<"+a+"?"+this.tagEndChar:n+=this.indentate(e)+"<"+a+"/"+this.tagEndChar;else if(t[a]instanceof Date)n+=this.buildTextValNode(t[a],a,"",e,i);else if("object"!=typeof t[a]){const h=this.isAttribute(a);if(h&&!this.ignoreAttributesFn(h,o))s+=this.buildAttrPairStr(h,""+t[a],r);else if(!h)if(a===this.options.textNodeName){let e=this.options.tagValueProcessor(a,""+t[a]);n+=this.replaceEntitiesValue(e)}else{i.push(a);const s=this.checkStopNode(i);if(i.pop(),s){const i=""+t[a];n+=""===i?this.indentate(e)+"<"+a+this.closeTag(a)+this.tagEndChar:this.indentate(e)+"<"+a+">"+i+""+t+"${t}`;else if("object"==typeof t&&null!==t){const s=this.buildRawContent(t),n=this.buildAttributesForStopNode(t);e+=""===s?`<${i}${n}/>`:`<${i}${n}>${s}`}}else if("object"==typeof s&&null!==s){const t=this.buildRawContent(s),n=this.buildAttributesForStopNode(s);e+=""===t?`<${i}${n}/>`:`<${i}${n}>${t}`}else e+=`<${i}>${s}`}return e},f.prototype.buildAttributesForStopNode=function(t){if(!t||"object"!=typeof t)return"";let e="";if(this.options.attributesGroupName&&t[this.options.attributesGroupName]){const i=t[this.options.attributesGroupName];for(let t in i){if(!Object.prototype.hasOwnProperty.call(i,t))continue;const s=t.startsWith(this.options.attributeNamePrefix)?t.substring(this.options.attributeNamePrefix.length):t,n=i[t];!0===n&&this.options.suppressBooleanAttributes?e+=" "+s:e+=" "+s+'="'+n+'"'}}else for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;const s=this.isAttribute(i);if(s){const n=t[i];!0===n&&this.options.suppressBooleanAttributes?e+=" "+s:e+=" "+s+'="'+n+'"'}}return e},f.prototype.buildObjectNode=function(t,e,i,s){if(""===t)return"?"===e[0]?this.indentate(s)+"<"+e+i+"?"+this.tagEndChar:this.indentate(s)+"<"+e+i+this.closeTag(e)+this.tagEndChar;{let n=""+t+n}},f.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(s)+`\x3c!--${t}--\x3e`+this.newLine;if("?"===e[0])return this.indentate(s)+"<"+e+i+"?"+this.tagEndChar;{let n=this.options.tagValueProcessor(e,t);return n=this.replaceEntitiesValue(n),""===n?this.indentate(s)+"<"+e+i+this.closeTag(e)+this.tagEndChar:this.indentate(s)+"<"+e+i+">"+n+"0&&this.options.processEntities)for(let e=0;e` - filters out attributes that match provided patterns + * + * When `Function` - calls the function for each attribute and filters out those for which the function returned `true` + * + * Defaults to `true` + */ + ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean); + + /** + * Give a property name to set CDATA values to instead of merging to tag's text value + * + * Defaults to `false` + */ + cdataPropName?: false | string; + + /** + * If set, parse comments and set as this property + * + * Defaults to `false` + */ + commentPropName?: false | string; + + /** + * Whether to make output pretty instead of single line + * + * Defaults to `false` + */ + format?: boolean; + + + /** + * If `format` is set to `true`, sets the indent string + * + * Defaults to ` ` + */ + indentBy?: string; + + /** + * Give a name to a top-level array + * + * Defaults to `undefined` + */ + arrayNodeName?: string; + + /** + * Create empty tags for tags with no text value + * + * Defaults to `false` + */ + suppressEmptyNode?: boolean; + + /** + * Suppress an unpaired tag + * + * Defaults to `true` + */ + suppressUnpairedNode?: boolean; + + /** + * Don't put a value for boolean attributes + * + * Defaults to `true` + */ + suppressBooleanAttributes?: boolean; + + /** + * Preserve the order of tags in resulting JS object + * + * Defaults to `false` + */ + preserveOrder?: boolean; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; + + /** + * Nodes to stop parsing at + * + * Accepts string patterns or Expression objects from path-expression-matcher + * + * String patterns starting with "*." are automatically converted to ".." for backward compatibility + * + * Defaults to `[]` + */ + stopNodes?: (string | Expression)[]; + + /** + * Control how tag value should be parsed. Called only if tag value is not empty + * + * @returns {undefined|null} `undefined` or `null` to set original value. + * @returns {unknown} + * + * 1. Different value or value with different data type to set new value. + * 2. Same value to set parsed value if `parseTagValue: true`. + * + * Defaults to `(tagName, val, jPath, hasAttributes, isLeafNode) => val` + */ + tagValueProcessor?: (name: string, value: unknown) => unknown; + + /** + * Control how attribute value should be parsed + * + * @param attrName + * @param attrValue + * @param jPath + * @returns {undefined|null} `undefined` or `null` to set original value + * @returns {unknown} + * + * Defaults to `(attrName, val, jPath) => val` + */ + attributeValueProcessor?: (name: string, value: unknown) => unknown; + + /** + * Whether to process default and DOCTYPE entities + * + * Defaults to `true` + */ + processEntities?: boolean; + + + oneListGroup?: boolean; + + /** + * Maximum number of nested tags + * + * Defaults to `100` + */ + maxNestedTags?: number; +}; + +interface XMLBuilder { + build(jObj: any): string; +} + +interface XMLBuilderConstructor { + new(options?: XmlBuilderOptions): XMLBuilder; + (options?: XmlBuilderOptions): XMLBuilder; +} + +declare const Builder: XMLBuilderConstructor; + +export = Builder; \ No newline at end of file diff --git a/node_modules/fast-xml-builder/lib/fxb.min.js b/node_modules/fast-xml-builder/lib/fxb.min.js new file mode 100644 index 0000000..3835a72 --- /dev/null +++ b/node_modules/fast-xml-builder/lib/fxb.min.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.fxb=e():t.fxb=e()}(this,()=>(()=>{"use strict";var t={d:(e,i)=>{for(var r in i)t.o(i,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:i[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{default:()=>b});class i{constructor(t,e={}){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let i=0,r="";for(;i0&&(this.path[this.path.length-1].values=void 0);const r=this.path.length;this.siblingStacks[r]||(this.siblingStacks[r]=new Map);const s=this.siblingStacks[r],n=i?`${i}:${t}`:t,o=s.get(n)||0;let a=0;for(const t of s.values())a+=t;s.set(n,o+1);const h={tag:t,position:a,counter:o};null!=i&&(h.namespace=i),null!=e&&(h.values=e),this.path.push(h)}pop(){if(0===this.path.length)return;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0===this.path.length)return;const e=this.path[this.path.length-1];return e.values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const i=t||this.separator;return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i)}toArray(){return this.path.map(t=>t.tag)}reset(){this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e=0&&e>=0;){const r=t[i];if("deep-wildcard"===r.type){if(i--,i<0)return!0;const r=t[i];let s=!1;for(let t=e;t>=0;t--){const n=t===this.path.length-1;if(this._matchSegment(r,this.path[t],n)){e=t-1,i--,s=!0;break}}if(!s)return!1}else{const t=e===this.path.length-1;if(!this._matchSegment(r,this.path[e],t))return!1;e--,i--}}return i<0}_matchSegment(t,e,i){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!i)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue){const i=e.values[t.attrName];if(String(i)!==String(t.attrValue))return!1}}if(void 0!==t.position){if(!i)return!1;const r=e.counter??0;if("first"===t.position&&0!==r)return!1;if("odd"===t.position&&r%2!=1)return!1;if("even"===t.position&&r%2!=0)return!1;if("nth"===t.position&&r!==t.positionValue)return!1}return!0}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}}function s(t,e){var s="";e.format&&e.indentBy.length>0&&(s="\n");var o=[];if(e.stopNodes&&Array.isArray(e.stopNodes))for(var a=0;ae.maxNestedTags)throw new Error("Maximum nested tags exceeded");if(!Array.isArray(t)){if(null!=t){var f=t.toString();return d(f,e)}return""}for(var g=0;g":h+=x+"/>":A&&0!==A.length||!e.suppressEmptyNode?A&&A.endsWith(">")?h+=x+">"+A+i+"":(h+=x+">",A&&""!==i&&(A.includes("/>")||A.includes(""):h+=x+"/>",c=!0,r.pop()}else{var S=u(m[":@"],e,N),P="?xml"===b?"":i,O=m[b][0][e.textNodeName];h+=P+"<"+b+(O=0!==O.length?" "+O:"")+S+"?>",c=!0,r.pop()}else h+=i+"\x3c!--"+m[b][0][e.textNodeName]+"--\x3e",c=!0,r.pop();else c&&(h+=i),h+="",c=!1,r.pop();else{var w=m[b];N||(w=d(w=e.tagValueProcessor(b,w),e)),c&&(h+=i),h+=w,c=!1,r.pop()}}}return h}function o(t,e){if(!t||e.ignoreAttributes)return null;var i={},r=!1;for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[s.startsWith(e.attributeNamePrefix)?s.substr(e.attributeNamePrefix.length):s]=t[s],r=!0);return r?i:null}function a(t,e){if(!Array.isArray(t))return null!=t?t.toString():"";for(var i="",r=0;r"+u+"":i+="<"+n+o+"/>"}}}return i}function h(t,e){var i="";if(t&&!e.ignoreAttributes)for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){var s=t[r];!0===s&&e.suppressBooleanAttributes?i+=" "+r.substr(e.attributeNamePrefix.length):i+=" "+r.substr(e.attributeNamePrefix.length)+'="'+s+'"'}return i}function p(t){for(var e=Object.keys(t),i=0;i0&&e.processEntities)for(var i=0;it.length)&&(e=t.length);for(var i=0,r=Array(e);i=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function g(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=Array(e);i","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1,maxNestedTags:100,jPath:!0};function b(t){if(this.options=Object.assign({},m,t),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map(function(t){return"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t})),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(var e=0;e=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(s);!(e=i()).done;){var r=e.value;if("string"==typeof r&&t===r)return!0;if(r instanceof RegExp&&r.test(t))return!0}}:function(){return!1},this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=y),this.processTextOrObjNode=v,this.options.format?(this.indentate=N,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function v(t,e,i,r){var s=this.extractAttributes(t);if(r.push(e,s),this.checkStopNode(r)){var n=this.buildRawContent(t),o=this.buildAttributesForStopNode(t);return r.pop(),this.buildObjectNode(n,e,o,i)}var a=this.j2x(t,i+1,r);return r.pop(),void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,a.attrStr,i,r):this.buildObjectNode(a.val,e,a.attrStr,i)}function N(t){return this.options.indentBy.repeat(t)}function y(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}return b.prototype.build=function(t){if(this.options.preserveOrder)return s(t,this.options);var e;Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&((e={})[this.options.arrayNodeName]=t,t=e);var i=new r;return this.j2x(t,0,i).val},b.prototype.j2x=function(t,e,i){var r="",s="";if(this.options.maxNestedTags&&i.getDepth()>=this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");var n=this.options.jPath?i.toString():i,o=this.checkStopNode(i);for(var a in t)if(Object.prototype.hasOwnProperty.call(t,a))if(void 0===t[a])this.isAttribute(a)&&(s+="");else if(null===t[a])this.isAttribute(a)||a===this.options.cdataPropName?s+="":"?"===a[0]?s+=this.indentate(e)+"<"+a+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+a+"/"+this.tagEndChar;else if(t[a]instanceof Date)s+=this.buildTextValNode(t[a],a,"",e,i);else if("object"!=typeof t[a]){var h=this.isAttribute(a);if(h&&!this.ignoreAttributesFn(h,n))r+=this.buildAttrPairStr(h,""+t[a],o);else if(!h)if(a===this.options.textNodeName){var p=this.options.tagValueProcessor(a,""+t[a]);s+=this.replaceEntitiesValue(p)}else{i.push(a);var u=this.checkStopNode(i);if(i.pop(),u){var l=""+t[a];s+=""===l?this.indentate(e)+"<"+a+this.closeTag(a)+this.tagEndChar:this.indentate(e)+"<"+a+">"+l+""+y+""+o+"";else if("object"==typeof o&&null!==o){var a=this.buildRawContent(o),h=this.buildAttributesForStopNode(o);e+=""===a?"<"+i+h+"/>":"<"+i+h+">"+a+""}}else if("object"==typeof r&&null!==r){var p=this.buildRawContent(r),u=this.buildAttributesForStopNode(r);e+=""===p?"<"+i+u+"/>":"<"+i+u+">"+p+""}else e+="<"+i+">"+r+""}return e},b.prototype.buildAttributesForStopNode=function(t){if(!t||"object"!=typeof t)return"";var e="";if(this.options.attributesGroupName&&t[this.options.attributesGroupName]){var i=t[this.options.attributesGroupName];for(var r in i)if(Object.prototype.hasOwnProperty.call(i,r)){var s=r.startsWith(this.options.attributeNamePrefix)?r.substring(this.options.attributeNamePrefix.length):r,n=i[r];!0===n&&this.options.suppressBooleanAttributes?e+=" "+s:e+=" "+s+'="'+n+'"'}}else for(var o in t)if(Object.prototype.hasOwnProperty.call(t,o)){var a=this.isAttribute(o);if(a){var h=t[o];!0===h&&this.options.suppressBooleanAttributes?e+=" "+a:e+=" "+a+'="'+h+'"'}}return e},b.prototype.buildObjectNode=function(t,e,i,r){if(""===t)return"?"===e[0]?this.indentate(r)+"<"+e+i+"?"+this.tagEndChar:this.indentate(r)+"<"+e+i+this.closeTag(e)+this.tagEndChar;var s=""+t+s},b.prototype.closeTag=function(t){var e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":">"+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(r)+"\x3c!--"+t+"--\x3e"+this.newLine;if("?"===e[0])return this.indentate(r)+"<"+e+i+"?"+this.tagEndChar;var n=this.options.tagValueProcessor(e,t);return""===(n=this.replaceEntitiesValue(n))?this.indentate(r)+"<"+e+i+this.closeTag(e)+this.tagEndChar:this.indentate(r)+"<"+e+i+">"+n+"0&&this.options.processEntities)for(var e=0;e {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Expression - Parses and stores a tag pattern expression\n * \n * Patterns are parsed once and stored in an optimized structure for fast matching.\n * \n * @example\n * const expr = new Expression(\"root.users.user\");\n * const expr2 = new Expression(\"..user[id]:first\");\n * const expr3 = new Expression(\"root/users/user\", { separator: '/' });\n */\nexport default class Expression {\n /**\n * Create a new Expression\n * @param {string} pattern - Pattern string (e.g., \"root.users.user\", \"..user[id]\")\n * @param {Object} options - Configuration options\n * @param {string} options.separator - Path separator (default: '.')\n */\n constructor(pattern, options = {}) {\n this.pattern = pattern;\n this.separator = options.separator || '.';\n this.segments = this._parse(pattern);\n\n // Cache expensive checks for performance (O(1) instead of O(n))\n this._hasDeepWildcard = this.segments.some(seg => seg.type === 'deep-wildcard');\n this._hasAttributeCondition = this.segments.some(seg => seg.attrName !== undefined);\n this._hasPositionSelector = this.segments.some(seg => seg.position !== undefined);\n }\n\n /**\n * Parse pattern string into segments\n * @private\n * @param {string} pattern - Pattern to parse\n * @returns {Array} Array of segment objects\n */\n _parse(pattern) {\n const segments = [];\n\n // Split by separator but handle \"..\" specially\n let i = 0;\n let currentPart = '';\n\n while (i < pattern.length) {\n if (pattern[i] === this.separator) {\n // Check if next char is also separator (deep wildcard)\n if (i + 1 < pattern.length && pattern[i + 1] === this.separator) {\n // Flush current part if any\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n currentPart = '';\n }\n // Add deep wildcard\n segments.push({ type: 'deep-wildcard' });\n i += 2; // Skip both separators\n } else {\n // Regular separator\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n currentPart = '';\n i++;\n }\n } else {\n currentPart += pattern[i];\n i++;\n }\n }\n\n // Flush remaining part\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n\n return segments;\n }\n\n /**\n * Parse a single segment\n * @private\n * @param {string} part - Segment string (e.g., \"user\", \"ns::user\", \"user[id]\", \"ns::user:first\")\n * @returns {Object} Segment object\n */\n _parseSegment(part) {\n const segment = { type: 'tag' };\n\n // NEW NAMESPACE SYNTAX (v2.0):\n // ============================\n // Namespace uses DOUBLE colon (::)\n // Position uses SINGLE colon (:)\n // \n // Examples:\n // \"user\" → tag\n // \"user:first\" → tag + position\n // \"user[id]\" → tag + attribute\n // \"user[id]:first\" → tag + attribute + position\n // \"ns::user\" → namespace + tag\n // \"ns::user:first\" → namespace + tag + position\n // \"ns::user[id]\" → namespace + tag + attribute\n // \"ns::user[id]:first\" → namespace + tag + attribute + position\n // \"ns::first\" → namespace + tag named \"first\" (NO ambiguity!)\n //\n // This eliminates all ambiguity:\n // :: = namespace separator\n // : = position selector\n // [] = attributes\n\n // Step 1: Extract brackets [attr] or [attr=value]\n let bracketContent = null;\n let withoutBrackets = part;\n\n const bracketMatch = part.match(/^([^\\[]+)(\\[[^\\]]*\\])(.*)$/);\n if (bracketMatch) {\n withoutBrackets = bracketMatch[1] + bracketMatch[3];\n if (bracketMatch[2]) {\n const content = bracketMatch[2].slice(1, -1);\n if (content) {\n bracketContent = content;\n }\n }\n }\n\n // Step 2: Check for namespace (double colon ::)\n let namespace = undefined;\n let tagAndPosition = withoutBrackets;\n\n if (withoutBrackets.includes('::')) {\n const nsIndex = withoutBrackets.indexOf('::');\n namespace = withoutBrackets.substring(0, nsIndex).trim();\n tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim(); // Skip ::\n\n if (!namespace) {\n throw new Error(`Invalid namespace in pattern: ${part}`);\n }\n }\n\n // Step 3: Parse tag and position (single colon :)\n let tag = undefined;\n let positionMatch = null;\n\n if (tagAndPosition.includes(':')) {\n const colonIndex = tagAndPosition.lastIndexOf(':'); // Use last colon for position\n const tagPart = tagAndPosition.substring(0, colonIndex).trim();\n const posPart = tagAndPosition.substring(colonIndex + 1).trim();\n\n // Verify position is a valid keyword\n const isPositionKeyword = ['first', 'last', 'odd', 'even'].includes(posPart) ||\n /^nth\\(\\d+\\)$/.test(posPart);\n\n if (isPositionKeyword) {\n tag = tagPart;\n positionMatch = posPart;\n } else {\n // Not a valid position keyword, treat whole thing as tag\n tag = tagAndPosition;\n }\n } else {\n tag = tagAndPosition;\n }\n\n if (!tag) {\n throw new Error(`Invalid segment pattern: ${part}`);\n }\n\n segment.tag = tag;\n if (namespace) {\n segment.namespace = namespace;\n }\n\n // Step 4: Parse attributes\n if (bracketContent) {\n if (bracketContent.includes('=')) {\n const eqIndex = bracketContent.indexOf('=');\n segment.attrName = bracketContent.substring(0, eqIndex).trim();\n segment.attrValue = bracketContent.substring(eqIndex + 1).trim();\n } else {\n segment.attrName = bracketContent.trim();\n }\n }\n\n // Step 5: Parse position selector\n if (positionMatch) {\n const nthMatch = positionMatch.match(/^nth\\((\\d+)\\)$/);\n if (nthMatch) {\n segment.position = 'nth';\n segment.positionValue = parseInt(nthMatch[1], 10);\n } else {\n segment.position = positionMatch;\n }\n }\n\n return segment;\n }\n\n /**\n * Get the number of segments\n * @returns {number}\n */\n get length() {\n return this.segments.length;\n }\n\n /**\n * Check if expression contains deep wildcard\n * @returns {boolean}\n */\n hasDeepWildcard() {\n return this._hasDeepWildcard;\n }\n\n /**\n * Check if expression has attribute conditions\n * @returns {boolean}\n */\n hasAttributeCondition() {\n return this._hasAttributeCondition;\n }\n\n /**\n * Check if expression has position selectors\n * @returns {boolean}\n */\n hasPositionSelector() {\n return this._hasPositionSelector;\n }\n\n /**\n * Get string representation\n * @returns {string}\n */\n toString() {\n return this.pattern;\n }\n}","/**\n * Matcher - Tracks current path in XML/JSON tree and matches against Expressions\n * \n * The matcher maintains a stack of nodes representing the current path from root to\n * current tag. It only stores attribute values for the current (top) node to minimize\n * memory usage. Sibling tracking is used to auto-calculate position and counter.\n * \n * @example\n * const matcher = new Matcher();\n * matcher.push(\"root\", {});\n * matcher.push(\"users\", {});\n * matcher.push(\"user\", { id: \"123\", type: \"admin\" });\n * \n * const expr = new Expression(\"root.users.user\");\n * matcher.matches(expr); // true\n */\nexport default class Matcher {\n /**\n * Create a new Matcher\n * @param {Object} options - Configuration options\n * @param {string} options.separator - Default path separator (default: '.')\n */\n constructor(options = {}) {\n this.separator = options.separator || '.';\n this.path = [];\n this.siblingStacks = [];\n // Each path node: { tag: string, values: object, position: number, counter: number }\n // values only present for current (last) node\n // Each siblingStacks entry: Map tracking occurrences at each level\n }\n\n /**\n * Push a new tag onto the path\n * @param {string} tagName - Name of the tag\n * @param {Object} attrValues - Attribute key-value pairs for current node (optional)\n * @param {string} namespace - Namespace for the tag (optional)\n */\n push(tagName, attrValues = null, namespace = null) {\n // Remove values from previous current node (now becoming ancestor)\n if (this.path.length > 0) {\n const prev = this.path[this.path.length - 1];\n prev.values = undefined;\n }\n\n // Get or create sibling tracking for current level\n const currentLevel = this.path.length;\n if (!this.siblingStacks[currentLevel]) {\n this.siblingStacks[currentLevel] = new Map();\n }\n\n const siblings = this.siblingStacks[currentLevel];\n\n // Create a unique key for sibling tracking that includes namespace\n const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;\n\n // Calculate counter (how many times this tag appeared at this level)\n const counter = siblings.get(siblingKey) || 0;\n\n // Calculate position (total children at this level so far)\n let position = 0;\n for (const count of siblings.values()) {\n position += count;\n }\n\n // Update sibling count for this tag\n siblings.set(siblingKey, counter + 1);\n\n // Create new node\n const node = {\n tag: tagName,\n position: position,\n counter: counter\n };\n\n // Store namespace if provided\n if (namespace !== null && namespace !== undefined) {\n node.namespace = namespace;\n }\n\n // Store values only for current node\n if (attrValues !== null && attrValues !== undefined) {\n node.values = attrValues;\n }\n\n this.path.push(node);\n }\n\n /**\n * Pop the last tag from the path\n * @returns {Object|undefined} The popped node\n */\n pop() {\n if (this.path.length === 0) {\n return undefined;\n }\n\n const node = this.path.pop();\n\n // Clean up sibling tracking for levels deeper than current\n // After pop, path.length is the new depth\n // We need to clean up siblingStacks[path.length + 1] and beyond\n if (this.siblingStacks.length > this.path.length + 1) {\n this.siblingStacks.length = this.path.length + 1;\n }\n\n return node;\n }\n\n /**\n * Update current node's attribute values\n * Useful when attributes are parsed after push\n * @param {Object} attrValues - Attribute values\n */\n updateCurrent(attrValues) {\n if (this.path.length > 0) {\n const current = this.path[this.path.length - 1];\n if (attrValues !== null && attrValues !== undefined) {\n current.values = attrValues;\n }\n }\n }\n\n /**\n * Get current tag name\n * @returns {string|undefined}\n */\n getCurrentTag() {\n return this.path.length > 0 ? this.path[this.path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n return this.path.length > 0 ? this.path[this.path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value\n * @param {string} attrName - Attribute name\n * @returns {*} Attribute value or undefined\n */\n getAttrValue(attrName) {\n if (this.path.length === 0) return undefined;\n const current = this.path[this.path.length - 1];\n return current.values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute\n * @param {string} attrName - Attribute name\n * @returns {boolean}\n */\n hasAttr(attrName) {\n if (this.path.length === 0) return false;\n const current = this.path[this.path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent)\n * @returns {number}\n */\n getPosition() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name)\n * @returns {number}\n */\n getCounter() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition for backward compatibility)\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth\n * @returns {number}\n */\n getDepth() {\n return this.path.length;\n }\n\n /**\n * Get path as string\n * @param {string} separator - Optional separator (uses default if not provided)\n * @param {boolean} includeNamespace - Whether to include namespace in output (default: true)\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n const sep = separator || this.separator;\n return this.path.map(n => {\n if (includeNamespace && n.namespace) {\n return `${n.namespace}:${n.tag}`;\n }\n return n.tag;\n }).join(sep);\n }\n\n /**\n * Get path as array of tag names\n * @returns {string[]}\n */\n toArray() {\n return this.path.map(n => n.tag);\n }\n\n /**\n * Reset the path to empty\n */\n reset() {\n this.path = [];\n this.siblingStacks = [];\n }\n\n /**\n * Match current path against an Expression\n * @param {Expression} expression - The expression to match against\n * @returns {boolean} True if current path matches the expression\n */\n matches(expression) {\n const segments = expression.segments;\n\n if (segments.length === 0) {\n return false;\n }\n\n // Handle deep wildcard patterns\n if (expression.hasDeepWildcard()) {\n return this._matchWithDeepWildcard(segments);\n }\n\n // Simple path matching (no deep wildcards)\n return this._matchSimple(segments);\n }\n\n /**\n * Match simple path (no deep wildcards)\n * @private\n */\n _matchSimple(segments) {\n // Path must be same length as segments\n if (this.path.length !== segments.length) {\n return false;\n }\n\n // Match each segment bottom-to-top\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n const node = this.path[i];\n const isCurrentNode = (i === this.path.length - 1);\n\n if (!this._matchSegment(segment, node, isCurrentNode)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Match path with deep wildcards\n * @private\n */\n _matchWithDeepWildcard(segments) {\n let pathIdx = this.path.length - 1; // Start from current node (bottom)\n let segIdx = segments.length - 1; // Start from last segment\n\n while (segIdx >= 0 && pathIdx >= 0) {\n const segment = segments[segIdx];\n\n if (segment.type === 'deep-wildcard') {\n // \"..\" matches zero or more levels\n segIdx--;\n\n if (segIdx < 0) {\n // Pattern ends with \"..\", always matches\n return true;\n }\n\n // Find where next segment matches in the path\n const nextSeg = segments[segIdx];\n let found = false;\n\n for (let i = pathIdx; i >= 0; i--) {\n const isCurrentNode = (i === this.path.length - 1);\n if (this._matchSegment(nextSeg, this.path[i], isCurrentNode)) {\n pathIdx = i - 1;\n segIdx--;\n found = true;\n break;\n }\n }\n\n if (!found) {\n return false;\n }\n } else {\n // Regular segment\n const isCurrentNode = (pathIdx === this.path.length - 1);\n if (!this._matchSegment(segment, this.path[pathIdx], isCurrentNode)) {\n return false;\n }\n pathIdx--;\n segIdx--;\n }\n }\n\n // All segments must be consumed\n return segIdx < 0;\n }\n\n /**\n * Match a single segment against a node\n * @private\n * @param {Object} segment - Segment from Expression\n * @param {Object} node - Node from path\n * @param {boolean} isCurrentNode - Whether this is the current (last) node\n * @returns {boolean}\n */\n _matchSegment(segment, node, isCurrentNode) {\n // Match tag name (* is wildcard)\n if (segment.tag !== '*' && segment.tag !== node.tag) {\n return false;\n }\n\n // Match namespace if specified in segment\n if (segment.namespace !== undefined) {\n // Segment has namespace - node must match it\n if (segment.namespace !== '*' && segment.namespace !== node.namespace) {\n return false;\n }\n }\n // If segment has no namespace, it matches nodes with or without namespace\n\n // Match attribute name (check if node has this attribute)\n // Can only check for current node since ancestors don't have values\n if (segment.attrName !== undefined) {\n if (!isCurrentNode) {\n // Can't check attributes for ancestor nodes (values not stored)\n return false;\n }\n\n if (!node.values || !(segment.attrName in node.values)) {\n return false;\n }\n\n // Match attribute value (only possible for current node)\n if (segment.attrValue !== undefined) {\n const actualValue = node.values[segment.attrName];\n // Both should be strings\n if (String(actualValue) !== String(segment.attrValue)) {\n return false;\n }\n }\n }\n\n // Match position (only for current node)\n if (segment.position !== undefined) {\n if (!isCurrentNode) {\n // Can't check position for ancestor nodes\n return false;\n }\n\n const counter = node.counter ?? 0;\n\n if (segment.position === 'first' && counter !== 0) {\n return false;\n } else if (segment.position === 'odd' && counter % 2 !== 1) {\n return false;\n } else if (segment.position === 'even' && counter % 2 !== 0) {\n return false;\n } else if (segment.position === 'nth') {\n if (counter !== segment.positionValue) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n /**\n * Create a snapshot of current state\n * @returns {Object} State snapshot\n */\n snapshot() {\n return {\n path: this.path.map(node => ({ ...node })),\n siblingStacks: this.siblingStacks.map(map => new Map(map))\n };\n }\n\n /**\n * Restore state from snapshot\n * @param {Object} snapshot - State snapshot\n */\n restore(snapshot) {\n this.path = snapshot.path.map(node => ({ ...node }));\n this.siblingStacks = snapshot.siblingStacks.map(map => new Map(map));\n }\n}","import { Expression, Matcher } from 'path-expression-matcher';\n\nconst EOL = \"\\n\";\n\n/**\n * \n * @param {array} jArray \n * @param {any} options \n * @returns \n */\nexport default function toXml(jArray, options) {\n let indentation = \"\";\n if (options.format && options.indentBy.length > 0) {\n indentation = EOL;\n }\n\n // Pre-compile stopNode expressions for pattern matching\n const stopNodeExpressions = [];\n if (options.stopNodes && Array.isArray(options.stopNodes)) {\n for (let i = 0; i < options.stopNodes.length; i++) {\n const node = options.stopNodes[i];\n if (typeof node === 'string') {\n stopNodeExpressions.push(new Expression(node));\n } else if (node instanceof Expression) {\n stopNodeExpressions.push(node);\n }\n }\n }\n\n // Initialize matcher for path tracking\n const matcher = new Matcher();\n\n return arrToStr(jArray, options, indentation, matcher, stopNodeExpressions);\n}\n\nfunction arrToStr(arr, options, indentation, matcher, stopNodeExpressions) {\n let xmlStr = \"\";\n let isPreviousElementTag = false;\n\n if (options.maxNestedTags && matcher.getDepth() > options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n\n if (!Array.isArray(arr)) {\n // Non-array values (e.g. string tag values) should be treated as text content\n if (arr !== undefined && arr !== null) {\n let text = arr.toString();\n text = replaceEntitiesValue(text, options);\n return text;\n }\n return \"\";\n }\n\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const tagName = propName(tagObj);\n if (tagName === undefined) continue;\n\n // Extract attributes from \":@\" property\n const attrValues = extractAttributeValues(tagObj[\":@\"], options);\n\n // Push tag to matcher WITH attributes\n matcher.push(tagName, attrValues);\n\n // Check if this is a stop node using Expression matching\n const isStopNode = checkStopNode(matcher, stopNodeExpressions);\n\n if (tagName === options.textNodeName) {\n let tagText = tagObj[tagName];\n if (!isStopNode) {\n tagText = options.tagValueProcessor(tagName, tagText);\n tagText = replaceEntitiesValue(tagText, options);\n }\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += tagText;\n isPreviousElementTag = false;\n matcher.pop();\n continue;\n } else if (tagName === options.cdataPropName) {\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += ``;\n isPreviousElementTag = false;\n matcher.pop();\n continue;\n } else if (tagName === options.commentPropName) {\n xmlStr += indentation + ``;\n isPreviousElementTag = true;\n matcher.pop();\n continue;\n } else if (tagName[0] === \"?\") {\n const attStr = attr_to_str(tagObj[\":@\"], options, isStopNode);\n const tempInd = tagName === \"?xml\" ? \"\" : indentation;\n let piTextNodeName = tagObj[tagName][0][options.textNodeName];\n piTextNodeName = piTextNodeName.length !== 0 ? \" \" + piTextNodeName : \"\"; //remove extra spacing\n xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;\n isPreviousElementTag = true;\n matcher.pop();\n continue;\n }\n\n let newIdentation = indentation;\n if (newIdentation !== \"\") {\n newIdentation += options.indentBy;\n }\n\n // Pass isStopNode to attr_to_str so attributes are also not processed for stopNodes\n const attStr = attr_to_str(tagObj[\":@\"], options, isStopNode);\n const tagStart = indentation + `<${tagName}${attStr}`;\n\n // If this is a stopNode, get raw content without processing\n let tagValue;\n if (isStopNode) {\n tagValue = getRawContent(tagObj[tagName], options);\n } else {\n\n tagValue = arrToStr(tagObj[tagName], options, newIdentation, matcher, stopNodeExpressions);\n }\n\n if (options.unpairedTags.indexOf(tagName) !== -1) {\n if (options.suppressUnpairedNode) xmlStr += tagStart + \">\";\n else xmlStr += tagStart + \"/>\";\n } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {\n xmlStr += tagStart + \"/>\";\n } else if (tagValue && tagValue.endsWith(\">\")) {\n xmlStr += tagStart + `>${tagValue}${indentation}`;\n } else {\n xmlStr += tagStart + \">\";\n if (tagValue && indentation !== \"\" && (tagValue.includes(\"/>\") || tagValue.includes(\"`;\n }\n isPreviousElementTag = true;\n\n // Pop tag from matcher\n matcher.pop();\n }\n\n return xmlStr;\n}\n\n/**\n * Extract attribute values from the \":@\" object and return as plain object\n * for passing to matcher.push()\n */\nfunction extractAttributeValues(attrMap, options) {\n if (!attrMap || options.ignoreAttributes) return null;\n\n const attrValues = {};\n let hasAttrs = false;\n\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n // Remove the attribute prefix to get clean attribute name\n const cleanAttrName = attr.startsWith(options.attributeNamePrefix)\n ? attr.substr(options.attributeNamePrefix.length)\n : attr;\n attrValues[cleanAttrName] = attrMap[attr];\n hasAttrs = true;\n }\n\n return hasAttrs ? attrValues : null;\n}\n\n/**\n * Extract raw content from a stopNode without any processing\n * This preserves the content exactly as-is, including special characters\n */\nfunction getRawContent(arr, options) {\n if (!Array.isArray(arr)) {\n // Non-array values return as-is\n if (arr !== undefined && arr !== null) {\n return arr.toString();\n }\n return \"\";\n }\n\n let content = \"\";\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n const tagName = propName(item);\n\n if (tagName === options.textNodeName) {\n // Raw text content - NO processing, NO entity replacement\n content += item[tagName];\n } else if (tagName === options.cdataPropName) {\n // CDATA content\n content += item[tagName][0][options.textNodeName];\n } else if (tagName === options.commentPropName) {\n // Comment content\n content += item[tagName][0][options.textNodeName];\n } else if (tagName && tagName[0] === \"?\") {\n // Processing instruction - skip for stopNodes\n continue;\n } else if (tagName) {\n // Nested tags within stopNode\n // Recursively get raw content and reconstruct the tag\n // For stopNodes, we don't process attributes either\n const attStr = attr_to_str_raw(item[\":@\"], options);\n const nestedContent = getRawContent(item[tagName], options);\n\n if (!nestedContent || nestedContent.length === 0) {\n content += `<${tagName}${attStr}/>`;\n } else {\n content += `<${tagName}${attStr}>${nestedContent}`;\n }\n }\n }\n return content;\n}\n\n/**\n * Build attribute string for stopNodes - NO entity replacement\n */\nfunction attr_to_str_raw(attrMap, options) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n // For stopNodes, use raw value without processing\n let attrVal = attrMap[attr];\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${attrVal}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n if (key !== \":@\") return key;\n }\n}\n\nfunction attr_to_str(attrMap, options, isStopNode) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n let attrVal;\n\n if (isStopNode) {\n // For stopNodes, use raw value without any processing\n attrVal = attrMap[attr];\n } else {\n // Normal processing: apply attributeValueProcessor and entity replacement\n attrVal = options.attributeValueProcessor(attr, attrMap[attr]);\n attrVal = replaceEntitiesValue(attrVal, options);\n }\n\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${attrVal}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction checkStopNode(matcher, stopNodeExpressions) {\n if (!stopNodeExpressions || stopNodeExpressions.length === 0) return false;\n\n for (let i = 0; i < stopNodeExpressions.length; i++) {\n if (matcher.matches(stopNodeExpressions[i])) {\n return true;\n }\n }\n return false;\n}\n\nfunction replaceEntitiesValue(textValue, options) {\n if (textValue && textValue.length > 0 && options.processEntities) {\n for (let i = 0; i < options.entities.length; i++) {\n const entity = options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}","'use strict';\n//parse Empty Node as self closing node\nimport buildFromOrderedJs from './orderedJs2Xml.js';\nimport getIgnoreAttributesFn from \"./ignoreAttributes.js\";\nimport { Expression, Matcher } from 'path-expression-matcher';\n\nconst defaultOptions = {\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n cdataPropName: false,\n format: false,\n indentBy: ' ',\n suppressEmptyNode: false,\n suppressUnpairedNode: true,\n suppressBooleanAttributes: true,\n tagValueProcessor: function (key, a) {\n return a;\n },\n attributeValueProcessor: function (attrName, a) {\n return a;\n },\n preserveOrder: false,\n commentPropName: false,\n unpairedTags: [],\n entities: [\n { regex: new RegExp(\"&\", \"g\"), val: \"&\" },//it must be on top\n { regex: new RegExp(\">\", \"g\"), val: \">\" },\n { regex: new RegExp(\"<\", \"g\"), val: \"<\" },\n { regex: new RegExp(\"\\'\", \"g\"), val: \"'\" },\n { regex: new RegExp(\"\\\"\", \"g\"), val: \""\" }\n ],\n processEntities: true,\n stopNodes: [],\n // transformTagName: false,\n // transformAttributeName: false,\n oneListGroup: false,\n maxNestedTags: 100,\n jPath: true // When true, callbacks receive string jPath; when false, receive Matcher instance\n};\n\nexport default function Builder(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n // Convert old-style stopNodes for backward compatibility\n // Old syntax: \"*.tag\" meant \"tag anywhere in tree\"\n // New syntax: \"..tag\" means \"tag anywhere in tree\"\n if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {\n this.options.stopNodes = this.options.stopNodes.map(node => {\n if (typeof node === 'string' && node.startsWith('*.')) {\n // Convert old wildcard syntax to deep wildcard\n return '..' + node.substring(2);\n }\n return node;\n });\n }\n\n // Pre-compile stopNode expressions for pattern matching\n this.stopNodeExpressions = [];\n if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {\n for (let i = 0; i < this.options.stopNodes.length; i++) {\n const node = this.options.stopNodes[i];\n if (typeof node === 'string') {\n this.stopNodeExpressions.push(new Expression(node));\n } else if (node instanceof Expression) {\n this.stopNodeExpressions.push(node);\n }\n }\n }\n\n if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {\n this.isAttribute = function (/*a*/) {\n return false;\n };\n } else {\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.attrPrefixLen = this.options.attributeNamePrefix.length;\n this.isAttribute = isAttribute;\n }\n\n this.processTextOrObjNode = processTextOrObjNode\n\n if (this.options.format) {\n this.indentate = indentate;\n this.tagEndChar = '>\\n';\n this.newLine = '\\n';\n } else {\n this.indentate = function () {\n return '';\n };\n this.tagEndChar = '>';\n this.newLine = '';\n }\n}\n\nBuilder.prototype.build = function (jObj) {\n if (this.options.preserveOrder) {\n return buildFromOrderedJs(jObj, this.options);\n } else {\n if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {\n jObj = {\n [this.options.arrayNodeName]: jObj\n }\n }\n // Initialize matcher for path tracking\n const matcher = new Matcher();\n return this.j2x(jObj, 0, matcher).val;\n }\n};\n\nBuilder.prototype.j2x = function (jObj, level, matcher) {\n let attrStr = '';\n let val = '';\n if (this.options.maxNestedTags && matcher.getDepth() >= this.options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n // Get jPath based on option: string for backward compatibility, or Matcher for new features\n const jPath = this.options.jPath ? matcher.toString() : matcher;\n\n // Check if current node is a stopNode (will be used for attribute encoding)\n const isCurrentStopNode = this.checkStopNode(matcher);\n\n for (let key in jObj) {\n if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;\n if (typeof jObj[key] === 'undefined') {\n // supress undefined node only if it is not an attribute\n if (this.isAttribute(key)) {\n val += '';\n }\n } else if (jObj[key] === null) {\n // null attribute should be ignored by the attribute list, but should not cause the tag closing\n if (this.isAttribute(key)) {\n val += '';\n } else if (key === this.options.cdataPropName) {\n val += '';\n } else if (key[0] === '?') {\n val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n }\n // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n } else if (jObj[key] instanceof Date) {\n val += this.buildTextValNode(jObj[key], key, '', level, matcher);\n } else if (typeof jObj[key] !== 'object') {\n //premitive type\n const attr = this.isAttribute(key);\n if (attr && !this.ignoreAttributesFn(attr, jPath)) {\n attrStr += this.buildAttrPairStr(attr, '' + jObj[key], isCurrentStopNode);\n } else if (!attr) {\n //tag value\n if (key === this.options.textNodeName) {\n let newval = this.options.tagValueProcessor(key, '' + jObj[key]);\n val += this.replaceEntitiesValue(newval);\n } else {\n // Check if this is a stopNode before building\n matcher.push(key);\n const isStopNode = this.checkStopNode(matcher);\n matcher.pop();\n\n if (isStopNode) {\n // Build as raw content without encoding\n const textValue = '' + jObj[key];\n if (textValue === '') {\n val += this.indentate(level) + '<' + key + this.closeTag(key) + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + key + '>' + textValue + '' + textValue + '${item}`;\n } else if (typeof item === 'object' && item !== null) {\n const nestedContent = this.buildRawContent(item);\n const nestedAttrs = this.buildAttributesForStopNode(item);\n if (nestedContent === '') {\n content += `<${key}${nestedAttrs}/>`;\n } else {\n content += `<${key}${nestedAttrs}>${nestedContent}`;\n }\n }\n }\n } else if (typeof value === 'object' && value !== null) {\n // Nested object\n const nestedContent = this.buildRawContent(value);\n const nestedAttrs = this.buildAttributesForStopNode(value);\n if (nestedContent === '') {\n content += `<${key}${nestedAttrs}/>`;\n } else {\n content += `<${key}${nestedAttrs}>${nestedContent}`;\n }\n } else {\n // Primitive value\n content += `<${key}>${value}`;\n }\n }\n\n return content;\n};\n\n// Build attribute string for stopNode (no entity encoding)\nBuilder.prototype.buildAttributesForStopNode = function (obj) {\n if (!obj || typeof obj !== 'object') return '';\n\n let attrStr = '';\n\n // Check for attributesGroupName (when attributes are grouped)\n if (this.options.attributesGroupName && obj[this.options.attributesGroupName]) {\n const attrGroup = obj[this.options.attributesGroupName];\n for (let attrKey in attrGroup) {\n if (!Object.prototype.hasOwnProperty.call(attrGroup, attrKey)) continue;\n const cleanKey = attrKey.startsWith(this.options.attributeNamePrefix)\n ? attrKey.substring(this.options.attributeNamePrefix.length)\n : attrKey;\n const val = attrGroup[attrKey];\n if (val === true && this.options.suppressBooleanAttributes) {\n attrStr += ' ' + cleanKey;\n } else {\n attrStr += ' ' + cleanKey + '=\"' + val + '\"'; // No encoding for stopNode\n }\n }\n } else {\n // Look for individual attributes\n for (let key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n const attr = this.isAttribute(key);\n if (attr) {\n const val = obj[key];\n if (val === true && this.options.suppressBooleanAttributes) {\n attrStr += ' ' + attr;\n } else {\n attrStr += ' ' + attr + '=\"' + val + '\"'; // No encoding for stopNode\n }\n }\n }\n }\n\n return attrStr;\n};\n\nBuilder.prototype.buildObjectNode = function (val, key, attrStr, level) {\n if (val === \"\") {\n if (key[0] === \"?\") return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n else {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n }\n } else {\n\n let tagEndExp = '' + val + tagEndExp);\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {\n return this.indentate(level) + `` + this.newLine;\n } else {\n return (\n this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +\n val +\n this.indentate(level) + tagEndExp);\n }\n }\n}\n\nBuilder.prototype.closeTag = function (key) {\n let closeTag = \"\";\n if (this.options.unpairedTags.indexOf(key) !== -1) { //unpaired\n if (!this.options.suppressUnpairedNode) closeTag = \"/\"\n } else if (this.options.suppressEmptyNode) { //empty\n closeTag = \"/\";\n } else {\n closeTag = `>` + this.newLine;\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName) {\n return this.indentate(level) + `` + this.newLine;\n } else if (key[0] === \"?\") {//PI tag\n return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n } else {\n // Normal processing: apply tagValueProcessor and entity replacement\n let textValue = this.options.tagValueProcessor(key, val);\n textValue = this.replaceEntitiesValue(textValue);\n\n if (textValue === '') {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n } else {\n return this.indentate(level) + '<' + key + attrStr + '>' +\n textValue +\n ' 0 && this.options.processEntities) {\n for (let i = 0; i < this.options.entities.length; i++) {\n const entity = this.options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}\n\nfunction indentate(level) {\n return this.options.indentBy.repeat(level);\n}\n\nfunction isAttribute(name /*, options*/) {\n if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {\n return name.substr(this.attrPrefixLen);\n } else {\n return false;\n }\n}","export default function getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}"],"names":["root","factory","exports","module","define","amd","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","Expression","constructor","pattern","options","separator","segments","_parse","_hasDeepWildcard","some","seg","type","_hasAttributeCondition","undefined","attrName","_hasPositionSelector","position","i","currentPart","length","trim","push","_parseSegment","part","segment","bracketContent","withoutBrackets","bracketMatch","match","content","slice","namespace","tag","tagAndPosition","includes","nsIndex","indexOf","substring","Error","positionMatch","colonIndex","lastIndexOf","tagPart","posPart","test","eqIndex","attrValue","nthMatch","positionValue","parseInt","hasDeepWildcard","hasAttributeCondition","hasPositionSelector","toString","Matcher","path","siblingStacks","tagName","attrValues","values","currentLevel","Map","siblings","siblingKey","counter","count","set","node","pop","updateCurrent","current","getCurrentTag","getCurrentNamespace","getAttrValue","hasAttr","getPosition","getCounter","getIndex","getDepth","includeNamespace","sep","map","n","join","toArray","reset","matches","expression","_matchWithDeepWildcard","_matchSimple","isCurrentNode","_matchSegment","pathIdx","segIdx","nextSeg","found","actualValue","String","snapshot","restore","toXml","jArray","indentation","format","indentBy","stopNodeExpressions","stopNodes","Array","isArray","arrToStr","arr","matcher","xmlStr","isPreviousElementTag","maxNestedTags","text","replaceEntitiesValue","tagObj","propName","extractAttributeValues","isStopNode","checkStopNode","textNodeName","cdataPropName","commentPropName","newIdentation","tagStart","attr_to_str","tagValue","getRawContent","unpairedTags","suppressUnpairedNode","suppressEmptyNode","endsWith","attStr","tempInd","piTextNodeName","tagText","tagValueProcessor","attrMap","ignoreAttributes","hasAttrs","attr","startsWith","attributeNamePrefix","substr","item","attr_to_str_raw","nestedContent","attrStr","attrVal","suppressBooleanAttributes","keys","attributeValueProcessor","textValue","processEntities","entities","entity","replace","regex","val","_createForOfIteratorHelperLoose","r","e","t","iterator","next","bind","a","_arrayLikeToArray","name","from","_unsupportedIterableToArray","done","TypeError","defaultOptions","attributesGroupName","preserveOrder","RegExp","oneListGroup","jPath","Builder","assign","isAttribute","ignoreAttributesFn","_step","_iterator","attrPrefixLen","processTextOrObjNode","indentate","tagEndChar","newLine","object","level","extractAttributes","rawContent","buildRawContent","buildAttributesForStopNode","buildObjectNode","result","j2x","buildTextValNode","repeat","build","jObj","buildFromOrderedJs","_jObj","arrayNodeName","isCurrentStopNode","Date","buildAttrPairStr","newval","closeTag","arrLen","listTagVal","listTagAttr","j","Ks","L","attrGroup","attrKey","nestedAttrs","cleanKey","tagEndExp","piClosingChar"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/fast-xml-builder/package.json b/node_modules/fast-xml-builder/package.json new file mode 100644 index 0000000..8eb9401 --- /dev/null +++ b/node_modules/fast-xml-builder/package.json @@ -0,0 +1,80 @@ +{ + "name": "fast-xml-builder", + "version": "1.1.5", + "description": "Build XML from JSON without C/C++ based libraries", + "main": "./lib/fxb.cjs", + "type": "module", + "sideEffects": false, + "module": "./src/fxb.js", + "types": "./src/fxb.d.ts", + "exports": { + ".": { + "import": { + "types": "./src/fxb.d.ts", + "default": "./src/fxb.js" + }, + "require": { + "types": "./lib/fxb.d.cts", + "default": "./lib/fxb.cjs" + } + } + }, + "scripts": { + "test": "c8 --reporter=lcov --reporter=text jasmine spec/*spec.js", + "test-types": "tsc --noEmit spec/typings/typings-test.ts", + "unit": "jasmine", + "lint": "eslint src/**/*.js spec/**/*.js benchmark/**/*.js", + "bundle": "webpack --config webpack.cjs.config.js", + "prettier": "prettier --write src/**/*.js", + "checkReadiness": "publish-please --dry-run", + "publish-please": "publish-please", + "prepublishOnly": "publish-please guard" + }, + "files": [ + "lib", + "src", + "CHANGELOG.md" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/NaturalIntelligence/fast-xml-builder.git" + }, + "keywords": [ + "xml", + "json", + "fast", + "builder", + "parser", + "js2xml", + "json2xml" + ], + "author": "Amit Gupta (https://solothought.com)", + "license": "MIT", + "devDependencies": { + "@babel/core": "^7.13.10", + "@babel/plugin-transform-runtime": "^7.13.10", + "@babel/preset-env": "^7.13.10", + "@babel/register": "^7.13.8", + "@types/node": "20", + "babel-loader": "^8.2.2", + "c8": "^10.1.3", + "eslint": "^8.3.0", + "fast-xml-parser": "^5.3.9", + "he": "^1.2.0", + "jasmine": "^5.6.0", + "prettier": "^3.5.1", + "publish-please": "^5.5.2", + "typescript": "5", + "webpack": "^5.64.4", + "webpack-cli": "^4.9.1" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "dependencies": { + "path-expression-matcher": "^1.1.3" + } +} \ No newline at end of file diff --git a/node_modules/fast-xml-builder/src/fxb.d.ts b/node_modules/fast-xml-builder/src/fxb.d.ts new file mode 100644 index 0000000..55c0bfa --- /dev/null +++ b/node_modules/fast-xml-builder/src/fxb.d.ts @@ -0,0 +1,180 @@ +// import { Expression } from 'path-expression-matcher'; + +type Matcher = unknown; +type Expression = unknown; + +export type XmlBuilderOptions = { + /** + * Give a prefix to the attribute name in the resulting JS object + * + * Defaults to '@_' + */ + attributeNamePrefix?: string; + + /** + * A name to group all attributes of a tag under, or `false` to disable + * + * Defaults to `false` + */ + attributesGroupName?: false | string; + + /** + * The name of the next node in the resulting JS + * + * Defaults to `#text` + */ + textNodeName?: string; + + /** + * Whether to ignore attributes when building + * + * When `true` - ignores all the attributes + * + * When `false` - builds all the attributes + * + * When `Array` - filters out attributes that match provided patterns + * + * When `Function` - calls the function for each attribute and filters out those for which the function returned `true` + * + * Defaults to `true` + */ + ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean); + + /** + * Give a property name to set CDATA values to instead of merging to tag's text value + * + * Defaults to `false` + */ + cdataPropName?: false | string; + + /** + * If set, parse comments and set as this property + * + * Defaults to `false` + */ + commentPropName?: false | string; + + /** + * Whether to make output pretty instead of single line + * + * Defaults to `false` + */ + format?: boolean; + + + /** + * If `format` is set to `true`, sets the indent string + * + * Defaults to ` ` + */ + indentBy?: string; + + /** + * Give a name to a top-level array + * + * Defaults to `undefined` + */ + arrayNodeName?: string; + + /** + * Create empty tags for tags with no text value + * + * Defaults to `false` + */ + suppressEmptyNode?: boolean; + + /** + * Suppress an unpaired tag + * + * Defaults to `true` + */ + suppressUnpairedNode?: boolean; + + /** + * Don't put a value for boolean attributes + * + * Defaults to `true` + */ + suppressBooleanAttributes?: boolean; + + /** + * Preserve the order of tags in resulting JS object + * + * Defaults to `false` + */ + preserveOrder?: boolean; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; + + /** + * Nodes to stop parsing at + * + * Accepts string patterns or Expression objects from path-expression-matcher + * + * String patterns starting with "*." are automatically converted to ".." for backward compatibility + * + * Defaults to `[]` + */ + stopNodes?: (string | Expression)[]; + + /** + * Control how tag value should be parsed. Called only if tag value is not empty + * + * @returns {undefined|null} `undefined` or `null` to set original value. + * @returns {unknown} + * + * 1. Different value or value with different data type to set new value. + * 2. Same value to set parsed value if `parseTagValue: true`. + * + * Defaults to `(tagName, val, jPath, hasAttributes, isLeafNode) => val` + */ + tagValueProcessor?: (name: string, value: unknown) => unknown; + + /** + * Control how attribute value should be parsed + * + * @param attrName + * @param attrValue + * @param jPath + * @returns {undefined|null} `undefined` or `null` to set original value + * @returns {unknown} + * + * Defaults to `(attrName, val, jPath) => val` + */ + attributeValueProcessor?: (name: string, value: unknown) => unknown; + + /** + * Whether to process default and DOCTYPE entities + * + * Defaults to `true` + */ + processEntities?: boolean; + + + oneListGroup?: boolean; + + /** + * Maximum number of nested tags + * + * Defaults to `100` + */ + maxNestedTags?: number; +}; + +export interface XMLBuilder { + build(jObj: any): string; +} + +export interface XMLBuilderConstructor { + new(options?: XmlBuilderOptions): XMLBuilder; + (options?: XmlBuilderOptions): XMLBuilder; +} + +declare const Builder: XMLBuilderConstructor; + +export default Builder; \ No newline at end of file diff --git a/node_modules/fast-xml-builder/src/fxb.js b/node_modules/fast-xml-builder/src/fxb.js new file mode 100644 index 0000000..7c14a5b --- /dev/null +++ b/node_modules/fast-xml-builder/src/fxb.js @@ -0,0 +1,533 @@ +'use strict'; +//parse Empty Node as self closing node +import buildFromOrderedJs from './orderedJs2Xml.js'; +import getIgnoreAttributesFn from "./ignoreAttributes.js"; +import { Expression, Matcher } from 'path-expression-matcher'; + +const defaultOptions = { + attributeNamePrefix: '@_', + attributesGroupName: false, + textNodeName: '#text', + ignoreAttributes: true, + cdataPropName: false, + format: false, + indentBy: ' ', + suppressEmptyNode: false, + suppressUnpairedNode: true, + suppressBooleanAttributes: true, + tagValueProcessor: function (key, a) { + return a; + }, + attributeValueProcessor: function (attrName, a) { + return a; + }, + preserveOrder: false, + commentPropName: false, + unpairedTags: [], + entities: [ + { regex: new RegExp("&", "g"), val: "&" },//it must be on top + { regex: new RegExp(">", "g"), val: ">" }, + { regex: new RegExp("<", "g"), val: "<" }, + { regex: new RegExp("\'", "g"), val: "'" }, + { regex: new RegExp("\"", "g"), val: """ } + ], + processEntities: true, + stopNodes: [], + // transformTagName: false, + // transformAttributeName: false, + oneListGroup: false, + maxNestedTags: 100, + jPath: true // When true, callbacks receive string jPath; when false, receive Matcher instance +}; + +export default function Builder(options) { + this.options = Object.assign({}, defaultOptions, options); + + // Convert old-style stopNodes for backward compatibility + // Old syntax: "*.tag" meant "tag anywhere in tree" + // New syntax: "..tag" means "tag anywhere in tree" + if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) { + this.options.stopNodes = this.options.stopNodes.map(node => { + if (typeof node === 'string' && node.startsWith('*.')) { + // Convert old wildcard syntax to deep wildcard + return '..' + node.substring(2); + } + return node; + }); + } + + // Pre-compile stopNode expressions for pattern matching + this.stopNodeExpressions = []; + if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) { + for (let i = 0; i < this.options.stopNodes.length; i++) { + const node = this.options.stopNodes[i]; + if (typeof node === 'string') { + this.stopNodeExpressions.push(new Expression(node)); + } else if (node instanceof Expression) { + this.stopNodeExpressions.push(node); + } + } + } + + if (this.options.ignoreAttributes === true || this.options.attributesGroupName) { + this.isAttribute = function (/*a*/) { + return false; + }; + } else { + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes) + this.attrPrefixLen = this.options.attributeNamePrefix.length; + this.isAttribute = isAttribute; + } + + this.processTextOrObjNode = processTextOrObjNode + + if (this.options.format) { + this.indentate = indentate; + this.tagEndChar = '>\n'; + this.newLine = '\n'; + } else { + this.indentate = function () { + return ''; + }; + this.tagEndChar = '>'; + this.newLine = ''; + } +} + +Builder.prototype.build = function (jObj) { + if (this.options.preserveOrder) { + return buildFromOrderedJs(jObj, this.options); + } else { + if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) { + jObj = { + [this.options.arrayNodeName]: jObj + } + } + // Initialize matcher for path tracking + const matcher = new Matcher(); + return this.j2x(jObj, 0, matcher).val; + } +}; + +Builder.prototype.j2x = function (jObj, level, matcher) { + let attrStr = ''; + let val = ''; + if (this.options.maxNestedTags && matcher.getDepth() >= this.options.maxNestedTags) { + throw new Error("Maximum nested tags exceeded"); + } + // Get jPath based on option: string for backward compatibility, or Matcher for new features + const jPath = this.options.jPath ? matcher.toString() : matcher; + + // Check if current node is a stopNode (will be used for attribute encoding) + const isCurrentStopNode = this.checkStopNode(matcher); + + for (let key in jObj) { + if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue; + if (typeof jObj[key] === 'undefined') { + // supress undefined node only if it is not an attribute + if (this.isAttribute(key)) { + val += ''; + } + } else if (jObj[key] === null) { + // null attribute should be ignored by the attribute list, but should not cause the tag closing + if (this.isAttribute(key)) { + val += ''; + } else if (key === this.options.cdataPropName) { + val += ''; + } else if (key[0] === '?') { + val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; + } else { + val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } + // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } else if (jObj[key] instanceof Date) { + val += this.buildTextValNode(jObj[key], key, '', level, matcher); + } else if (typeof jObj[key] !== 'object') { + //premitive type + const attr = this.isAttribute(key); + if (attr && !this.ignoreAttributesFn(attr, jPath)) { + attrStr += this.buildAttrPairStr(attr, '' + jObj[key], isCurrentStopNode); + } else if (!attr) { + //tag value + if (key === this.options.textNodeName) { + let newval = this.options.tagValueProcessor(key, '' + jObj[key]); + val += this.replaceEntitiesValue(newval); + } else { + // Check if this is a stopNode before building + matcher.push(key); + const isStopNode = this.checkStopNode(matcher); + matcher.pop(); + + if (isStopNode) { + // Build as raw content without encoding + const textValue = '' + jObj[key]; + if (textValue === '') { + val += this.indentate(level) + '<' + key + this.closeTag(key) + this.tagEndChar; + } else { + val += this.indentate(level) + '<' + key + '>' + textValue + '' + textValue + '${item}`; + } else if (typeof item === 'object' && item !== null) { + const nestedContent = this.buildRawContent(item); + const nestedAttrs = this.buildAttributesForStopNode(item); + if (nestedContent === '') { + content += `<${key}${nestedAttrs}/>`; + } else { + content += `<${key}${nestedAttrs}>${nestedContent}`; + } + } + } + } else if (typeof value === 'object' && value !== null) { + // Nested object + const nestedContent = this.buildRawContent(value); + const nestedAttrs = this.buildAttributesForStopNode(value); + if (nestedContent === '') { + content += `<${key}${nestedAttrs}/>`; + } else { + content += `<${key}${nestedAttrs}>${nestedContent}`; + } + } else { + // Primitive value + content += `<${key}>${value}`; + } + } + + return content; +}; + +// Build attribute string for stopNode (no entity encoding) +Builder.prototype.buildAttributesForStopNode = function (obj) { + if (!obj || typeof obj !== 'object') return ''; + + let attrStr = ''; + + // Check for attributesGroupName (when attributes are grouped) + if (this.options.attributesGroupName && obj[this.options.attributesGroupName]) { + const attrGroup = obj[this.options.attributesGroupName]; + for (let attrKey in attrGroup) { + if (!Object.prototype.hasOwnProperty.call(attrGroup, attrKey)) continue; + const cleanKey = attrKey.startsWith(this.options.attributeNamePrefix) + ? attrKey.substring(this.options.attributeNamePrefix.length) + : attrKey; + const val = attrGroup[attrKey]; + if (val === true && this.options.suppressBooleanAttributes) { + attrStr += ' ' + cleanKey; + } else { + attrStr += ' ' + cleanKey + '="' + val + '"'; // No encoding for stopNode + } + } + } else { + // Look for individual attributes + for (let key in obj) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; + const attr = this.isAttribute(key); + if (attr) { + const val = obj[key]; + if (val === true && this.options.suppressBooleanAttributes) { + attrStr += ' ' + attr; + } else { + attrStr += ' ' + attr + '="' + val + '"'; // No encoding for stopNode + } + } + } + } + + return attrStr; +}; + +Builder.prototype.buildObjectNode = function (val, key, attrStr, level) { + if (val === "") { + if (key[0] === "?") return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar; + else { + return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; + } + } else { + + let tagEndExp = '' + val + tagEndExp); + } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { + return this.indentate(level) + `` + this.newLine; + } else { + return ( + this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar + + val + + this.indentate(level) + tagEndExp); + } + } +} + +Builder.prototype.closeTag = function (key) { + let closeTag = ""; + if (this.options.unpairedTags.indexOf(key) !== -1) { //unpaired + if (!this.options.suppressUnpairedNode) closeTag = "/" + } else if (this.options.suppressEmptyNode) { //empty + closeTag = "/"; + } else { + closeTag = `>/g, ']]]]>'); + return this.indentate(level) + `` + this.newLine; + } else if (this.options.commentPropName !== false && key === this.options.commentPropName) { + const safeVal = String(val) + .replace(/--/g, '- -') // -- is illegal anywhere in comment content + .replace(/-$/, '- '); // trailing - would form -- with the closing --> + return this.indentate(level) + `` + this.newLine; + } else if (key[0] === "?") {//PI tag + return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar; + } else { + // Normal processing: apply tagValueProcessor and entity replacement + let textValue = this.options.tagValueProcessor(key, val); + textValue = this.replaceEntitiesValue(textValue); + + if (textValue === '') { + return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; + } else { + return this.indentate(level) + '<' + key + attrStr + '>' + + textValue + + ' 0 && this.options.processEntities) { + for (let i = 0; i < this.options.entities.length; i++) { + const entity = this.options.entities[i]; + textValue = textValue.replace(entity.regex, entity.val); + } + } + return textValue; +} + +function indentate(level) { + return this.options.indentBy.repeat(level); +} + +function isAttribute(name /*, options*/) { + if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) { + return name.substr(this.attrPrefixLen); + } else { + return false; + } +} \ No newline at end of file diff --git a/node_modules/fast-xml-builder/src/ignoreAttributes.js b/node_modules/fast-xml-builder/src/ignoreAttributes.js new file mode 100644 index 0000000..bdec0a6 --- /dev/null +++ b/node_modules/fast-xml-builder/src/ignoreAttributes.js @@ -0,0 +1,18 @@ +export default function getIgnoreAttributesFn(ignoreAttributes) { + if (typeof ignoreAttributes === 'function') { + return ignoreAttributes + } + if (Array.isArray(ignoreAttributes)) { + return (attrName) => { + for (const pattern of ignoreAttributes) { + if (typeof pattern === 'string' && attrName === pattern) { + return true + } + if (pattern instanceof RegExp && pattern.test(attrName)) { + return true + } + } + } + } + return () => false +} \ No newline at end of file diff --git a/node_modules/fast-xml-builder/src/orderedJs2Xml.js b/node_modules/fast-xml-builder/src/orderedJs2Xml.js new file mode 100644 index 0000000..638a029 --- /dev/null +++ b/node_modules/fast-xml-builder/src/orderedJs2Xml.js @@ -0,0 +1,306 @@ +import { Expression, Matcher } from 'path-expression-matcher'; + +const EOL = "\n"; + +/** + * + * @param {array} jArray + * @param {any} options + * @returns + */ +export default function toXml(jArray, options) { + let indentation = ""; + if (options.format && options.indentBy.length > 0) { + indentation = EOL; + } + + // Pre-compile stopNode expressions for pattern matching + const stopNodeExpressions = []; + if (options.stopNodes && Array.isArray(options.stopNodes)) { + for (let i = 0; i < options.stopNodes.length; i++) { + const node = options.stopNodes[i]; + if (typeof node === 'string') { + stopNodeExpressions.push(new Expression(node)); + } else if (node instanceof Expression) { + stopNodeExpressions.push(node); + } + } + } + + // Initialize matcher for path tracking + const matcher = new Matcher(); + + return arrToStr(jArray, options, indentation, matcher, stopNodeExpressions); +} + +function arrToStr(arr, options, indentation, matcher, stopNodeExpressions) { + let xmlStr = ""; + let isPreviousElementTag = false; + + if (options.maxNestedTags && matcher.getDepth() > options.maxNestedTags) { + throw new Error("Maximum nested tags exceeded"); + } + + if (!Array.isArray(arr)) { + // Non-array values (e.g. string tag values) should be treated as text content + if (arr !== undefined && arr !== null) { + let text = arr.toString(); + text = replaceEntitiesValue(text, options); + return text; + } + return ""; + } + + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const tagName = propName(tagObj); + if (tagName === undefined) continue; + + // Extract attributes from ":@" property + const attrValues = extractAttributeValues(tagObj[":@"], options); + + // Push tag to matcher WITH attributes + matcher.push(tagName, attrValues); + + // Check if this is a stop node using Expression matching + const isStopNode = checkStopNode(matcher, stopNodeExpressions); + + if (tagName === options.textNodeName) { + let tagText = tagObj[tagName]; + if (!isStopNode) { + tagText = options.tagValueProcessor(tagName, tagText); + tagText = replaceEntitiesValue(tagText, options); + } + if (isPreviousElementTag) { + xmlStr += indentation; + } + xmlStr += tagText; + isPreviousElementTag = false; + matcher.pop(); + continue; + } else if (tagName === options.cdataPropName) { + if (isPreviousElementTag) { + xmlStr += indentation; + } + const val = tagObj[tagName][0][options.textNodeName]; + const safeVal = String(val).replace(/\]\]>/g, ']]]]>'); + xmlStr += ``; + isPreviousElementTag = false; + matcher.pop(); + continue; + } else if (tagName === options.commentPropName) { + const val = tagObj[tagName][0][options.textNodeName] + const safeVal = String(val) + .replace(/--/g, '- -') // -- is illegal anywhere in comment content + .replace(/-$/, '- '); // trailing - would form -- with the closing --> + xmlStr += indentation + ``; + isPreviousElementTag = true; + matcher.pop(); + continue; + } else if (tagName[0] === "?") { + const attStr = attr_to_str(tagObj[":@"], options, isStopNode); + const tempInd = tagName === "?xml" ? "" : indentation; + let piTextNodeName = tagObj[tagName][0][options.textNodeName]; + piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing + xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`; + isPreviousElementTag = true; + matcher.pop(); + continue; + } + + let newIdentation = indentation; + if (newIdentation !== "") { + newIdentation += options.indentBy; + } + + // Pass isStopNode to attr_to_str so attributes are also not processed for stopNodes + const attStr = attr_to_str(tagObj[":@"], options, isStopNode); + const tagStart = indentation + `<${tagName}${attStr}`; + + // If this is a stopNode, get raw content without processing + let tagValue; + if (isStopNode) { + tagValue = getRawContent(tagObj[tagName], options); + } else { + + tagValue = arrToStr(tagObj[tagName], options, newIdentation, matcher, stopNodeExpressions); + } + + if (options.unpairedTags.indexOf(tagName) !== -1) { + if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; + else xmlStr += tagStart + "/>"; + } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { + xmlStr += tagStart + "/>"; + } else if (tagValue && tagValue.endsWith(">")) { + xmlStr += tagStart + `>${tagValue}${indentation}`; + } else { + xmlStr += tagStart + ">"; + if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; + } + isPreviousElementTag = true; + + // Pop tag from matcher + matcher.pop(); + } + + return xmlStr; +} + +/** + * Extract attribute values from the ":@" object and return as plain object + * for passing to matcher.push() + */ +function extractAttributeValues(attrMap, options) { + if (!attrMap || options.ignoreAttributes) return null; + + const attrValues = {}; + let hasAttrs = false; + + for (let attr in attrMap) { + if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue; + // Remove the attribute prefix to get clean attribute name + const cleanAttrName = attr.startsWith(options.attributeNamePrefix) + ? attr.substr(options.attributeNamePrefix.length) + : attr; + attrValues[cleanAttrName] = attrMap[attr]; + hasAttrs = true; + } + + return hasAttrs ? attrValues : null; +} + +/** + * Extract raw content from a stopNode without any processing + * This preserves the content exactly as-is, including special characters + */ +function getRawContent(arr, options) { + if (!Array.isArray(arr)) { + // Non-array values return as-is + if (arr !== undefined && arr !== null) { + return arr.toString(); + } + return ""; + } + + let content = ""; + for (let i = 0; i < arr.length; i++) { + const item = arr[i]; + const tagName = propName(item); + + if (tagName === options.textNodeName) { + // Raw text content - NO processing, NO entity replacement + content += item[tagName]; + } else if (tagName === options.cdataPropName) { + // CDATA content + content += item[tagName][0][options.textNodeName]; + } else if (tagName === options.commentPropName) { + // Comment content + content += item[tagName][0][options.textNodeName]; + } else if (tagName && tagName[0] === "?") { + // Processing instruction - skip for stopNodes + continue; + } else if (tagName) { + // Nested tags within stopNode + // Recursively get raw content and reconstruct the tag + // For stopNodes, we don't process attributes either + const attStr = attr_to_str_raw(item[":@"], options); + const nestedContent = getRawContent(item[tagName], options); + + if (!nestedContent || nestedContent.length === 0) { + content += `<${tagName}${attStr}/>`; + } else { + content += `<${tagName}${attStr}>${nestedContent}`; + } + } + } + return content; +} + +/** + * Build attribute string for stopNodes - NO entity replacement + */ +function attr_to_str_raw(attrMap, options) { + let attrStr = ""; + if (attrMap && !options.ignoreAttributes) { + for (let attr in attrMap) { + if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue; + // For stopNodes, use raw value without processing + let attrVal = attrMap[attr]; + if (attrVal === true && options.suppressBooleanAttributes) { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; + } else { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; + } + } + } + return attrStr; +} + +function propName(obj) { + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; + if (key !== ":@") return key; + } +} + +function attr_to_str(attrMap, options, isStopNode) { + let attrStr = ""; + if (attrMap && !options.ignoreAttributes) { + for (let attr in attrMap) { + if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue; + let attrVal; + + if (isStopNode) { + // For stopNodes, use raw value without any processing + attrVal = attrMap[attr]; + } else { + // Normal processing: apply attributeValueProcessor and entity replacement + attrVal = options.attributeValueProcessor(attr, attrMap[attr]); + attrVal = replaceEntitiesValue(attrVal, options); + } + + if (attrVal === true && options.suppressBooleanAttributes) { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; + } else { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; + } + } + } + return attrStr; +} + +function checkStopNode(matcher, stopNodeExpressions) { + if (!stopNodeExpressions || stopNodeExpressions.length === 0) return false; + + for (let i = 0; i < stopNodeExpressions.length; i++) { + if (matcher.matches(stopNodeExpressions[i])) { + return true; + } + } + return false; +} + +function replaceEntitiesValue(textValue, options) { + if (textValue && textValue.length > 0 && options.processEntities) { + for (let i = 0; i < options.entities.length; i++) { + const entity = options.entities[i]; + textValue = textValue.replace(entity.regex, entity.val); + } + } + return textValue; +} + +function cdataVal(val) { + +} + +function commentVal(val) { + +} \ No newline at end of file diff --git a/node_modules/fast-xml-builder/src/prettifyJs2Xml.js b/node_modules/fast-xml-builder/src/prettifyJs2Xml.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/fast-xml-parser/CHANGELOG.md b/node_modules/fast-xml-parser/CHANGELOG.md new file mode 100644 index 0000000..926231f --- /dev/null +++ b/node_modules/fast-xml-parser/CHANGELOG.md @@ -0,0 +1,812 @@ +Note: If you find missing information about particular minor version, that version must have been changed without any functional change in this library. + +Note: Due to some last quick changes on v4, detail of v4.5.3 & v4.5.4 are not updated here. v4.5.4x is the last tag of v4 in github repository. I'm extremely sorry for the confusion + +**5.7.0 / 2026-04-17** +- Use `@nodable/entities` v2.1.0 + - breaking changes + - single entity scan. You're not allowed to user entity value to form another entity name. + - you cant add numeric external entity + - entity error message when expantion limit is crossed might change + - typings are updated for new options related to process entity + - please follow documentation of `@nodable/entities` for more detail. + - performance + - if processEntities is false, then there should not be impact on performance. + - if processEntities is true, but you dont pass entity decoder separately then performance may degrade by approx 8-10% + - if processEntities is true, and you pass entity decoder separately + - if no entity then performance should be same as before + - if there are entities then performance should be increased from past versions + - ignoreAttributes is not required to be set to set xml version for NCR entity value +- update 'fast-xml-builder' to sanitize malicious CDATA and comment's content + +**5.6.0 / 2026-04-15** +- fix: entity replacement for numeric entities +- use @nodable/entities to replace entities + - this may change some error messages related to entities expansion limit or inavlid use + - post check would be exposed in future version + +**5.5.12 / 2026-04-13** +- Performance Improvement: update path-expression-matcher + - use proxy pattern than Proxy class + +**5.5.11 / 2026-04-08** +- Performance Improvement + - integrate ExpressionSet for stopNodes + +**5.5.10 / 2026-04-03** +- increase default entity explansion limit as many projects demand for that +- performance improvement + - reduce calls to toString + - early return when entities are not present + - prepare rawAttrsForMatcher only if user sets `jPath: false` + +**5.5.9 / 2026-03-23** +- combine typing files + + +**4.5.5 / 2026-03-22** + +apply fixes from v5 (legacy maintenance branch v4-maintenance) + +- support maxEntityCount +- support onDangerousProperty +- support maxNestedTags +- handle prototype pollution +- fix incorrect entity name replacement +- fix incorrect condition for entity expansion + +**5.5.8 / 2026-03-20** +- pass read only matcher in callback + +**5.5.7 / 2026-03-19** +- fix: entity expansion limits +- update strnum package to 2.2.0 + +**5.5.6 / 2026-03-16** +- update builder dependency +- fix incorrect regex to replace \. in entity name +- fix check for entitiy expansion for lastEntities and html entities too + +**5.5.5 / 2026-03-13** +- sanitize dangerous tag or attribute name +- error on critical property name +- support onDangerousProperty option + +**5.5.4 / 2026-03-13** +- declare Matcher & Expression as unknown so user is not forced to install path-expression-matcher + + +**5.5.3 / 2026-03-11** +- upgrade builder + +**5.5.2 / 2026-03-11** +- update dependency to fix typings + +**5.5.1 / 2026-03-10** +- fix dependency + +**5.5.0 / 2026-03-10** +- support path-expression-matcher +- fix: stopNode should not be parsed +- performance improvement for stopNode checking + +**5.4.2 / 2026-03-03** +- support maxEntityCount option + +**5.4.1 / 2026-02-25** +- fix (#785) unpairedTag node should not have tag content + +**5.4.0 / 2026-02-25** +- migrate to fast-xml-builder + +**5.3.9 / 2026-02-25** +- support strictReservedNames + +**5.3.8 / 2026-02-25** +- support maxNestedTags +- handle non-array input for XML builder when preserveOrder is true (By [Angelo Coetzee](https://github.com/Angelopvtac)) +- save use of js properies + +**5.3.7 / 2026-02-20** +- fix typings for CJS (By [Corentin Girard](https://github.com/Drarig29)) + + + +**5.3.6 / 2026-02-14** +- Improve security and performance of entity processing + - new options `maxEntitySize`, `maxExpansionDepth`, `maxTotalExpansions`, `maxExpandedLength`, `allowedTags`,`tagFilter` + - fast return when no edtity is present + - improvement replacement logic to reduce number of calls + + +**5.3.5 / 2026-02-08** +- fix: Escape regex char in entity name +- update strnum to 2.1.2 +- add missing exports in CJS typings + + +**5.3.4 / 2026-01-30** +- fix: handle HTML numeric and hex entities when out of range + + +**5.3.3 / 2025-12-12** +- fix #775: transformTagName with allowBooleanAttributes adds an unnecessary attribute + +**5.3.2 / 2025-11-14** +- fix for import statement for v6 + +**5.3.1 / 2025-11-03** +- Performance improvement for stopNodes (By [Maciek Lamberski](https://github.com/macieklamberski)) + +**5.3.0 / 2025-10-03** +- Use `Uint8Array` in place of `Buffer` in Parser + +**5.2.5 / 2025-06-08** +- Inform user to use [fxp-cli](https://github.com/NaturalIntelligence/fxp-cli) instead of in-built CLI feature +- Export typings for direct use + +**5.2.4 / 2025-06-06** +- fix (#747): fix EMPTY and ANY with ELEMENT in DOCTYPE + +**5.2.3 / 2025-05-11** +- fix (#747): support EMPTY and ANY with ELEMENT in DOCTYPE + +**5.2.2 / 2025-05-05** +- fix (#746): update strnum to fix parsing issues related to enotations + +**5.2.1 / 2025-04-22** +- fix: read DOCTYPE entity value correctly +- read DOCTYPE NOTATION, ELEMENT exp but not using read values + + +**5.2.0 / 2025-04-03** +- feat: support metadata on nodes (#593) (By [Steven R. Loomis](https://github.com/srl295)) + +**5.1.0 / 2025-04-02** +- feat: declare package as side-effect free (#738) (By [Thomas Bouffard](https://github.com/tbouffard)) +- fix cjs build mode +- fix builder return type to string +- + +**5.0.9 / 2025-03-14** +- fix: support numeric entities with values over 0xFFFF (#726) (By [Marc Durdin](https://github.com/mcdurdin)) +- fix: update strnum to fix parsing 0 if skiplike option is used + +**5.0.8 / 2025-02-27** +- fix parsing 0 if skiplike option is used. + - updating strnum dependency + +**5.0.7 / 2025-02-25** +- fix (#724) typings for cjs. + +**5.0.6 / 2025-02-20** +- fix cli output (By [Angel Delgado](https://github.com/angeld7)) + - remove multiple JSON parsing + +**5.0.5 / 2025-02-20** +- fix parsing of string starting with 'e' or 'E' by updating strnum + +**5.0.4 / 2025-02-20** +- fix CLI to support all the versions of node js when displaying library version. +- fix CJS import in v5 + - by fixing webpack config + +**5.0.3 / 2025-02-20** +- Using strnum ESM module + - new fixes in strum may break your experience + +**5.0.2 / 2025-02-20** +- fix: include CommonJS resources in the npm package #714 (By [Thomas Bouffard](https://github.com/tbouffard)) +- fix: move babel deps to dev deps + +**5.0.1 / 2025-02-19** +- fix syntax error for CLI command + +**5.0.0 / 2025-02-19** +- ESM support + - no change in the functionality, syntax, APIs, options, or documentation. + +**4.5.2 / 2025-02-18** +- Fix null CDATA to comply with undefined behavior (#701) (By [Matthieu BOHEAS](https://github.com/Kelgors)) +- Fix(performance): Update check for leaf node in saveTextToParentTag function in OrderedObjParser.js (#707) (By [...](https://github.com/tomingtoming)) +- Fix: emit full JSON string from CLI when no output filename specified (#710) (By [Matt Benson](https://github.com/mbenson)) + +**4.5.1 / 2024-12-15** +- Fix empty tag key name for v5 (#697). no impact on v4 +- Fixes entity parsing when used in strict mode (#699) + +**4.5.0 / 2024-09-03** +- feat #666: ignoreAttributes support function, and array of string or regex (By [ArtemM](https://github.com/mav-rik)) + +**4.4.1 / 2024-07-28** +- v5 fix: maximum length limit to currency value +- fix #634: build attributes with oneListGroup and attributesGroupName (#653)(By [Andreas Naziris](https://github.com/a-rasin)) +- fix: get oneListGroup to work as expected for array of strings (#662)(By [Andreas Naziris](https://github.com/a-rasin)) + +**4.4.0 / 2024-05-18** +- fix #654: parse attribute list correctly for self closing stop node. +- fix: validator bug when closing tag is not opened. (#647) (By [Ryosuke Fukatani](https://github.com/RyosukeFukatani)) +- fix #581: typings; return type of `tagValueProcessor` & `attributeValueProcessor` (#582) (By [monholm]()) + +**4.3.6 / 2024-03-16** +- Add support for parsing HTML numeric entities (#645) (By [Jonas Schade ](https://github.com/DerZade)) + +**4.3.5 / 2024-02-24** +- code for v5 is added for experimental use + +**4.3.4 / 2024-01-10** +- fix: Don't escape entities in CDATA sections (#633) (By [wackbyte](https://github.com/wackbyte)) + +**4.3.3 / 2024-01-10** +- Remove unnecessary regex + +**4.3.2 / 2023-10-02** +- fix `jObj.hasOwnProperty` when give input is null (By [Arda TANRIKULU](https://github.com/ardatan)) + +**4.3.1 / 2023-09-24** +- revert back "Fix typings for builder and parser to make return type generic" to avoid failure of existing projects. Need to decide a common approach. + +**4.3.0 / 2023-09-20** +- Fix stopNodes to work with removeNSPrefix (#607) (#608) (By [Craig Andrews]https://github.com/candrews)) +- Fix #610 ignore properties set to Object.prototype +- Fix typings for builder and parser to make return type generic (By [Sarah Dayan](https://github.com/sarahdayan)) + +**4.2.7 / 2023-07-30** +- Fix: builder should set text node correctly when only textnode is present (#589) (By [qianqing](https://github.com/joneqian)) +- Fix: Fix for null and undefined attributes when building xml (#585) (#598). A null or undefined value should be ignored. (By [Eugenio Ceschia](https://github.com/cecia234)) + +**4.2.6 / 2023-07-17** +- Fix: Remove trailing slash from jPath for self-closing tags (#595) (By [Maciej Radzikowski](https://github.com/m-radzikowski)) + +**4.2.5 / 2023-06-22** +- change code implementation + +**4.2.4 / 2023-06-06** +- fix security bug + +**4.2.3 / 2023-06-05** +- fix security bug + +**4.2.2 / 2023-04-18** +- fix #562: fix unpaired tag when it comes in last of a nested tag. Also throw error when unpaired tag is used as closing tag + +**4.2.1 / 2023-04-18** +- fix: jpath after unpaired tags + +**4.2.0 / 2023-04-09** +- support `updateTag` parser property + +**4.1.4 / 2023-04-08** +- update typings to let user create XMLBuilder instance without options (#556) (By [Patrick](https://github.com/omggga)) +- fix: IsArray option isn't parsing tags with 0 as value correctly #490 (#557) (By [Aleksandr Murashkin](https://github.com/p-kuen)) +- feature: support `oneListGroup` to group repeated children tags udder single group + +**4.1.3 / 2023-02-26** +- fix #546: Support complex entity value + +**4.1.2 / 2023-02-12** +- Security Fix + +**4.1.1 / 2023-02-03** +- Fix #540: ignoreAttributes breaks unpairedTags +- Refactor XML builder code + +**4.1.0 / 2023-02-02** +- Fix '<' or '>' in DTD comment throwing an error. (#533) (By [Adam Baker](https://github.com/Cwazywierdo)) +- Set "eNotation" to 'true' as default + +**4.0.15 / 2023-01-25** +- make "eNotation" optional + +**4.0.14 / 2023-01-22** +- fixed: add missed typing "eNotation" to parse values + +**4.0.13 / 2023-01-07** +- preserveorder formatting (By [mdeknowis](https://github.com/mdeknowis)) +- support `transformAttributeName` (By [Erik Rothoff Andersson](https://github.com/erkie)) + +**4.0.12 / 2022-11-19** +- fix typescript + +**4.0.11 / 2022-10-05** +- fix #501: parse for entities only once + +**4.0.10 / 2022-09-14** +- fix broken links in demo site (By [Yannick Lang](https://github.com/layaxx)) +- fix #491: tagValueProcessor type definition (By [Andrea Francesco Speziale](https://github.com/andreafspeziale)) +- Add jsdocs for tagValueProcessor + + +**4.0.9 / 2022-07-10** +- fix #470: stop-tag can have self-closing tag with same name +- fix #472: stopNode can have any special tag inside +- Allow !ATTLIST and !NOTATION with DOCTYPE +- Add transformTagName option to transform tag names when parsing (#469) (By [Erik Rothoff Andersson](https://github.com/erkie)) + +**4.0.8 / 2022-05-28** +- Fix CDATA parsing returning empty string when value = 0 (#451) (By [ndelanou](https://github.com/ndelanou)) +- Fix stopNodes when same tag appears inside node (#456) (By [patrickshipe](https://github.com/patrickshipe)) +- fix #468: prettify own properties only + +**4.0.7 / 2022-03-18** +- support CDATA even if tag order is not preserved +- support Comments even if tag order is not preserved +- fix #446: XMLbuilder should not indent XML declaration + +**4.0.6 / 2022-03-08** +- fix: call tagValueProcessor only once for array items +- fix: missing changed for #437 + +**4.0.5 / 2022-03-06** +- fix #437: call tagValueProcessor from XML builder + +**4.0.4 / 2022-03-03** +- fix #435: should skip unpaired and self-closing nodes when set as stopnodes + +**4.0.3 / 2022-02-15** +- fix: ReferenceError when Bundled with Strict (#431) (By [Andreas Heissenberger](https://github.com/aheissenberger)) + + +**4.0.2 / 2022-02-04** +- builder supports `suppressUnpairedNode` +- parser supports `ignoreDeclaration` and `ignorePiTags` +- fix: when comment is parsed as text value if given as ` ...` #423 +- builder supports decoding `&` + +**4.0.1 / 2022-01-08** +- fix builder for pi tag +- fix: support suppressBooleanAttrs by builder + +**4.0.0 / 2022-01-06** +- Generating different combined, parser only, builder only, validator only browser bundles +- Keeping cjs modules as they can be imported in cjs and esm modules both. Otherwise refer `esm` branch. + +**4.0.0-beta.8 / 2021-12-13** +- call tagValueProcessor for stop nodes + +**4.0.0-beta.7 / 2021-12-09** +- fix Validator bug when an attribute has no value but '=' only +- XML Builder should suppress unpaired tags by default. +- documents update for missing features +- refactoring to use Object.assign +- refactoring to remove repeated code + +**4.0.0-beta.6 / 2021-12-05** +- Support PI Tags processing +- Support `suppressBooleanAttributes` by XML Builder for attributes with value `true`. + +**4.0.0-beta.5 / 2021-12-04** +- fix: when a tag with name "attributes" + +**4.0.0-beta.4 / 2021-12-02** +- Support HTML document parsing +- skip stop nodes parsing when building the XML from JS object +- Support external entites without DOCTYPE +- update dev dependency: strnum v1.0.5 to fix long number issue + +**4.0.0-beta.3 / 2021-11-30** +- support global stopNodes expression like "*.stop" +- support self-closing and paired unpaired tags +- fix: CDATA should not be parsed. +- Fix typings for XMLBuilder (#396)(By [Anders Emil Salvesen](https://github.com/andersem)) +- supports XML entities, HTML entities, DOCTYPE entities + +**⚠️ 4.0.0-beta.2 / 2021-11-19** +- rename `attrMap` to `attibutes` in parser output when `preserveOrder:true` +- supports unpairedTags + +**⚠️ 4.0.0-beta.1 / 2021-11-18** +- Parser returns an array now + - to make the structure common + - and to return root level detail +- renamed `cdataTagName` to `cdataPropName` +- Added `commentPropName` +- fix typings + +**⚠️ 4.0.0-beta.0 / 2021-11-16** +- Name change of many configuration properties. + - `attrNodeName` to `attributesGroupName` + - `attrValueProcessor` to `attributeValueProcessor` + - `parseNodeValue` to `parseTagValue` + - `ignoreNameSpace` to `removeNSPrefix` + - `numParseOptions` to `numberParseOptions` + - spelling correction for `suppressEmptyNode` +- Name change of cli and browser bundle to **fxparser** +- `isArray` option is added to parse a tag into array +- `preserveOrder` option is added to render XML in such a way that the result js Object maintains the order of properties same as in XML. +- Processing behaviour of `tagValueProcessor` and `attributeValueProcessor` are changes with extra input parameters +- j2xparser is renamed to XMLBuilder. +- You need to build XML parser instance for given options first before parsing XML. +- fix #327, #336: throw error when extra text after XML content +- fix #330: attribute value can have '\n', +- fix #350: attrbiutes can be separated by '\n' from tagname + +3.21.1 / 2021-10-31 +- Correctly format JSON elements with a text prop but no attribute props ( By [haddadnj](https://github.com/haddadnj) ) + +3.21.0 / 2021-10-25 + - feat: added option `rootNodeName` to set tag name for array input when converting js object to XML. + - feat: added option `alwaysCreateTextNode` to force text node creation (by: *@massimo-ua*) + - ⚠️ feat: Better error location for unclosed tags. (by *@Gei0r*) + - Some error messages would be changed when validating XML. Eg + - `{ InvalidXml: "Invalid '[ \"rootNode\"]' found." }` → `{InvalidTag: "Unclosed tag 'rootNode'."}` + - `{ InvalidTag: "Closing tag 'rootNode' is expected inplace of 'rootnode'." }` → `{ InvalidTag: "Expected closing tag 'rootNode' (opened in line 1) instead of closing tag 'rootnode'."}` + - ⚠️ feat: Column in error response when validating XML +```js +{ + "code": "InvalidAttr", + "msg": "Attribute 'abc' is repeated.", + "line": 1, + "col": 22 +} +``` + +3.20.1 / 2021-09-25 + - update strnum package + +3.20.0 / 2021-09-10 + - Use strnum npm package to parse string to number + - breaking change: long number will be parsed to scientific notation. + +3.19.0 / 2021-03-14 + - License changed to MIT original + - Fix #321 : namespace tag parsing + +3.18.0 / 2021-02-05 + - Support RegEx and function in arrayMode option + - Fix #317 : validate nested PI tags + +3.17.4 / 2020-06-07 + - Refactor some code to support IE11 + - Fix: `` space as attribute string + +3.17.3 / 2020-05-23 + - Fix: tag name separated by \n \t + - Fix: throw error for unclosed tags + +3.17.2 / 2020-05-23 + - Fixed an issue in processing doctype tag + - Fixed tagName where it should not have whitespace chars + +3.17.1 / 2020-05-19 + - Fixed an issue in checking opening tag + +3.17.0 / 2020-05-18 + - parser: fix '<' issue when it comes in aatr value + - parser: refactoring to remove dependency from regex + - validator: fix IE 11 issue for error messages + - updated dev dependencies + - separated benchmark module to sub-module + - breaking change: comments will not be removed from CDATA data + +3.16.0 / 2020-01-12 + - validaor: fix for ampersand characters (#215) + - refactoring to support unicode chars in tag name + - update typing for validator error + +3.15.1 / 2019-12-09 + - validaor: fix multiple roots are not allowed + +3.15.0 / 2019-11-23 + - validaor: improve error messaging + - validator: add line number in case of error + - validator: add more error scenarios to make it more descriptive + +3.14.0 / 2019-10-25 + - arrayMode for XML to JS obj parsing + +3.13.0 / 2019-10-02 + - pass tag/attr name to tag/attr value processor + - inbuilt optional validation with XML parser + +3.12.21 / 2019-10-02 + - Fix validator for unclosed XMLs + - move nimnjs dependency to dev dependency + - update dependencies + +3.12.20 / 2019-08-16 + - Revert: Fix #167: '>' in attribute value as it is causing high performance degrade. + +3.12.19 / 2019-07-28 + - Fix js to xml parser should work for date values. (broken: `tagValueProcessor` will receive the original value instead of string always) (breaking change) + +3.12.18 / 2019-07-27 + - remove configstore dependency + +3.12.17 / 2019-07-14 + - Fix #167: '>' in attribute value + +3.12.16 / 2019-03-23 + - Support a new option "stopNodes". (#150) +Accept the list of tags which are not required to be parsed. Instead, all the nested tag and data will be assigned as string. + - Don't show post-install message + +3.12.12 / 2019-01-11 + - fix : IE parseInt, parseFloat error + +3.12.11 / 2018-12-24 + - fix #132: "/" should not be parsed as boolean attr in case of self closing tags + +3.12.9 / 2018-11-23 + - fix #129 : validator should not fail when an atrribute name is 'length' + +3.12.8 / 2018-11-22 + - fix #128 : use 'attrValueProcessor' to process attribute value in json2xml parser + +3.12.6 / 2018-11-10 + - Fix #126: check for type + +3.12.4 / 2018-09-12 + - Fix: include tasks in npm package + +3.12.3 / 2018-09-12 + - Fix CLI issue raised in last PR + +3.12.2 / 2018-09-11 + - Fix formatting for JSON to XML output + - Migrate to webpack (PR merged) + - fix cli (PR merged) + +3.12.0 / 2018-08-06 + - Support hexadecimal values + - Support true number parsing + +3.11.2 / 2018-07-23 + - Update Demo for more options + - Update license information + - Update readme for formatting, users, and spelling mistakes + - Add missing typescript definition for j2xParser + - refactoring: change filenames + +3.11.1 / 2018-06-05 + - fix #93: read the text after self closing tag + +3.11.0 / 2018-05-20 + - return defaultOptions if there are not options in buildOptions function + - added localeRange declaration in parser.d.ts + - Added support of cyrillic characters in validator XML + - fixed bug in validator work when XML data with byte order marker + +3.10.0 / 2018-05-13 + - Added support of cyrillic characters in parsing XML to JSON + +3.9.11 / 2018-05-09 + - fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/80 fix nimn chars + - update package information + - fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/86: json 2 xml parser : property with null value should be parsed to self closing tag. + - update online demo + - revert zombiejs to old version to support old version of node + - update dependencies + +3.3.10 / 2018-04-23 + - fix #77 : parse even if closing tag has space before '>' + - include all css & js lib in demo app + - remove babel dependencies until needed + +3.3.9 / 2018-04-18 + - fix #74 : TS2314 TypeScript compiler error + +3.3.8 / 2018-04-17 + - fix #73 : IE doesn't support Object.assign + +3.3.7 / 2018-04-14 + - fix: use let insted of const in for loop of validator + - Merge pull request + https://github.com/NaturalIntelligence/fast-xml-parser/issues/71 from bb/master + first draft of typings for typescript + https://github.com/NaturalIntelligence/fast-xml-parser/issues/69 + - Merge pull request + https://github.com/NaturalIntelligence/fast-xml-parser/issues/70 from bb/patch-1 + fix some typos in readme + +3.3.6 / 2018-03-21 + - change arrow functions to full notation for IE compatibility + +3.3.5 / 2018-03-15 + - fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/67 : attrNodeName invalid behavior + - fix: remove decodeHTML char condition + +3.3.4 / 2018-03-14 + - remove dependency on "he" package + - refactor code to separate methods in separate files. + - draft code for transforming XML to json string. It is not officially documented due to performance issue. + +3.3.0 / 2018-03-05 + - use common default options for XML parsing for consistency. And add `parseToNimn` method. + - update nexttodo + - update README about XML to Nimn transformation and remove special notes about 3.x release + - update CONTRIBUTING.ms mentioning nexttodo + - add negative case for XML PIs + - validate xml processing instruction tags https://github.com/NaturalIntelligence/fast-xml-parser/issues/62 + - nimndata: handle array with object + - nimndata: node with nested node and text node + - nimndata: handle attributes and text node + - nimndata: add options, handle array + - add xml to nimn data converter + - x2j: direct access property with tagname + - update changelog + - fix validator when single quote presents in value enclosed with double quotes or vice versa + - Revert "remove unneded nimnjs dependency, move opencollective to devDependencies and replace it + with more light opencollective-postinstall" + This reverts commit d47aa7181075d82db4fee97fd8ea32b056fe3f46. + - Merge pull request: https://github.com/NaturalIntelligence/fast-xml-parser/issues/63 from HaroldPutman/suppress-undefined + Keep undefined nodes out of the XML output : This is useful when you are deleting nodes from the JSON and rewriting XML. + +3.2.4 / 2018-03-01 + - fix #59 fix in validator when open quote presents in attribute value + - Create nexttodo.md + - exclude static from bitHound tests + - add package lock + +3.2.3 / 2018-02-28 + - Merge pull request from Delagen/master: fix namespaces can contain the same characters as xml names + +3.2.2 / 2018-02-22 + - fix: attribute xmlns should not be removed if ignoreNameSpace is false + - create CONTRIBUTING.md + +3.2.1 / 2018-02-17 + - fix: empty attribute should be parsed + +3.2.0 / 2018-02-16 + - Merge pull request : Dev to Master + - Update README and version + - j2x:add performance test + - j2x: Remove extra empty line before closing tag + - j2x: suppress empty nodes to self closing node if configured + - j2x: provide option to give indentation depth + - j2x: make optional formatting + - j2x: encodeHTMLchat + - j2x: handle cdata tag + - j2x: handle grouped attributes + - convert json to xml + - nested object + - array + - attributes + - text value + - small refactoring + - Merge pull request: Update cli.js to let user validate XML file or data + - Add option for rendering CDATA as separate property + +3.0.1 / 2018-02-09 + - fix CRLF: replace it with single space in attributes value only. + +3.0.0 / 2018-02-08 + - change online tool with new changes + - update info about new options + - separate tag value processing to separate function + - make HTML decoding optional + - give an option to allow boolean attributes + - change cli options as per v3 + - Correct comparison table format on README + - update v3 information + - some performance improvement changes + - Make regex object local to the method and move some common methods to util + - Change parser to + - handle multiple instances of CDATA + - make triming of value optionals + - HTML decode attribute and text value + - refactor code to separate files + - Ignore newline chars without RE (in validator) + - validate for XML prolog + - Validate DOCTYPE without RE + - Update validator to return error response + - Update README to add detail about V3 + - Separate xmlNode model class + - include vscode debug config + - fix for repeated object + - fix attribute regex for boolean attributes + - Fix validator for invalid attributes +2.9.4 / 2018-02-02 + - Merge pull request: Decode HTML characters + - refactor source folder name + - ignore bundle / browser js to be published to npm +2.9.3 / 2018-01-26 + - Merge pull request: Correctly remove CRLF line breaks + - Enable to parse attribute in online editor + - Fix testing demo app test + - Describe parsing options + - Add options for online demo +2.9.2 / 2018-01-18 + - Remove check if tag starting with "XML" + - Fix: when there are spaces before / after CDATA + +2.9.1 / 2018-01-16 + - Fix: newline should be replaced with single space + - Fix: for single and multiline comments + - validate xml with CDATA + - Fix: the issue when there is no space between 2 attributes + - Fix: https://github.com/NaturalIntelligence/fast-xml-parser/issues/33: when there is newline char in attr val, it doesn't parse + - Merge pull request: fix ignoreNamespace + - fix: don't wrap attributes if only namespace attrs + - fix: use portfinder for run tests, update deps + - fix: don't treat namespaces as attributes when ignoreNamespace enabled + +2.9.0 / 2018-01-10 + - Rewrite the validator to handle large files. + Ignore DOCTYPE validation. + - Fix: When attribute value has equal sign + +2.8.3 / 2017-12-15 + - Fix: when a tag has value along with subtags + +2.8.2 / 2017-12-04 + - Fix value parsing for IE + +2.8.1 / 2017-12-01 + - fix: validator should return false instead of err when invalid XML + +2.8.0 / 2017-11-29 + - Add CLI option to ignore value conversion + - Fix variable name when filename is given on CLI + - Update CLI help text + - Merge pull request: xml2js: Accept standard input + - Test Node 8 + - Update dependencies + - Bundle readToEnd + - Add ability to read from standard input + +2.7.4 / 2017-09-22 + - Merge pull request: Allow wrap attributes with subobject to compatible with other parsers output + +2.7.3 / 2017-08-02 + - fix: handle CDATA with regx + +2.7.2 / 2017-07-30 + - Change travis config for yarn caching + - fix validator: when tag property is same as array property + - Merge pull request: Failing test case in validator for valid SVG + +2.7.1 / 2017-07-26 + - Fix: Handle val 0 + +2.7.0 / 2017-07-25 + - Fix test for arrayMode + - Merge pull request: Add arrayMode option to parse any nodes as arrays + +2.6.0 / 2017-07-14 + - code improvement + - Add unit tests for value conversion for attr + - Merge pull request: option of an attribute value conversion to a number (textAttrConversion) the same way as the textNodeConversion option does. Default value is false. + +2.5.1 / 2017-07-01 + - Fix XML element name pattern + - Fix XML element name pattern while parsing + - Fix validation for xml tag element + +2.5.0 / 2017-06-25 + - Improve Validator performance + - update attr matching regex + - Add perf tests + - Improve atrr regex to handle all cases + +2.4.4 / 2017-06-08 + - Bug fix: when an attribute has single or double quote in value + +2.4.3 / 2017-06-05 + - Bug fix: when multiple CDATA tags are given + - Merge pull request: add option "textNodeConversion" + - add option "textNodeConversion" + +2.4.1 / 2017-04-14 + - fix tests + - Bug fix: preserve initial space of node value + - Handle CDATA + +2.3.1 / 2017-03-15 + - Bug fix: when single self closing tag + - Merge pull request: fix .codeclimate.yml + - Update .codeclimate.yml - Fixed config so it does not error anymore. + - Update .codeclimate.yml + +2.3.0 / 2017-02-26 + - Code improvement + - add bithound config + - Update usage + - Update travis to generate bundle js before running tests + - 1.Browserify, 2. add more tests for validator + - Add validator + - Fix CLI default parameter bug + +2.2.1 / 2017-02-05 + - Bug fix: CLI default option diff --git a/node_modules/fast-xml-parser/LICENSE b/node_modules/fast-xml-parser/LICENSE new file mode 100644 index 0000000..d7da622 --- /dev/null +++ b/node_modules/fast-xml-parser/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Amit Kumar Gupta + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/fast-xml-parser/README.md b/node_modules/fast-xml-parser/README.md new file mode 100644 index 0000000..6b5fb21 --- /dev/null +++ b/node_modules/fast-xml-parser/README.md @@ -0,0 +1,205 @@ +# [fast-xml-parser](https://www.npmjs.com/package/fast-xml-parser) + +[![NPM total downloads](https://img.shields.io/npm/dt/fast-xml-parser.svg)](https://npm.im/fast-xml-parser) + +Validate XML, Parse XML to JS Object, or Build XML from JS Object without C/C++ based libraries and no callback. + +FXP logo + +* Validate XML data syntactically. Use [detailed-xml-validator](https://github.com/NaturalIntelligence/detailed-xml-validator/) to verify business rules. +* Parse XML to JS Objects and vice versa +* Common JS, ESM, and browser compatible +* Faster than any other pure JS implementation. + +It can handle big files (tested up to 100mb). XML Entities, HTML entities, and DOCTYPE entites are supported. Unpaired tags (Eg `
` in HTML), stop nodes (Eg ` +: + +``` + +Bundle size + +| Bundle Name | Size | +| ------------------ | ---- | +| fxbuilder.min.js | 6.5K | +| fxparser.min.js | 20K | +| fxp.min.js | 26K | +| fxvalidator.min.js | 5.7K | + +## Documents + + + + + + + +
v3v4 and v5v6
+ documents +
    +
  1. Getting Started
  2. +
  3. XML Parser
  4. +
  5. XML Builder
  6. +
  7. XML Validator
  8. +
  9. Entities
  10. +
  11. HTML Document Parsing
  12. +
  13. PI Tag processing
  14. +
  15. Path Expression
  16. +
    +
  1. Getting Started +
  2. Features
  3. +
  4. Options
  5. +
  6. Output Builders
  7. +
  8. Value Parsers
  9. +
+ +**note**: +- Version 6 is released with version 4 for experimental use. Based on its demand, it'll be developed and the features can be different in final release. +- Version 5 has the same functionalities as version 4. + +## Performance +negative means error + +### XML Parser + + + + +* Y-axis: requests per second +* X-axis: File size + +### XML Builder + + +* Y-axis: requests per second + + + +--- + +## Usage Trend + +[Usage Trend of fast-xml-parser](https://npm-compare.com/fast-xml-parser#timeRange=THREE_YEARS) + + + NPM Usage Trend of fast-xml-parser + + +# Supporters +#### Contributors + +This project exists thanks to [all](graphs/contributors) the people who contribute. [[Contribute](docs/CONTRIBUTING.md)]. + + + + +#### Backers from Open collective + +Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/fast-xml-parser#backer)] + + + + + +# License +* MIT License + +![Donate $5](static/img/donation_quote.png) diff --git a/node_modules/fast-xml-parser/lib/fxbuilder.min.js b/node_modules/fast-xml-parser/lib/fxbuilder.min.js new file mode 100644 index 0000000..9e7512b --- /dev/null +++ b/node_modules/fast-xml-parser/lib/fxbuilder.min.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.XMLBuilder=e():t.XMLBuilder=e()}(this,()=>(()=>{"use strict";var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{default:()=>y});class i{constructor(t,e={},i){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=i,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let i=0,s="";for(;i0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const i=e[e.length-1];return void 0!==i.values&&t in i.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class n{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new s(this)}push(t,e=null,i=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const s=this.path.length;this.siblingStacks[s]||(this.siblingStacks[s]=new Map);const n=this.siblingStacks[s],r=i?`${i}:${t}`:t,o=n.get(r)||0;let a=0;for(const t of n.values())a+=t;n.set(r,o+1);const h={tag:t,position:a,counter:o};null!=i&&(h.namespace=i),null!=e&&(h.values=e),this.path.push(h)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const i=t||this.separator;if(i===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e=0&&e>=0;){const s=t[i];if("deep-wildcard"===s.type){if(i--,i<0)return!0;const s=t[i];let n=!1;for(let t=e;t>=0;t--)if(this._matchSegment(s,this.path[t],t===this.path.length-1)){e=t-1,i--,n=!0;break}if(!n)return!1}else{if(!this._matchSegment(s,this.path[e],e===this.path.length-1))return!1;e--,i--}}return i<0}_matchSegment(t,e,i){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!i)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!i)return!1;const s=e.counter??0;if("first"===t.position&&0!==s)return!1;if("odd"===t.position&&s%2!=1)return!1;if("even"===t.position&&s%2!=0)return!1;if("nth"===t.position&&s!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}function r(t,e){let s="";e.format&&e.indentBy.length>0&&(s="\n");const r=[];if(e.stopNodes&&Array.isArray(e.stopNodes))for(let t=0;te.maxNestedTags)throw new Error("Maximum nested tags exceeded");if(!Array.isArray(t)){if(null!=t){let i=t.toString();return i=g(i,e),i}return""}for(let d=0;d/g,"]]]]>")}]]>`,p=!1,s.pop();continue}if(m===e.commentPropName){const t=f[m][0][e.textNodeName];r+=i+`\x3c!--${String(t).replace(/--/g,"- -").replace(/-$/,"- ")}--\x3e`,p=!0,s.pop();continue}if("?"===m[0]){const t=l(f[":@"],e,N),n="?xml"===m?"":i;let o=f[m][0][e.textNodeName];o=0!==o.length?" "+o:"",r+=n+`<${m}${o}${t}?>`,p=!0,s.pop();continue}let y=i;""!==y&&(y+=e.indentBy);const x=i+`<${m}${l(f[":@"],e,N)}`;let A;A=N?h(f[m],e):o(f[m],e,y,s,n),-1!==e.unpairedTags.indexOf(m)?e.suppressUnpairedNode?r+=x+">":r+=x+"/>":A&&0!==A.length||!e.suppressEmptyNode?A&&A.endsWith(">")?r+=x+`>${A}${i}`:(r+=x+">",A&&""!==i&&(A.includes("/>")||A.includes("`):r+=x+"/>",p=!0,s.pop()}return r}function a(t,e){if(!t||e.ignoreAttributes)return null;const i={};let s=!1;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n.startsWith(e.attributeNamePrefix)?n.substr(e.attributeNamePrefix.length):n]=t[n],s=!0);return s?i:null}function h(t,e){if(!Array.isArray(t))return null!=t?t.toString():"";let i="";for(let s=0;s${s}`:i+=`<${r}${t}/>`}}}return i}function p(t,e){let i="";if(t&&!e.ignoreAttributes)for(let s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=t[s];!0===n&&e.suppressBooleanAttributes?i+=` ${s.substr(e.attributeNamePrefix.length)}`:i+=` ${s.substr(e.attributeNamePrefix.length)}="${n}"`}return i}function u(t){const e=Object.keys(t);for(let i=0;i0&&e.processEntities)for(let i=0;i","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1,maxNestedTags:100,jPath:!0};function f(t){if(this.options=Object.assign({},d,t),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(let t=0;t{for(const i of e){if("string"==typeof i&&t===i)return!0;if(i instanceof RegExp&&i.test(t))return!0}}:()=>!1,this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=N),this.processTextOrObjNode=m,this.options.format?(this.indentate=b,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function m(t,e,i,s){const n=this.extractAttributes(t);if(s.push(e,n),this.checkStopNode(s)){const n=this.buildRawContent(t),r=this.buildAttributesForStopNode(t);return s.pop(),this.buildObjectNode(n,e,r,i)}const r=this.j2x(t,i+1,s);return s.pop(),void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,r.attrStr,i,s):this.buildObjectNode(r.val,e,r.attrStr,i)}function b(t){return this.options.indentBy.repeat(t)}function N(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}f.prototype.build=function(t){if(this.options.preserveOrder)return r(t,this.options);{Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t});const e=new n;return this.j2x(t,0,e).val}},f.prototype.j2x=function(t,e,i){let s="",n="";if(this.options.maxNestedTags&&i.getDepth()>=this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");const r=this.options.jPath?i.toString():i,o=this.checkStopNode(i);for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a))if(void 0===t[a])this.isAttribute(a)&&(n+="");else if(null===t[a])this.isAttribute(a)||a===this.options.cdataPropName?n+="":"?"===a[0]?n+=this.indentate(e)+"<"+a+"?"+this.tagEndChar:n+=this.indentate(e)+"<"+a+"/"+this.tagEndChar;else if(t[a]instanceof Date)n+=this.buildTextValNode(t[a],a,"",e,i);else if("object"!=typeof t[a]){const h=this.isAttribute(a);if(h&&!this.ignoreAttributesFn(h,r))s+=this.buildAttrPairStr(h,""+t[a],o);else if(!h)if(a===this.options.textNodeName){let e=this.options.tagValueProcessor(a,""+t[a]);n+=this.replaceEntitiesValue(e)}else{i.push(a);const s=this.checkStopNode(i);if(i.pop(),s){const i=""+t[a];n+=""===i?this.indentate(e)+"<"+a+this.closeTag(a)+this.tagEndChar:this.indentate(e)+"<"+a+">"+i+""+t+"${t}`;else if("object"==typeof t&&null!==t){const s=this.buildRawContent(t),n=this.buildAttributesForStopNode(t);e+=""===s?`<${i}${n}/>`:`<${i}${n}>${s}`}}else if("object"==typeof s&&null!==s){const t=this.buildRawContent(s),n=this.buildAttributesForStopNode(s);e+=""===t?`<${i}${n}/>`:`<${i}${n}>${t}`}else e+=`<${i}>${s}`}return e},f.prototype.buildAttributesForStopNode=function(t){if(!t||"object"!=typeof t)return"";let e="";if(this.options.attributesGroupName&&t[this.options.attributesGroupName]){const i=t[this.options.attributesGroupName];for(let t in i){if(!Object.prototype.hasOwnProperty.call(i,t))continue;const s=t.startsWith(this.options.attributeNamePrefix)?t.substring(this.options.attributeNamePrefix.length):t,n=i[t];!0===n&&this.options.suppressBooleanAttributes?e+=" "+s:e+=" "+s+'="'+n+'"'}}else for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;const s=this.isAttribute(i);if(s){const n=t[i];!0===n&&this.options.suppressBooleanAttributes?e+=" "+s:e+=" "+s+'="'+n+'"'}}return e},f.prototype.buildObjectNode=function(t,e,i,s){if(""===t)return"?"===e[0]?this.indentate(s)+"<"+e+i+"?"+this.tagEndChar:this.indentate(s)+"<"+e+i+this.closeTag(e)+this.tagEndChar;{let n=""+t+n}},f.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>/g,"]]]]>");return this.indentate(s)+``+this.newLine}if(!1!==this.options.commentPropName&&e===this.options.commentPropName){const e=String(t).replace(/--/g,"- -").replace(/-$/,"- ");return this.indentate(s)+`\x3c!--${e}--\x3e`+this.newLine}if("?"===e[0])return this.indentate(s)+"<"+e+i+"?"+this.tagEndChar;{let n=this.options.tagValueProcessor(e,t);return n=this.replaceEntitiesValue(n),""===n?this.indentate(s)+"<"+e+i+this.closeTag(e)+this.tagEndChar:this.indentate(s)+"<"+e+i+">"+n+"0&&this.options.processEntities)for(let e=0;e {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Expression - Parses and stores a tag pattern expression\n * \n * Patterns are parsed once and stored in an optimized structure for fast matching.\n * \n * @example\n * const expr = new Expression(\"root.users.user\");\n * const expr2 = new Expression(\"..user[id]:first\");\n * const expr3 = new Expression(\"root/users/user\", { separator: '/' });\n */\nexport default class Expression {\n /**\n * Create a new Expression\n * @param {string} pattern - Pattern string (e.g., \"root.users.user\", \"..user[id]\")\n * @param {Object} options - Configuration options\n * @param {string} options.separator - Path separator (default: '.')\n */\n constructor(pattern, options = {}, data) {\n this.pattern = pattern;\n this.separator = options.separator || '.';\n this.segments = this._parse(pattern);\n this.data = data;\n // Cache expensive checks for performance (O(1) instead of O(n))\n this._hasDeepWildcard = this.segments.some(seg => seg.type === 'deep-wildcard');\n this._hasAttributeCondition = this.segments.some(seg => seg.attrName !== undefined);\n this._hasPositionSelector = this.segments.some(seg => seg.position !== undefined);\n }\n\n /**\n * Parse pattern string into segments\n * @private\n * @param {string} pattern - Pattern to parse\n * @returns {Array} Array of segment objects\n */\n _parse(pattern) {\n const segments = [];\n\n // Split by separator but handle \"..\" specially\n let i = 0;\n let currentPart = '';\n\n while (i < pattern.length) {\n if (pattern[i] === this.separator) {\n // Check if next char is also separator (deep wildcard)\n if (i + 1 < pattern.length && pattern[i + 1] === this.separator) {\n // Flush current part if any\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n currentPart = '';\n }\n // Add deep wildcard\n segments.push({ type: 'deep-wildcard' });\n i += 2; // Skip both separators\n } else {\n // Regular separator\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n currentPart = '';\n i++;\n }\n } else {\n currentPart += pattern[i];\n i++;\n }\n }\n\n // Flush remaining part\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n\n return segments;\n }\n\n /**\n * Parse a single segment\n * @private\n * @param {string} part - Segment string (e.g., \"user\", \"ns::user\", \"user[id]\", \"ns::user:first\")\n * @returns {Object} Segment object\n */\n _parseSegment(part) {\n const segment = { type: 'tag' };\n\n // NEW NAMESPACE SYNTAX (v2.0):\n // ============================\n // Namespace uses DOUBLE colon (::)\n // Position uses SINGLE colon (:)\n // \n // Examples:\n // \"user\" → tag\n // \"user:first\" → tag + position\n // \"user[id]\" → tag + attribute\n // \"user[id]:first\" → tag + attribute + position\n // \"ns::user\" → namespace + tag\n // \"ns::user:first\" → namespace + tag + position\n // \"ns::user[id]\" → namespace + tag + attribute\n // \"ns::user[id]:first\" → namespace + tag + attribute + position\n // \"ns::first\" → namespace + tag named \"first\" (NO ambiguity!)\n //\n // This eliminates all ambiguity:\n // :: = namespace separator\n // : = position selector\n // [] = attributes\n\n // Step 1: Extract brackets [attr] or [attr=value]\n let bracketContent = null;\n let withoutBrackets = part;\n\n const bracketMatch = part.match(/^([^\\[]+)(\\[[^\\]]*\\])(.*)$/);\n if (bracketMatch) {\n withoutBrackets = bracketMatch[1] + bracketMatch[3];\n if (bracketMatch[2]) {\n const content = bracketMatch[2].slice(1, -1);\n if (content) {\n bracketContent = content;\n }\n }\n }\n\n // Step 2: Check for namespace (double colon ::)\n let namespace = undefined;\n let tagAndPosition = withoutBrackets;\n\n if (withoutBrackets.includes('::')) {\n const nsIndex = withoutBrackets.indexOf('::');\n namespace = withoutBrackets.substring(0, nsIndex).trim();\n tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim(); // Skip ::\n\n if (!namespace) {\n throw new Error(`Invalid namespace in pattern: ${part}`);\n }\n }\n\n // Step 3: Parse tag and position (single colon :)\n let tag = undefined;\n let positionMatch = null;\n\n if (tagAndPosition.includes(':')) {\n const colonIndex = tagAndPosition.lastIndexOf(':'); // Use last colon for position\n const tagPart = tagAndPosition.substring(0, colonIndex).trim();\n const posPart = tagAndPosition.substring(colonIndex + 1).trim();\n\n // Verify position is a valid keyword\n const isPositionKeyword = ['first', 'last', 'odd', 'even'].includes(posPart) ||\n /^nth\\(\\d+\\)$/.test(posPart);\n\n if (isPositionKeyword) {\n tag = tagPart;\n positionMatch = posPart;\n } else {\n // Not a valid position keyword, treat whole thing as tag\n tag = tagAndPosition;\n }\n } else {\n tag = tagAndPosition;\n }\n\n if (!tag) {\n throw new Error(`Invalid segment pattern: ${part}`);\n }\n\n segment.tag = tag;\n if (namespace) {\n segment.namespace = namespace;\n }\n\n // Step 4: Parse attributes\n if (bracketContent) {\n if (bracketContent.includes('=')) {\n const eqIndex = bracketContent.indexOf('=');\n segment.attrName = bracketContent.substring(0, eqIndex).trim();\n segment.attrValue = bracketContent.substring(eqIndex + 1).trim();\n } else {\n segment.attrName = bracketContent.trim();\n }\n }\n\n // Step 5: Parse position selector\n if (positionMatch) {\n const nthMatch = positionMatch.match(/^nth\\((\\d+)\\)$/);\n if (nthMatch) {\n segment.position = 'nth';\n segment.positionValue = parseInt(nthMatch[1], 10);\n } else {\n segment.position = positionMatch;\n }\n }\n\n return segment;\n }\n\n /**\n * Get the number of segments\n * @returns {number}\n */\n get length() {\n return this.segments.length;\n }\n\n /**\n * Check if expression contains deep wildcard\n * @returns {boolean}\n */\n hasDeepWildcard() {\n return this._hasDeepWildcard;\n }\n\n /**\n * Check if expression has attribute conditions\n * @returns {boolean}\n */\n hasAttributeCondition() {\n return this._hasAttributeCondition;\n }\n\n /**\n * Check if expression has position selectors\n * @returns {boolean}\n */\n hasPositionSelector() {\n return this._hasPositionSelector;\n }\n\n /**\n * Get string representation\n * @returns {string}\n */\n toString() {\n return this.pattern;\n }\n}","import ExpressionSet from \"./ExpressionSet.js\";\n\n/**\n * MatcherView - A lightweight read-only view over a Matcher's internal state.\n *\n * Created once by Matcher and reused across all callbacks. Holds a direct\n * reference to the parent Matcher so it always reflects current parser state\n * with zero copying or freezing overhead.\n *\n * Users receive this via {@link Matcher#readOnly} or directly from parser\n * callbacks. It exposes all query and matching methods but has no mutation\n * methods — misuse is caught at the TypeScript level rather than at runtime.\n *\n * @example\n * const matcher = new Matcher();\n * const view = matcher.readOnly();\n *\n * matcher.push(\"root\", {});\n * view.getCurrentTag(); // \"root\"\n * view.getDepth(); // 1\n */\nexport class MatcherView {\n /**\n * @param {Matcher} matcher - The parent Matcher instance to read from.\n */\n constructor(matcher) {\n this._matcher = matcher;\n }\n\n /**\n * Get the path separator used by the parent matcher.\n * @returns {string}\n */\n get separator() {\n return this._matcher.separator;\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return undefined;\n return path[path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return false;\n const current = path[path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this._matcher.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n return this._matcher.toString(separator, includeNamespace);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this._matcher.path.map(n => n.tag);\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n return this._matcher.matches(expression);\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this._matcher);\n }\n}\n\n/**\n * Matcher - Tracks current path in XML/JSON tree and matches against Expressions.\n *\n * The matcher maintains a stack of nodes representing the current path from root to\n * current tag. It only stores attribute values for the current (top) node to minimize\n * memory usage. Sibling tracking is used to auto-calculate position and counter.\n *\n * Use {@link Matcher#readOnly} to obtain a {@link MatcherView} safe to pass to\n * user callbacks — it always reflects current state with no Proxy overhead.\n *\n * @example\n * const matcher = new Matcher();\n * matcher.push(\"root\", {});\n * matcher.push(\"users\", {});\n * matcher.push(\"user\", { id: \"123\", type: \"admin\" });\n *\n * const expr = new Expression(\"root.users.user\");\n * matcher.matches(expr); // true\n */\nexport default class Matcher {\n /**\n * Create a new Matcher.\n * @param {Object} [options={}]\n * @param {string} [options.separator='.'] - Default path separator\n */\n constructor(options = {}) {\n this.separator = options.separator || '.';\n this.path = [];\n this.siblingStacks = [];\n // Each path node: { tag, values, position, counter, namespace? }\n // values only present for current (last) node\n // Each siblingStacks entry: Map tracking occurrences at each level\n this._pathStringCache = null;\n this._view = new MatcherView(this);\n }\n\n /**\n * Push a new tag onto the path.\n * @param {string} tagName\n * @param {Object|null} [attrValues=null]\n * @param {string|null} [namespace=null]\n */\n push(tagName, attrValues = null, namespace = null) {\n this._pathStringCache = null;\n\n // Remove values from previous current node (now becoming ancestor)\n if (this.path.length > 0) {\n this.path[this.path.length - 1].values = undefined;\n }\n\n // Get or create sibling tracking for current level\n const currentLevel = this.path.length;\n if (!this.siblingStacks[currentLevel]) {\n this.siblingStacks[currentLevel] = new Map();\n }\n\n const siblings = this.siblingStacks[currentLevel];\n\n // Create a unique key for sibling tracking that includes namespace\n const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;\n\n // Calculate counter (how many times this tag appeared at this level)\n const counter = siblings.get(siblingKey) || 0;\n\n // Calculate position (total children at this level so far)\n let position = 0;\n for (const count of siblings.values()) {\n position += count;\n }\n\n // Update sibling count for this tag\n siblings.set(siblingKey, counter + 1);\n\n // Create new node\n const node = {\n tag: tagName,\n position: position,\n counter: counter\n };\n\n if (namespace !== null && namespace !== undefined) {\n node.namespace = namespace;\n }\n\n if (attrValues !== null && attrValues !== undefined) {\n node.values = attrValues;\n }\n\n this.path.push(node);\n }\n\n /**\n * Pop the last tag from the path.\n * @returns {Object|undefined} The popped node\n */\n pop() {\n if (this.path.length === 0) return undefined;\n this._pathStringCache = null;\n\n const node = this.path.pop();\n\n if (this.siblingStacks.length > this.path.length + 1) {\n this.siblingStacks.length = this.path.length + 1;\n }\n\n return node;\n }\n\n /**\n * Update current node's attribute values.\n * Useful when attributes are parsed after push.\n * @param {Object} attrValues\n */\n updateCurrent(attrValues) {\n if (this.path.length > 0) {\n const current = this.path[this.path.length - 1];\n if (attrValues !== null && attrValues !== undefined) {\n current.values = attrValues;\n }\n }\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n return this.path.length > 0 ? this.path[this.path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n return this.path.length > 0 ? this.path[this.path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n if (this.path.length === 0) return undefined;\n return this.path[this.path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n if (this.path.length === 0) return false;\n const current = this.path[this.path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n const sep = separator || this.separator;\n const isDefault = (sep === this.separator && includeNamespace === true);\n\n if (isDefault) {\n if (this._pathStringCache !== null) {\n return this._pathStringCache;\n }\n const result = this.path.map(n =>\n (n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n this._pathStringCache = result;\n return result;\n }\n\n return this.path.map(n =>\n (includeNamespace && n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this.path.map(n => n.tag);\n }\n\n /**\n * Reset the path to empty.\n */\n reset() {\n this._pathStringCache = null;\n this.path = [];\n this.siblingStacks = [];\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n const segments = expression.segments;\n\n if (segments.length === 0) {\n return false;\n }\n\n if (expression.hasDeepWildcard()) {\n return this._matchWithDeepWildcard(segments);\n }\n\n return this._matchSimple(segments);\n }\n\n /**\n * @private\n */\n _matchSimple(segments) {\n if (this.path.length !== segments.length) {\n return false;\n }\n\n for (let i = 0; i < segments.length; i++) {\n if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * @private\n */\n _matchWithDeepWildcard(segments) {\n let pathIdx = this.path.length - 1;\n let segIdx = segments.length - 1;\n\n while (segIdx >= 0 && pathIdx >= 0) {\n const segment = segments[segIdx];\n\n if (segment.type === 'deep-wildcard') {\n segIdx--;\n\n if (segIdx < 0) {\n return true;\n }\n\n const nextSeg = segments[segIdx];\n let found = false;\n\n for (let i = pathIdx; i >= 0; i--) {\n if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) {\n pathIdx = i - 1;\n segIdx--;\n found = true;\n break;\n }\n }\n\n if (!found) {\n return false;\n }\n } else {\n if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) {\n return false;\n }\n pathIdx--;\n segIdx--;\n }\n }\n\n return segIdx < 0;\n }\n\n /**\n * @private\n */\n _matchSegment(segment, node, isCurrentNode) {\n if (segment.tag !== '*' && segment.tag !== node.tag) {\n return false;\n }\n\n if (segment.namespace !== undefined) {\n if (segment.namespace !== '*' && segment.namespace !== node.namespace) {\n return false;\n }\n }\n\n if (segment.attrName !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n if (!node.values || !(segment.attrName in node.values)) {\n return false;\n }\n\n if (segment.attrValue !== undefined) {\n if (String(node.values[segment.attrName]) !== String(segment.attrValue)) {\n return false;\n }\n }\n }\n\n if (segment.position !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n const counter = node.counter ?? 0;\n\n if (segment.position === 'first' && counter !== 0) {\n return false;\n } else if (segment.position === 'odd' && counter % 2 !== 1) {\n return false;\n } else if (segment.position === 'even' && counter % 2 !== 0) {\n return false;\n } else if (segment.position === 'nth' && counter !== segment.positionValue) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this);\n }\n\n /**\n * Create a snapshot of current state.\n * @returns {Object}\n */\n snapshot() {\n return {\n path: this.path.map(node => ({ ...node })),\n siblingStacks: this.siblingStacks.map(map => new Map(map))\n };\n }\n\n /**\n * Restore state from snapshot.\n * @param {Object} snapshot\n */\n restore(snapshot) {\n this._pathStringCache = null;\n this.path = snapshot.path.map(node => ({ ...node }));\n this.siblingStacks = snapshot.siblingStacks.map(map => new Map(map));\n }\n\n /**\n * Return the read-only {@link MatcherView} for this matcher.\n *\n * The same instance is returned on every call — no allocation occurs.\n * It always reflects the current parser state and is safe to pass to\n * user callbacks without risk of accidental mutation.\n *\n * @returns {MatcherView}\n *\n * @example\n * const view = matcher.readOnly();\n * // pass view to callbacks — it stays in sync automatically\n * view.matches(expr); // ✓\n * view.getCurrentTag(); // ✓\n * // view.push(...) // ✗ method does not exist — caught by TypeScript\n */\n readOnly() {\n return this._view;\n }\n}","import { Expression, Matcher } from 'path-expression-matcher';\n\nconst EOL = \"\\n\";\n\n/**\n * \n * @param {array} jArray \n * @param {any} options \n * @returns \n */\nexport default function toXml(jArray, options) {\n let indentation = \"\";\n if (options.format && options.indentBy.length > 0) {\n indentation = EOL;\n }\n\n // Pre-compile stopNode expressions for pattern matching\n const stopNodeExpressions = [];\n if (options.stopNodes && Array.isArray(options.stopNodes)) {\n for (let i = 0; i < options.stopNodes.length; i++) {\n const node = options.stopNodes[i];\n if (typeof node === 'string') {\n stopNodeExpressions.push(new Expression(node));\n } else if (node instanceof Expression) {\n stopNodeExpressions.push(node);\n }\n }\n }\n\n // Initialize matcher for path tracking\n const matcher = new Matcher();\n\n return arrToStr(jArray, options, indentation, matcher, stopNodeExpressions);\n}\n\nfunction arrToStr(arr, options, indentation, matcher, stopNodeExpressions) {\n let xmlStr = \"\";\n let isPreviousElementTag = false;\n\n if (options.maxNestedTags && matcher.getDepth() > options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n\n if (!Array.isArray(arr)) {\n // Non-array values (e.g. string tag values) should be treated as text content\n if (arr !== undefined && arr !== null) {\n let text = arr.toString();\n text = replaceEntitiesValue(text, options);\n return text;\n }\n return \"\";\n }\n\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const tagName = propName(tagObj);\n if (tagName === undefined) continue;\n\n // Extract attributes from \":@\" property\n const attrValues = extractAttributeValues(tagObj[\":@\"], options);\n\n // Push tag to matcher WITH attributes\n matcher.push(tagName, attrValues);\n\n // Check if this is a stop node using Expression matching\n const isStopNode = checkStopNode(matcher, stopNodeExpressions);\n\n if (tagName === options.textNodeName) {\n let tagText = tagObj[tagName];\n if (!isStopNode) {\n tagText = options.tagValueProcessor(tagName, tagText);\n tagText = replaceEntitiesValue(tagText, options);\n }\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += tagText;\n isPreviousElementTag = false;\n matcher.pop();\n continue;\n } else if (tagName === options.cdataPropName) {\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n const val = tagObj[tagName][0][options.textNodeName];\n const safeVal = String(val).replace(/\\]\\]>/g, ']]]]>');\n xmlStr += ``;\n isPreviousElementTag = false;\n matcher.pop();\n continue;\n } else if (tagName === options.commentPropName) {\n const val = tagObj[tagName][0][options.textNodeName]\n const safeVal = String(val)\n .replace(/--/g, '- -') // -- is illegal anywhere in comment content\n .replace(/-$/, '- '); // trailing - would form -- with the closing -->\n xmlStr += indentation + ``;\n isPreviousElementTag = true;\n matcher.pop();\n continue;\n } else if (tagName[0] === \"?\") {\n const attStr = attr_to_str(tagObj[\":@\"], options, isStopNode);\n const tempInd = tagName === \"?xml\" ? \"\" : indentation;\n let piTextNodeName = tagObj[tagName][0][options.textNodeName];\n piTextNodeName = piTextNodeName.length !== 0 ? \" \" + piTextNodeName : \"\"; //remove extra spacing\n xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;\n isPreviousElementTag = true;\n matcher.pop();\n continue;\n }\n\n let newIdentation = indentation;\n if (newIdentation !== \"\") {\n newIdentation += options.indentBy;\n }\n\n // Pass isStopNode to attr_to_str so attributes are also not processed for stopNodes\n const attStr = attr_to_str(tagObj[\":@\"], options, isStopNode);\n const tagStart = indentation + `<${tagName}${attStr}`;\n\n // If this is a stopNode, get raw content without processing\n let tagValue;\n if (isStopNode) {\n tagValue = getRawContent(tagObj[tagName], options);\n } else {\n\n tagValue = arrToStr(tagObj[tagName], options, newIdentation, matcher, stopNodeExpressions);\n }\n\n if (options.unpairedTags.indexOf(tagName) !== -1) {\n if (options.suppressUnpairedNode) xmlStr += tagStart + \">\";\n else xmlStr += tagStart + \"/>\";\n } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {\n xmlStr += tagStart + \"/>\";\n } else if (tagValue && tagValue.endsWith(\">\")) {\n xmlStr += tagStart + `>${tagValue}${indentation}`;\n } else {\n xmlStr += tagStart + \">\";\n if (tagValue && indentation !== \"\" && (tagValue.includes(\"/>\") || tagValue.includes(\"`;\n }\n isPreviousElementTag = true;\n\n // Pop tag from matcher\n matcher.pop();\n }\n\n return xmlStr;\n}\n\n/**\n * Extract attribute values from the \":@\" object and return as plain object\n * for passing to matcher.push()\n */\nfunction extractAttributeValues(attrMap, options) {\n if (!attrMap || options.ignoreAttributes) return null;\n\n const attrValues = {};\n let hasAttrs = false;\n\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n // Remove the attribute prefix to get clean attribute name\n const cleanAttrName = attr.startsWith(options.attributeNamePrefix)\n ? attr.substr(options.attributeNamePrefix.length)\n : attr;\n attrValues[cleanAttrName] = attrMap[attr];\n hasAttrs = true;\n }\n\n return hasAttrs ? attrValues : null;\n}\n\n/**\n * Extract raw content from a stopNode without any processing\n * This preserves the content exactly as-is, including special characters\n */\nfunction getRawContent(arr, options) {\n if (!Array.isArray(arr)) {\n // Non-array values return as-is\n if (arr !== undefined && arr !== null) {\n return arr.toString();\n }\n return \"\";\n }\n\n let content = \"\";\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n const tagName = propName(item);\n\n if (tagName === options.textNodeName) {\n // Raw text content - NO processing, NO entity replacement\n content += item[tagName];\n } else if (tagName === options.cdataPropName) {\n // CDATA content\n content += item[tagName][0][options.textNodeName];\n } else if (tagName === options.commentPropName) {\n // Comment content\n content += item[tagName][0][options.textNodeName];\n } else if (tagName && tagName[0] === \"?\") {\n // Processing instruction - skip for stopNodes\n continue;\n } else if (tagName) {\n // Nested tags within stopNode\n // Recursively get raw content and reconstruct the tag\n // For stopNodes, we don't process attributes either\n const attStr = attr_to_str_raw(item[\":@\"], options);\n const nestedContent = getRawContent(item[tagName], options);\n\n if (!nestedContent || nestedContent.length === 0) {\n content += `<${tagName}${attStr}/>`;\n } else {\n content += `<${tagName}${attStr}>${nestedContent}`;\n }\n }\n }\n return content;\n}\n\n/**\n * Build attribute string for stopNodes - NO entity replacement\n */\nfunction attr_to_str_raw(attrMap, options) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n // For stopNodes, use raw value without processing\n let attrVal = attrMap[attr];\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${attrVal}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n if (key !== \":@\") return key;\n }\n}\n\nfunction attr_to_str(attrMap, options, isStopNode) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n let attrVal;\n\n if (isStopNode) {\n // For stopNodes, use raw value without any processing\n attrVal = attrMap[attr];\n } else {\n // Normal processing: apply attributeValueProcessor and entity replacement\n attrVal = options.attributeValueProcessor(attr, attrMap[attr]);\n attrVal = replaceEntitiesValue(attrVal, options);\n }\n\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${attrVal}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction checkStopNode(matcher, stopNodeExpressions) {\n if (!stopNodeExpressions || stopNodeExpressions.length === 0) return false;\n\n for (let i = 0; i < stopNodeExpressions.length; i++) {\n if (matcher.matches(stopNodeExpressions[i])) {\n return true;\n }\n }\n return false;\n}\n\nfunction replaceEntitiesValue(textValue, options) {\n if (textValue && textValue.length > 0 && options.processEntities) {\n for (let i = 0; i < options.entities.length; i++) {\n const entity = options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}\n\nfunction cdataVal(val) {\n\n}\n\nfunction commentVal(val) {\n\n}","'use strict';\n//parse Empty Node as self closing node\nimport buildFromOrderedJs from './orderedJs2Xml.js';\nimport getIgnoreAttributesFn from \"./ignoreAttributes.js\";\nimport { Expression, Matcher } from 'path-expression-matcher';\n\nconst defaultOptions = {\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n cdataPropName: false,\n format: false,\n indentBy: ' ',\n suppressEmptyNode: false,\n suppressUnpairedNode: true,\n suppressBooleanAttributes: true,\n tagValueProcessor: function (key, a) {\n return a;\n },\n attributeValueProcessor: function (attrName, a) {\n return a;\n },\n preserveOrder: false,\n commentPropName: false,\n unpairedTags: [],\n entities: [\n { regex: new RegExp(\"&\", \"g\"), val: \"&\" },//it must be on top\n { regex: new RegExp(\">\", \"g\"), val: \">\" },\n { regex: new RegExp(\"<\", \"g\"), val: \"<\" },\n { regex: new RegExp(\"\\'\", \"g\"), val: \"'\" },\n { regex: new RegExp(\"\\\"\", \"g\"), val: \""\" }\n ],\n processEntities: true,\n stopNodes: [],\n // transformTagName: false,\n // transformAttributeName: false,\n oneListGroup: false,\n maxNestedTags: 100,\n jPath: true // When true, callbacks receive string jPath; when false, receive Matcher instance\n};\n\nexport default function Builder(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n // Convert old-style stopNodes for backward compatibility\n // Old syntax: \"*.tag\" meant \"tag anywhere in tree\"\n // New syntax: \"..tag\" means \"tag anywhere in tree\"\n if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {\n this.options.stopNodes = this.options.stopNodes.map(node => {\n if (typeof node === 'string' && node.startsWith('*.')) {\n // Convert old wildcard syntax to deep wildcard\n return '..' + node.substring(2);\n }\n return node;\n });\n }\n\n // Pre-compile stopNode expressions for pattern matching\n this.stopNodeExpressions = [];\n if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {\n for (let i = 0; i < this.options.stopNodes.length; i++) {\n const node = this.options.stopNodes[i];\n if (typeof node === 'string') {\n this.stopNodeExpressions.push(new Expression(node));\n } else if (node instanceof Expression) {\n this.stopNodeExpressions.push(node);\n }\n }\n }\n\n if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {\n this.isAttribute = function (/*a*/) {\n return false;\n };\n } else {\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.attrPrefixLen = this.options.attributeNamePrefix.length;\n this.isAttribute = isAttribute;\n }\n\n this.processTextOrObjNode = processTextOrObjNode\n\n if (this.options.format) {\n this.indentate = indentate;\n this.tagEndChar = '>\\n';\n this.newLine = '\\n';\n } else {\n this.indentate = function () {\n return '';\n };\n this.tagEndChar = '>';\n this.newLine = '';\n }\n}\n\nBuilder.prototype.build = function (jObj) {\n if (this.options.preserveOrder) {\n return buildFromOrderedJs(jObj, this.options);\n } else {\n if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {\n jObj = {\n [this.options.arrayNodeName]: jObj\n }\n }\n // Initialize matcher for path tracking\n const matcher = new Matcher();\n return this.j2x(jObj, 0, matcher).val;\n }\n};\n\nBuilder.prototype.j2x = function (jObj, level, matcher) {\n let attrStr = '';\n let val = '';\n if (this.options.maxNestedTags && matcher.getDepth() >= this.options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n // Get jPath based on option: string for backward compatibility, or Matcher for new features\n const jPath = this.options.jPath ? matcher.toString() : matcher;\n\n // Check if current node is a stopNode (will be used for attribute encoding)\n const isCurrentStopNode = this.checkStopNode(matcher);\n\n for (let key in jObj) {\n if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;\n if (typeof jObj[key] === 'undefined') {\n // supress undefined node only if it is not an attribute\n if (this.isAttribute(key)) {\n val += '';\n }\n } else if (jObj[key] === null) {\n // null attribute should be ignored by the attribute list, but should not cause the tag closing\n if (this.isAttribute(key)) {\n val += '';\n } else if (key === this.options.cdataPropName) {\n val += '';\n } else if (key[0] === '?') {\n val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n }\n // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n } else if (jObj[key] instanceof Date) {\n val += this.buildTextValNode(jObj[key], key, '', level, matcher);\n } else if (typeof jObj[key] !== 'object') {\n //premitive type\n const attr = this.isAttribute(key);\n if (attr && !this.ignoreAttributesFn(attr, jPath)) {\n attrStr += this.buildAttrPairStr(attr, '' + jObj[key], isCurrentStopNode);\n } else if (!attr) {\n //tag value\n if (key === this.options.textNodeName) {\n let newval = this.options.tagValueProcessor(key, '' + jObj[key]);\n val += this.replaceEntitiesValue(newval);\n } else {\n // Check if this is a stopNode before building\n matcher.push(key);\n const isStopNode = this.checkStopNode(matcher);\n matcher.pop();\n\n if (isStopNode) {\n // Build as raw content without encoding\n const textValue = '' + jObj[key];\n if (textValue === '') {\n val += this.indentate(level) + '<' + key + this.closeTag(key) + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + key + '>' + textValue + '' + textValue + '${item}`;\n } else if (typeof item === 'object' && item !== null) {\n const nestedContent = this.buildRawContent(item);\n const nestedAttrs = this.buildAttributesForStopNode(item);\n if (nestedContent === '') {\n content += `<${key}${nestedAttrs}/>`;\n } else {\n content += `<${key}${nestedAttrs}>${nestedContent}`;\n }\n }\n }\n } else if (typeof value === 'object' && value !== null) {\n // Nested object\n const nestedContent = this.buildRawContent(value);\n const nestedAttrs = this.buildAttributesForStopNode(value);\n if (nestedContent === '') {\n content += `<${key}${nestedAttrs}/>`;\n } else {\n content += `<${key}${nestedAttrs}>${nestedContent}`;\n }\n } else {\n // Primitive value\n content += `<${key}>${value}`;\n }\n }\n\n return content;\n};\n\n// Build attribute string for stopNode (no entity encoding)\nBuilder.prototype.buildAttributesForStopNode = function (obj) {\n if (!obj || typeof obj !== 'object') return '';\n\n let attrStr = '';\n\n // Check for attributesGroupName (when attributes are grouped)\n if (this.options.attributesGroupName && obj[this.options.attributesGroupName]) {\n const attrGroup = obj[this.options.attributesGroupName];\n for (let attrKey in attrGroup) {\n if (!Object.prototype.hasOwnProperty.call(attrGroup, attrKey)) continue;\n const cleanKey = attrKey.startsWith(this.options.attributeNamePrefix)\n ? attrKey.substring(this.options.attributeNamePrefix.length)\n : attrKey;\n const val = attrGroup[attrKey];\n if (val === true && this.options.suppressBooleanAttributes) {\n attrStr += ' ' + cleanKey;\n } else {\n attrStr += ' ' + cleanKey + '=\"' + val + '\"'; // No encoding for stopNode\n }\n }\n } else {\n // Look for individual attributes\n for (let key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n const attr = this.isAttribute(key);\n if (attr) {\n const val = obj[key];\n if (val === true && this.options.suppressBooleanAttributes) {\n attrStr += ' ' + attr;\n } else {\n attrStr += ' ' + attr + '=\"' + val + '\"'; // No encoding for stopNode\n }\n }\n }\n }\n\n return attrStr;\n};\n\nBuilder.prototype.buildObjectNode = function (val, key, attrStr, level) {\n if (val === \"\") {\n if (key[0] === \"?\") return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n else {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n }\n } else {\n\n let tagEndExp = '' + val + tagEndExp);\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {\n return this.indentate(level) + `` + this.newLine;\n } else {\n return (\n this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +\n val +\n this.indentate(level) + tagEndExp);\n }\n }\n}\n\nBuilder.prototype.closeTag = function (key) {\n let closeTag = \"\";\n if (this.options.unpairedTags.indexOf(key) !== -1) { //unpaired\n if (!this.options.suppressUnpairedNode) closeTag = \"/\"\n } else if (this.options.suppressEmptyNode) { //empty\n closeTag = \"/\";\n } else {\n closeTag = `>/g, ']]]]>');\n return this.indentate(level) + `` + this.newLine;\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName) {\n const safeVal = String(val)\n .replace(/--/g, '- -') // -- is illegal anywhere in comment content\n .replace(/-$/, '- '); // trailing - would form -- with the closing -->\n return this.indentate(level) + `` + this.newLine;\n } else if (key[0] === \"?\") {//PI tag\n return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n } else {\n // Normal processing: apply tagValueProcessor and entity replacement\n let textValue = this.options.tagValueProcessor(key, val);\n textValue = this.replaceEntitiesValue(textValue);\n\n if (textValue === '') {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n } else {\n return this.indentate(level) + '<' + key + attrStr + '>' +\n textValue +\n ' 0 && this.options.processEntities) {\n for (let i = 0; i < this.options.entities.length; i++) {\n const entity = this.options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}\n\nfunction indentate(level) {\n return this.options.indentBy.repeat(level);\n}\n\nfunction isAttribute(name /*, options*/) {\n if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {\n return name.substr(this.attrPrefixLen);\n } else {\n return false;\n }\n}","export default function getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}","// Re-export from fast-xml-builder for backward compatibility\nimport XMLBuilder from 'fast-xml-builder';\nexport default XMLBuilder;\n\n// If there are any named exports you also want to re-export:\nexport * from 'fast-xml-builder';"],"names":["root","factory","exports","module","define","amd","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","Expression","constructor","pattern","options","data","separator","segments","_parse","_hasDeepWildcard","some","seg","type","_hasAttributeCondition","undefined","attrName","_hasPositionSelector","position","i","currentPart","length","trim","push","_parseSegment","part","segment","bracketContent","withoutBrackets","bracketMatch","match","content","slice","namespace","tag","tagAndPosition","includes","nsIndex","indexOf","substring","Error","positionMatch","colonIndex","lastIndexOf","tagPart","posPart","test","eqIndex","attrValue","nthMatch","positionValue","parseInt","hasDeepWildcard","hasAttributeCondition","hasPositionSelector","toString","MatcherView","matcher","_matcher","getCurrentTag","path","getCurrentNamespace","getAttrValue","values","hasAttr","current","getPosition","getCounter","counter","getIndex","getDepth","includeNamespace","toArray","map","n","matches","expression","matchesAny","exprSet","Matcher","siblingStacks","_pathStringCache","_view","tagName","attrValues","currentLevel","Map","siblings","siblingKey","count","set","node","pop","updateCurrent","sep","result","join","reset","_matchWithDeepWildcard","_matchSimple","_matchSegment","pathIdx","segIdx","nextSeg","found","isCurrentNode","String","snapshot","restore","readOnly","toXml","jArray","indentation","format","indentBy","stopNodeExpressions","stopNodes","Array","isArray","arrToStr","arr","xmlStr","isPreviousElementTag","maxNestedTags","text","replaceEntitiesValue","tagObj","propName","extractAttributeValues","isStopNode","checkStopNode","textNodeName","tagText","tagValueProcessor","cdataPropName","val","replace","commentPropName","attStr","attr_to_str","tempInd","piTextNodeName","newIdentation","tagStart","tagValue","getRawContent","unpairedTags","suppressUnpairedNode","suppressEmptyNode","endsWith","attrMap","ignoreAttributes","hasAttrs","attr","startsWith","attributeNamePrefix","substr","item","attr_to_str_raw","nestedContent","attrStr","attrVal","suppressBooleanAttributes","keys","attributeValueProcessor","textValue","processEntities","entities","entity","regex","defaultOptions","attributesGroupName","a","preserveOrder","RegExp","oneListGroup","jPath","Builder","assign","isAttribute","ignoreAttributesFn","attrPrefixLen","processTextOrObjNode","indentate","tagEndChar","newLine","object","level","extractAttributes","rawContent","buildRawContent","buildAttributesForStopNode","buildObjectNode","j2x","buildTextValNode","repeat","name","build","jObj","buildFromOrderedJs","arrayNodeName","isCurrentStopNode","Date","buildAttrPairStr","newval","closeTag","arrLen","listTagVal","listTagAttr","j","Ks","L","attrGroup","attrKey","nestedAttrs","cleanKey","tagEndExp","piClosingChar","safeVal"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/lib/fxp.cjs b/node_modules/fast-xml-parser/lib/fxp.cjs new file mode 100644 index 0000000..65cde85 --- /dev/null +++ b/node_modules/fast-xml-parser/lib/fxp.cjs @@ -0,0 +1 @@ +(()=>{"use strict";var t={d:(e,n)=>{for(var i in n)t.o(n,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:n[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{XMLBuilder:()=>Bt,XMLParser:()=>Tt,XMLValidator:()=>Ut});const n=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",i=new RegExp("^["+n+"]["+n+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function s(t,e){const n=[];let i=e.exec(t);for(;i;){const s=[];s.startIndex=e.lastIndex-i[0].length;const r=i.length;for(let t=0;t"!==t[r]&&" "!==t[r]&&"\t"!==t[r]&&"\n"!==t[r]&&"\r"!==t[r];r++)h+=t[r];if(h=h.trim(),"/"===h[h.length-1]&&(h=h.substring(0,h.length-1),r--),!E(h)){let e;return e=0===h.trim().length?"Invalid space after '<'.":"Tag '"+h+"' is an invalid name.",b("InvalidTag",e,w(t,r))}const l=g(t,r);if(!1===l)return b("InvalidAttr","Attributes for '"+h+"' have open quote.",w(t,r));let d=l.value;if(r=l.index,"/"===d[d.length-1]){const n=r-d.length;d=d.substring(0,d.length-1);const s=x(d,e);if(!0!==s)return b(s.err.code,s.err.msg,w(t,n+s.err.line));i=!0}else if(a){if(!l.tagClosed)return b("InvalidTag","Closing tag '"+h+"' doesn't have proper closing.",w(t,r));if(d.trim().length>0)return b("InvalidTag","Closing tag '"+h+"' can't have attributes or invalid starting.",w(t,o));if(0===n.length)return b("InvalidTag","Closing tag '"+h+"' has not been opened.",w(t,o));{const e=n.pop();if(h!==e.tagName){let n=w(t,e.tagStartPos);return b("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+h+"'.",w(t,o))}0==n.length&&(s=!0)}}else{const a=x(d,e);if(!0!==a)return b(a.err.code,a.err.msg,w(t,r-d.length+a.err.line));if(!0===s)return b("InvalidXml","Multiple possible root nodes found.",w(t,r));-1!==e.unpairedTags.indexOf(h)||n.push({tagName:h,tagStartPos:o}),i=!0}for(r++;r0)||b("InvalidXml","Invalid '"+JSON.stringify(n.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):b("InvalidXml","Start tag expected.",1)}function u(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function p(t,e){const n=e;for(;e5&&"xml"===i)return b("InvalidXml","XML declaration allowed only at the start of the document.",w(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function c(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let n=1;for(e+=8;e"===t[e]&&(n--,0===n))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}const d='"',f="'";function g(t,e){let n="",i="",s=!1;for(;e"===t[e]&&""===i){s=!0;break}n+=t[e]}return""===i&&{value:n,index:e,tagClosed:s}}const m=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function x(t,e){const n=s(t,m),i={};for(let t=0;to.includes(t)?"__"+t:t,_={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:S};function A(t,e){if("string"!=typeof t)return;const n=t.toLowerCase();if(o.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);if(a.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`)}function T(t,e){return"boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:"object"==typeof t&&null!==t?{enabled:!1!==t.enabled,maxEntitySize:Math.max(1,t.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,t.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,t.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,t.maxExpandedLength??1e5),maxEntityCount:Math.max(1,t.maxEntityCount??1e3),allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null,appliesTo:t.appliesTo??"all"}:T(!0)}const C=function(t){const e=Object.assign({},_,t),n=[{value:e.attributeNamePrefix,name:"attributeNamePrefix"},{value:e.attributesGroupName,name:"attributesGroupName"},{value:e.textNodeName,name:"textNodeName"},{value:e.cdataPropName,name:"cdataPropName"},{value:e.commentPropName,name:"commentPropName"}];for(const{value:t,name:e}of n)t&&A(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=S),e.processEntities=T(e.processEntities,e.htmlEntities),e.unpairedTagsSet=new Set(e.unpairedTags),e.stopNodes&&Array.isArray(e.stopNodes)&&(e.stopNodes=e.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),e};let P;P="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class O{constructor(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null)}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][P]={startIndex:e})}static getMetaDataSymbol(){return P}}class ${constructor(t){this.suppressValidationErr=!t,this.options=t}readDocType(t,e){const n=Object.create(null);let i=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let s=1,r=!1,o=!1,a="";for(;e"===t[e]){if(o?"-"===t[e-1]&&"-"===t[e-2]&&(o=!1,s--):s--,0===s)break}else"["===t[e]?r=!0:a+=t[e];else{if(r&&D(t,"!ENTITY",e)){let s,r;if(e+=7,[s,r,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===r.indexOf("&")){if(!1!==this.options.enabled&&null!=this.options.maxEntityCount&&i>=this.options.maxEntityCount)throw new Error(`Entity count (${i+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);n[s]=r,i++}}else if(r&&D(t,"!ELEMENT",e)){e+=8;const{index:n}=this.readElementExp(t,e+1);e=n}else if(r&&D(t,"!ATTLIST",e))e+=8;else if(r&&D(t,"!NOTATION",e)){e+=9;const{index:n}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=n}else{if(!D(t,"!--",e))throw new Error("Invalid DOCTYPE");o=!0}s++,a=""}if(0!==s)throw new Error("Unclosed DOCTYPE")}return{entities:n,i:e}}readEntityExp(t,e){const n=e=I(t,e);for(;ethis.options.maxEntitySize)throw new Error(`Entity "${i}" size (${s.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[i,s,--e]}readNotationExp(t,e){const n=e=I(t,e);for(;e{for(;e0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const n=e[e.length-1];return void 0!==n.values&&t in n.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class R{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new F(this)}push(t,e=null,n=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const i=this.path.length;this.siblingStacks[i]||(this.siblingStacks[i]=new Map);const s=this.siblingStacks[i],r=n?`${n}:${t}`:t,o=s.get(r)||0;let a=0;for(const t of s.values())a+=t;s.set(r,o+1);const h={tag:t,position:a,counter:o};null!=n&&(h.namespace=n),null!=e&&(h.values=e),this.path.push(h)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const n=t||this.separator;if(n===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(n);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(n)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e=0&&e>=0;){const i=t[n];if("deep-wildcard"===i.type){if(n--,n<0)return!0;const i=t[n];let s=!1;for(let t=e;t>=0;t--)if(this._matchSegment(i,this.path[t],t===this.path.length-1)){e=t-1,n--,s=!0;break}if(!s)return!1}else{if(!this._matchSegment(i,this.path[e],e===this.path.length-1))return!1;e--,n--}}return n<0}_matchSegment(t,e,n){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!n)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!n)return!1;const i=e.counter??0;if("first"===t.position&&0!==i)return!1;if("odd"===t.position&&i%2!=1)return!1;if("even"===t.position&&i%2!=0)return!1;if("nth"===t.position&&i!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}class G{constructor(t,e={},n){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=n,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let n=0,i="";for(;n",lt:"<",quot:'"'},X={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},Y=new Set("!?\\\\/[]$%{}^&*()<>|+");function z(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(Y.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function q(...t){const e=Object.create(null);for(const n of t)if(n)for(const t of Object.keys(n)){const i=n[t];if("string"==typeof i)e[t]=i;else if(i&&"object"==typeof i&&void 0!==i.val){const n=i.val;"string"==typeof n&&(e[t]=n)}}return e}const Z="external",J="base",K="all",Q=Object.freeze({allow:0,leave:1,remove:2,throw:3}),H=new Set([9,10,13]);class tt{constructor(t={}){var e;this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitTiers=(e=this._limit.applyLimitsTo??Z)&&e!==Z?e===K?new Set([K]):e===J?new Set([J]):Array.isArray(e)?new Set(e):new Set([Z]):new Set([Z]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=q(W,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const n=function(t){if(!t)return{xmlVersion:1,onLevel:Q.allow,nullLevel:Q.remove};const e=1.1===t.xmlVersion?1.1:1,n=Q[t.onNCR]??Q.allow,i=Q[t.nullNCR]??Q.remove;return{xmlVersion:e,onLevel:n,nullLevel:Math.max(i,Q.remove)}}(t.ncr);this._ncrXmlVersion=n.xmlVersion,this._ncrOnLevel=n.onLevel,this._ncrNullLevel=n.nullLevel}setExternalEntities(t){if(t)for(const e of Object.keys(t))z(e);this._externalMap=q(t)}addExternalEntity(t,e){z(t),"string"==typeof e&&-1===e.indexOf("&")&&(this._externalMap[t]=e)}addInputEntities(t){this._totalExpansions=0,this._expandedLength=0,this._inputMap=q(t)}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=1.1===t?1.1:1}decode(t){if("string"!=typeof t||0===t.length)return t;const e=t,n=[],i=t.length;let s=0,r=0;const o=this._maxTotalExpansions>0,a=this._maxExpandedLength>0,h=o||a;for(;r=i||59!==t.charCodeAt(e)){r++;continue}const l=t.slice(r+1,e);if(0===l.length){r++;continue}let u,p;if(this._removeSet.has(l))u="",void 0===p&&(p=Z);else{if(this._leaveSet.has(l)){r++;continue}if(35===l.charCodeAt(0)){const t=this._resolveNCR(l);if(void 0===t){r++;continue}u=t,p=J}else{const t=this._resolveName(l);u=t?.value,p=t?.tier}}if(void 0!==u){if(r>s&&n.push(t.slice(s,r)),n.push(u),s=e+1,r=s,h&&this._tierCounts(p)){if(o&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(a){const t=u.length-(l.length+2);if(t>0&&(this._expandedLength+=t,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else r++}s=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!H.has(t)?Q.remove:-1}_applyNCRAction(t,e,n){switch(t){case Q.allow:return String.fromCodePoint(n);case Q.remove:return"";case Q.leave:return;case Q.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${n.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(n)}}_resolveNCR(t){const e=t.charCodeAt(1);let n;if(n=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(n)||n<0||n>1114111)return;const i=this._classifyNCR(n);if(!this._numericAllowed&&i0){const n=t.substring(0,e);if("xmlns"!==n)return n}}class it{constructor(t){var e;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=ht,this.parseTextData=st,this.resolveNameSpace=rt,this.buildAttributesMap=at,this.isItStopNode=ct,this.replaceEntitiesValue=ut,this.readStopNodeData=mt,this.saveTextToParentTag=pt,this.addChild=lt,this.ignoreAttributesFn="function"==typeof(e=this.options.ignoreAttributes)?e:Array.isArray(e)?t=>{for(const n of e){if("string"==typeof n&&t===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}}:()=>!1,this.entityExpansionCount=0,this.currentExpandedLength=0;let n={...W};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?n=this.options.htmlEntities:!0===this.options.htmlEntities&&(n={...X,...U}),this.entityDecoder=new tt({namedEntities:n,numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo}})),this.matcher=new R,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new B;const i=this.options.stopNodes;if(i&&i.length>0){for(let t=0;t0)){o||(t=this.replaceEntitiesValue(t,e,n));const i=a.jPath?n.toString():n,h=a.tagValueProcessor(e,t,i,s,r);return null==h?t:typeof h!=typeof t||h!==t?h:a.trimValues||t.trim()===t?xt(t,a.parseTagValue,a.numberParseOptions):t}}function rt(t){if(this.options.removeNSPrefix){const e=t.split(":"),n="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=n+e[1])}return t}const ot=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function at(t,e,n,i=!1){const r=this.options;if(!0===i||!0!==r.ignoreAttributes&&"string"==typeof t){const i=s(t,ot),o=i.length,a={},h=new Array(o);let l=!1;const u={};for(let t=0;t",a,"Closing Tag is not closed.");let r=t.substring(a+2,e).trim();if(s.removeNSPrefix){const t=r.indexOf(":");-1!==t&&(r=r.substr(t+1))}r=Nt(s.transformTagName,r,"",s).tagName,n&&(i=this.saveTextToParentTag(i,n,this.readonlyMatcher));const o=this.matcher.getCurrentTag();if(r&&s.unpairedTagsSet.has(r))throw new Error(`Unpaired tag can not be used as closing tag: `);o&&s.unpairedTagsSet.has(o)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,n=this.tagsNodeStack.pop(),i="",a=e}else if(63===h){let e=gt(t,a,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");i=this.saveTextToParentTag(i,n,this.readonlyMatcher);const r=this.buildAttributesMap(e.tagExp,this.matcher,e.tagName,!0);if(r){const t=r[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(t)||1)}if(s.ignoreDeclaration&&"?xml"===e.tagName||s.ignorePiTags);else{const t=new O(e.tagName);t.add(s.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&!0!==s.ignoreAttributes&&(t[":@"]=r),this.addChild(n,t,this.readonlyMatcher,a)}a=e.closeIndex+1}else if(33===h&&45===t.charCodeAt(a+2)&&45===t.charCodeAt(a+3)){const e=dt(t,"--\x3e",a+4,"Comment is not closed.");if(s.commentPropName){const r=t.substring(a+4,e-2);i=this.saveTextToParentTag(i,n,this.readonlyMatcher),n.add(s.commentPropName,[{[s.textNodeName]:r}])}a=e}else if(33===h&&68===t.charCodeAt(a+2)){const e=r.readDocType(t,a);this.entityDecoder.addInputEntities(e.entities),a=e.i}else if(33===h&&91===t.charCodeAt(a+2)){const e=dt(t,"]]>",a,"CDATA is not closed.")-2,r=t.substring(a+9,e);i=this.saveTextToParentTag(i,n,this.readonlyMatcher);let o=this.parseTextData(r,n.tagname,this.readonlyMatcher,!0,!1,!0,!0);null==o&&(o=""),s.cdataPropName?n.add(s.cdataPropName,[{[s.textNodeName]:r}]):n.add(s.textNodeName,o),a=e+2}else{let r=gt(t,a,s.removeNSPrefix);if(!r){const e=t.substring(Math.max(0,a-50),Math.min(o,a+50));throw new Error(`readTagExp returned undefined at position ${a}. Context: "${e}"`)}let h=r.tagName;const l=r.rawTagName;let u=r.tagExp,p=r.attrExpPresent,c=r.closeIndex;if(({tagName:h,tagExp:u}=Nt(s.transformTagName,h,u,s)),s.strictReservedNames&&(h===s.commentPropName||h===s.cdataPropName||h===s.textNodeName||h===s.attributesGroupName))throw new Error(`Invalid tag name: ${h}`);n&&i&&"!xml"!==n.tagname&&(i=this.saveTextToParentTag(i,n,this.readonlyMatcher,!1));const d=n;d&&s.unpairedTagsSet.has(d.tagname)&&(n=this.tagsNodeStack.pop(),this.matcher.pop());let f=!1;u.length>0&&u.lastIndexOf("/")===u.length-1&&(f=!0,"/"===h[h.length-1]?(h=h.substr(0,h.length-1),u=h):u=u.substr(0,u.length-1),p=h!==u);let g,m=null,x={};g=nt(l),h!==e.tagname&&this.matcher.push(h,{},g),h!==u&&p&&(m=this.buildAttributesMap(u,this.matcher,h),m&&(x=et(m,s))),h!==e.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());const N=a;if(this.isCurrentNodeStopNode){let e="";if(f)a=r.closeIndex;else if(s.unpairedTagsSet.has(h))a=r.closeIndex;else{const n=this.readStopNodeData(t,l,c+1);if(!n)throw new Error(`Unexpected end of ${l}`);a=n.i,e=n.tagContent}const i=new O(h);m&&(i[":@"]=m),i.add(s.textNodeName,e),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(n,i,this.readonlyMatcher,N)}else{if(f){({tagName:h,tagExp:u}=Nt(s.transformTagName,h,u,s));const t=new O(h);m&&(t[":@"]=m),this.addChild(n,t,this.readonlyMatcher,N),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else{if(s.unpairedTagsSet.has(h)){const t=new O(h);m&&(t[":@"]=m),this.addChild(n,t,this.readonlyMatcher,N),this.matcher.pop(),this.isCurrentNodeStopNode=!1,a=r.closeIndex;continue}{const t=new O(h);if(this.tagsNodeStack.length>s.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(n),m&&(t[":@"]=m),this.addChild(n,t,this.readonlyMatcher,N),n=t}}i="",a=c}}}else i+=t[a];return e.child};function lt(t,e,n,i){this.options.captureMetaData||(i=void 0);const s=this.options.jPath?n.toString():n,r=this.options.updateTag(e.tagname,s,e[":@"]);!1===r||("string"==typeof r?(e.tagname=r,t.addChild(e,i)):t.addChild(e,i))}function ut(t,e,n){const i=this.options.processEntities;if(!i||!i.enabled)return t;if(i.allowedTags){const s=this.options.jPath?n.toString():n;if(!(Array.isArray(i.allowedTags)?i.allowedTags.includes(e):i.allowedTags(e,s)))return t}if(i.tagFilter){const s=this.options.jPath?n.toString():n;if(!i.tagFilter(e,s))return t}return this.entityDecoder.decode(t)}function pt(t,e,n,i){return t&&(void 0===i&&(i=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,n,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,i))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function ct(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function dt(t,e,n,i){const s=t.indexOf(e,n);if(-1===s)throw new Error(i);return s+e.length-1}function ft(t,e,n,i){const s=t.indexOf(e,n);if(-1===s)throw new Error(i);return s}function gt(t,e,n,i=">"){const s=function(t,e,n=">"){let i=0;const s=[],r=t.length,o=n.charCodeAt(0),a=n.length>1?n.charCodeAt(1):-1;for(let n=e;n",n,`${e} is not closed`);if(t.substring(n+2,r).trim()===e&&(s--,0===s))return{tagContent:t.substring(i,n),i:r};n=r}else if(63===r)n=dt(t,"?>",n+1,"StopNode is not closed.");else if(33===r&&45===t.charCodeAt(n+2)&&45===t.charCodeAt(n+3))n=dt(t,"--\x3e",n+3,"StopNode is not closed.");else if(33===r&&91===t.charCodeAt(n+2))n=dt(t,"]]>",n,"StopNode is not closed.")-2;else{const i=gt(t,n,">");i&&((i&&i.tagName)===e&&"/"!==i.tagExp[i.tagExp.length-1]&&s++,n=i.closeIndex)}}}function xt(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},L,e),!t||"string"!=typeof t)return t;let n=t.trim();if(0===n.length)return t;if(void 0!==e.skipLike&&e.skipLike.test(n))return t;if("0"===n)return 0;if(e.hex&&j.test(n))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(n);if(isFinite(n)){if(n.includes("e")||n.includes("E"))return function(t,e,n){if(!n.eNotation)return t;const i=e.match(k);if(i){let s=i[1]||"";const r=-1===i[3].indexOf("e")?"E":"e",o=i[2],a=s?t[o.length+1]===r:t[o.length]===r;return o.length>1&&a?t:(1!==o.length||!i[3].startsWith(`.${r}`)&&i[3][0]!==r)&&o.length>0?n.leadingZeros&&!a?(e=(i[1]||"")+i[3],Number(e)):t:Number(e)}return t}(t,n,e);{const s=V.exec(n);if(s){const r=s[1]||"",o=s[2];let a=(i=s[3])&&-1!==i.indexOf(".")?("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1)),i):i;const h=r?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!h))return t;{const i=Number(n),s=String(i);if(0===i)return i;if(-1!==s.search(/[eE]/))return e.eNotation?i:t;if(-1!==n.indexOf("."))return"0"===s||s===a||s===`${r}${a}`?i:t;let h=o?a:n;return o?h===s||r+h===s?i:t:h===s||h===r+s?i:t}}return t}}var i;return function(t,e,n){const i=e===1/0;switch(n.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return i?"Infinity":"-Infinity";default:return t}}(t,Number(n),e)}(t,n)}return void 0!==t?t:""}function Nt(t,e,n,i){if(t){const i=t(e);n===e&&(n=i),e=i}return{tagName:e=bt(e,i),tagExp:n}}function bt(t,e){if(a.includes(t))throw new Error(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);return o.includes(t)?e.onDangerousProperty(t):t}const yt=O.getMetaDataSymbol();function Et(t,e){if(!t||"object"!=typeof t)return{};if(!e)return t;const n={};for(const i in t)i.startsWith(e)?n[i.substring(e.length)]=t[i]:n[i]=t[i];return n}function wt(t,e,n,i){return vt(t,e,n,i)}function vt(t,e,n,i){let s;const r={};for(let o=0;o0&&(r[e.textNodeName]=s):void 0!==s&&(r[e.textNodeName]=s),r}function St(t){const e=Object.keys(t);for(let t=0;t0&&(n="\n");const i=[];if(e.stopNodes&&Array.isArray(e.stopNodes))for(let t=0;te.maxNestedTags)throw new Error("Maximum nested tags exceeded");if(!Array.isArray(t)){if(null!=t){let n=t.toString();return n=Vt(n,e),n}return""}for(let a=0;a/g,"]]]]>")}]]>`,o=!1,i.pop();continue}if(l===e.commentPropName){const t=h[l][0][e.textNodeName];r+=n+`\x3c!--${String(t).replace(/--/g,"- -").replace(/-$/,"- ")}--\x3e`,o=!0,i.pop();continue}if("?"===l[0]){const t=Mt(h[":@"],e,p),s="?xml"===l?"":n;let a=h[l][0][e.textNodeName];a=0!==a.length?" "+a:"",r+=s+`<${l}${a}${t}?>`,o=!0,i.pop();continue}let c=n;""!==c&&(c+=e.indentBy);const d=n+`<${l}${Mt(h[":@"],e,p)}`;let f;f=p?$t(h[l],e):Pt(h[l],e,c,i,s),-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?r+=d+">":r+=d+"/>":f&&0!==f.length||!e.suppressEmptyNode?f&&f.endsWith(">")?r+=d+`>${f}${n}`:(r+=d+">",f&&""!==n&&(f.includes("/>")||f.includes("`):r+=d+"/>",o=!0,i.pop()}return r}function Ot(t,e){if(!t||e.ignoreAttributes)return null;const n={};let i=!1;for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[s.startsWith(e.attributeNamePrefix)?s.substr(e.attributeNamePrefix.length):s]=t[s],i=!0);return i?n:null}function $t(t,e){if(!Array.isArray(t))return null!=t?t.toString():"";let n="";for(let i=0;i${i}`:n+=`<${r}${t}/>`}}}return n}function It(t,e){let n="";if(t&&!e.ignoreAttributes)for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i];!0===s&&e.suppressBooleanAttributes?n+=` ${i.substr(e.attributeNamePrefix.length)}`:n+=` ${i.substr(e.attributeNamePrefix.length)}="${s}"`}return n}function Dt(t){const e=Object.keys(t);for(let n=0;n0&&e.processEntities)for(let n=0;n","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1,maxNestedTags:100,jPath:!0};function kt(t){if(this.options=Object.assign({},Lt,t),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(let t=0;t{for(const n of e){if("string"==typeof n&&t===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}}:()=>!1,this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Gt),this.processTextOrObjNode=Ft,this.options.format?(this.indentate=Rt,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function Ft(t,e,n,i){const s=this.extractAttributes(t);if(i.push(e,s),this.checkStopNode(i)){const s=this.buildRawContent(t),r=this.buildAttributesForStopNode(t);return i.pop(),this.buildObjectNode(s,e,r,n)}const r=this.j2x(t,n+1,i);return i.pop(),void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,r.attrStr,n,i):this.buildObjectNode(r.val,e,r.attrStr,n)}function Rt(t){return this.options.indentBy.repeat(t)}function Gt(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}kt.prototype.build=function(t){if(this.options.preserveOrder)return Ct(t,this.options);{Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t});const e=new R;return this.j2x(t,0,e).val}},kt.prototype.j2x=function(t,e,n){let i="",s="";if(this.options.maxNestedTags&&n.getDepth()>=this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");const r=this.options.jPath?n.toString():n,o=this.checkStopNode(n);for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a))if(void 0===t[a])this.isAttribute(a)&&(s+="");else if(null===t[a])this.isAttribute(a)||a===this.options.cdataPropName?s+="":"?"===a[0]?s+=this.indentate(e)+"<"+a+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+a+"/"+this.tagEndChar;else if(t[a]instanceof Date)s+=this.buildTextValNode(t[a],a,"",e,n);else if("object"!=typeof t[a]){const h=this.isAttribute(a);if(h&&!this.ignoreAttributesFn(h,r))i+=this.buildAttrPairStr(h,""+t[a],o);else if(!h)if(a===this.options.textNodeName){let e=this.options.tagValueProcessor(a,""+t[a]);s+=this.replaceEntitiesValue(e)}else{n.push(a);const i=this.checkStopNode(n);if(n.pop(),i){const n=""+t[a];s+=""===n?this.indentate(e)+"<"+a+this.closeTag(a)+this.tagEndChar:this.indentate(e)+"<"+a+">"+n+""+t+"${t}`;else if("object"==typeof t&&null!==t){const i=this.buildRawContent(t),s=this.buildAttributesForStopNode(t);e+=""===i?`<${n}${s}/>`:`<${n}${s}>${i}`}}else if("object"==typeof i&&null!==i){const t=this.buildRawContent(i),s=this.buildAttributesForStopNode(i);e+=""===t?`<${n}${s}/>`:`<${n}${s}>${t}`}else e+=`<${n}>${i}`}return e},kt.prototype.buildAttributesForStopNode=function(t){if(!t||"object"!=typeof t)return"";let e="";if(this.options.attributesGroupName&&t[this.options.attributesGroupName]){const n=t[this.options.attributesGroupName];for(let t in n){if(!Object.prototype.hasOwnProperty.call(n,t))continue;const i=t.startsWith(this.options.attributeNamePrefix)?t.substring(this.options.attributeNamePrefix.length):t,s=n[t];!0===s&&this.options.suppressBooleanAttributes?e+=" "+i:e+=" "+i+'="'+s+'"'}}else for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const i=this.isAttribute(n);if(i){const s=t[n];!0===s&&this.options.suppressBooleanAttributes?e+=" "+i:e+=" "+i+'="'+s+'"'}}return e},kt.prototype.buildObjectNode=function(t,e,n,i){if(""===t)return"?"===e[0]?this.indentate(i)+"<"+e+n+"?"+this.tagEndChar:this.indentate(i)+"<"+e+n+this.closeTag(e)+this.tagEndChar;{let s=""+t+s}},kt.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>/g,"]]]]>");return this.indentate(i)+``+this.newLine}if(!1!==this.options.commentPropName&&e===this.options.commentPropName){const e=String(t).replace(/--/g,"- -").replace(/-$/,"- ");return this.indentate(i)+`\x3c!--${e}--\x3e`+this.newLine}if("?"===e[0])return this.indentate(i)+"<"+e+n+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(e,t);return s=this.replaceEntitiesValue(s),""===s?this.indentate(i)+"<"+e+n+this.closeTag(e)+this.tagEndChar:this.indentate(i)+"<"+e+n+">"+s+"0&&this.options.processEntities)for(let e=0;e + * @updated + * + * Update this file when path-expression-matcher releases a new version. + * Source: https://github.com/NaturalIntelligence/path-expression-matcher + */ + +/** + * Options for creating an Expression + */ +interface ExpressionOptions { + /** + * Path separator character + * @default '.' + */ + separator?: string; +} + +/** + * Parsed segment from an expression pattern + */ +interface Segment { + type: 'tag' | 'deep-wildcard'; + tag?: string; + namespace?: string; + attrName?: string; + attrValue?: string; + position?: 'first' | 'last' | 'odd' | 'even' | 'nth'; + positionValue?: number; +} + +/** + * Expression - Parses and stores a tag pattern expression. + * Patterns are parsed once and stored in an optimized structure for fast matching. + * + * @example + * ```typescript + * const expr = new Expression("root.users.user"); + * const expr2 = new Expression("..user[id]:first"); + * const expr3 = new Expression("root/users/user", { separator: '/' }); + * ``` + * + * Pattern Syntax: + * - `root.users.user` — Match exact path + * - `..user` — Match "user" at any depth (deep wildcard) + * - `user[id]` — Match user tag with "id" attribute + * - `user[id=123]` — Match user tag where id="123" + * - `user:first` — Match first occurrence of user tag + * - `ns::user` — Match user tag with namespace "ns" + * - `ns::user[id]:first` — Combine namespace, attribute, and position + */ +declare class Expression { + readonly pattern: string; + readonly separator: string; + readonly segments: Segment[]; + + constructor(pattern: string, options?: ExpressionOptions); + + get length(): number; + hasDeepWildcard(): boolean; + hasAttributeCondition(): boolean; + hasPositionSelector(): boolean; + toString(): string; +} + +// --------------------------------------------------------------------------- +// MatcherView +// --------------------------------------------------------------------------- + +/** + * A lightweight, live read-only view of a Matcher instance. + * + * Returned by `Matcher.readOnly()`. The same instance is reused across every + * callback invocation — no allocation overhead per call. Reads directly from + * the parent Matcher's internal state so it always reflects the current parser + * position with no copying or freezing. + * + * Mutation methods (`push`, `pop`, `reset`, `updateCurrent`, `restore`) are + * simply absent — misuse is caught at compile time by TypeScript. + * + * This is the type received by all FXP user callbacks when `jPath: false`. + */ +interface MatcherView { + readonly separator: string; + + /** Check if current path matches an Expression. */ + matches(expression: Expression): boolean; + + /** Get current tag name, or `undefined` if path is empty. */ + getCurrentTag(): string | undefined; + + /** Get current namespace, or `undefined` if not present. */ + getCurrentNamespace(): string | undefined; + + /** Get attribute value of the current node. */ + getAttrValue(attrName: string): any; + + /** Check if the current node has a given attribute. */ + hasAttr(attrName: string): boolean; + + /** Sibling position of the current node (child index in parent). */ + getPosition(): number; + + /** Occurrence counter of the current tag name at this level. */ + getCounter(): number; + + /** Number of nodes in the current path. */ + getDepth(): number; + + /** Current path as a string (e.g. `"root.users.user"`). */ + toString(separator?: string, includeNamespace?: boolean): string; + + /** Current path as an array of tag names. */ + toArray(): string[]; + + /** + * Create a snapshot of the current state. + * The snapshot can be passed to the real Matcher.restore() if needed. + */ + snapshot(): MatcherSnapshot; +} + +/** + * @deprecated Use {@link MatcherView} instead. + * Alias kept for backward compatibility. + */ +type ReadonlyMatcher = MatcherView; + +/** Internal node structure — exposed via snapshot only. */ +interface PathNode { + tag: string; + namespace?: string; + position: number; + counter: number; + values?: Record; +} + +/** Snapshot of matcher state returned by `snapshot()` and `readOnly().snapshot()`. */ +interface MatcherSnapshot { + path: PathNode[]; + siblingStacks: Map[]; +} + +/********************************************************************** + * + * END of path-expression-matcher relevant typings + * + **********************************************************************/ + + + +// jPath: true → string +// jPath: false → MatcherView +type JPathOrMatcher = string | MatcherView; +type JPathOrExpression = string | Expression; + +type ProcessEntitiesOptions = { + /** + * Whether to enable entity processing + * + * Defaults to `true` + */ + enabled?: boolean; + + /** + * Maximum size in characters for a single entity definition + * + * Defaults to `10000` + */ + maxEntitySize?: number; + + /** + * Maximum depth for nested entity references (reserved for future use) + * + * Defaults to `10` + */ + maxExpansionDepth?: number; + + /** + * Maximum total number of entity expansions allowed + * + * Defaults to `1000` + */ + maxTotalExpansions?: number; + + /** + * Maximum total expanded content length in characters + * + * Defaults to `100000` + */ + maxExpandedLength?: number; + + /** + * Maximum number of entities allowed in the XML + * + * Defaults to `100` + */ + maxEntityCount?: number; + + /** + * Array of tag names where entity replacement is allowed. + * If null, entities are replaced in all tags. + * + * Defaults to `null` + */ + allowedTags?: string[] | null; + + /** + * Custom filter function to determine if entities should be replaced in a tag + * + * @param tagName - The name of the current tag + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @returns `true` to allow entity replacement, `false` to skip + * + * Defaults to `null` + */ + tagFilter?: ((tagName: string, jPathOrMatcher: JPathOrMatcher) => boolean) | null; +}; + +type EntityDecoderOptions = { + setExternalEntities: (entities: Record) => void; + addInputEntities: (entities: Record) => void; + reset: () => void; + decode: (text: string) => string; + setXmlVersion: (version: string) => void; +} + +type X2jOptions = { + /** + * Preserve the order of tags in resulting JS object + * + * Defaults to `false` + */ + preserveOrder?: boolean; + + /** + * Give a prefix to the attribute name in the resulting JS object + * + * Defaults to '@_' + */ + attributeNamePrefix?: string; + + /** + * A name to group all attributes of a tag under, or `false` to disable + * + * Defaults to `false` + */ + attributesGroupName?: false | string; + + /** + * The name of the next node in the resulting JS + * + * Defaults to `#text` + */ + textNodeName?: string; + + /** + * Whether to ignore attributes when parsing + * + * When `true` - ignores all the attributes + * + * When `false` - parses all the attributes + * + * When `Array` - filters out attributes that match provided patterns + * + * When `Function` - calls the function for each attribute and filters out those for which the function returned `true` + * + * Defaults to `true` + */ + ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPathOrMatcher: JPathOrMatcher) => boolean); + + /** + * Whether to remove namespace string from tag and attribute names + * + * Defaults to `false` + */ + removeNSPrefix?: boolean; + + /** + * Whether to allow attributes without value + * + * Defaults to `false` + */ + allowBooleanAttributes?: boolean; + + /** + * Whether to parse tag value with `strnum` package + * + * Defaults to `true` + */ + parseTagValue?: boolean; + + /** + * Whether to parse attribute value with `strnum` package + * + * Defaults to `false` + */ + parseAttributeValue?: boolean; + + /** + * Whether to remove surrounding whitespace from tag or attribute value + * + * Defaults to `true` + */ + trimValues?: boolean; + + /** + * Give a property name to set CDATA values to instead of merging to tag's text value + * + * Defaults to `false` + */ + cdataPropName?: false | string; + + /** + * If set, parse comments and set as this property + * + * Defaults to `false` + */ + commentPropName?: false | string; + + /** + * Control how tag value should be parsed. Called only if tag value is not empty + * + * @param tagName - The name of the tag + * @param tagValue - The value of the tag + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @param hasAttributes - Whether the tag has attributes + * @param isLeafNode - Whether the tag is a leaf node + * @returns {undefined|null} `undefined` or `null` to set original value. + * @returns {unknown} + * + * 1. Different value or value with different data type to set new value. + * 2. Same value to set parsed value if `parseTagValue: true`. + * + * Defaults to `(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode) => val` + */ + tagValueProcessor?: (tagName: string, tagValue: string, jPathOrMatcher: JPathOrMatcher, hasAttributes: boolean, isLeafNode: boolean) => unknown; + + /** + * Control how attribute value should be parsed + * + * @param attrName - The name of the attribute + * @param attrValue - The value of the attribute + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @returns {undefined|null} `undefined` or `null` to set original value + * @returns {unknown} + * + * Defaults to `(attrName, val, jPathOrMatcher) => val` + */ + attributeValueProcessor?: (attrName: string, attrValue: string, jPathOrMatcher: JPathOrMatcher) => unknown; + + /** + * Options to pass to `strnum` for parsing numbers + * + * Defaults to `{ hex: true, leadingZeros: true, eNotation: true }` + */ + numberParseOptions?: strnumOptions; + + /** + * Nodes to stop parsing at + * + * Accepts string patterns or Expression objects from path-expression-matcher + * + * String patterns starting with "*." are automatically converted to ".." for backward compatibility + * + * Defaults to `[]` + */ + stopNodes?: JPathOrExpression[]; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; + + /** + * Whether to always create a text node + * + * Defaults to `false` + */ + alwaysCreateTextNode?: boolean; + + /** + * Determine whether a tag should be parsed as an array + * + * @param tagName - The name of the tag + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @param isLeafNode - Whether the tag is a leaf node + * @param isAttribute - Whether this is an attribute + * @returns {boolean} + * + * Defaults to `() => false` + */ + isArray?: (tagName: string, jPathOrMatcher: JPathOrMatcher, isLeafNode: boolean, isAttribute: boolean) => boolean; + + /** + * Whether to process default and DOCTYPE entities + * + * When `true` - enables entity processing with default limits + * + * When `false` - disables all entity processing + * + * When `ProcessEntitiesOptions` - enables entity processing with custom configuration + * + * Defaults to `true` + */ + processEntities?: boolean | ProcessEntitiesOptions; + + /** + * Whether to process HTML entities + * + * Defaults to `false` + * @deprecated Use `entityDecoder` instead + */ + htmlEntities?: boolean; + + /** + * Custom entity decoder + */ + entityDecoder?: EntityDecoderOptions; + /** + * Whether to ignore the declaration tag from output + * + * Defaults to `false` + */ + ignoreDeclaration?: boolean; + + /** + * Whether to ignore Pi tags + * + * Defaults to `false` + */ + ignorePiTags?: boolean; + + /** + * Transform tag names + * + * Defaults to `false` + */ + transformTagName?: ((tagName: string) => string) | false; + + /** + * Transform attribute names + * + * Defaults to `false` + */ + transformAttributeName?: ((attributeName: string) => string) | false; + + /** + * Change the tag name when a different name is returned. Skip the tag from parsed result when false is returned. + * Modify `attrs` object to control attributes for the given tag. + * + * @param tagName - The name of the tag + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @param attrs - The attributes object + * @returns {string} new tag name. + * @returns false to skip the tag + * + * Defaults to `(tagName, jPathOrMatcher, attrs) => tagName` + */ + updateTag?: (tagName: string, jPathOrMatcher: JPathOrMatcher, attrs: { [k: string]: string }) => string | boolean; + + /** + * If true, adds a Symbol to all object nodes, accessible by {@link XMLParser.getMetaDataSymbol} with + * metadata about each the node in the XML file. + */ + captureMetaData?: boolean; + + /** + * Maximum number of nested tags + * + * Defaults to `100` + */ + maxNestedTags?: number; + + /** + * Whether to strictly validate tag names + * + * Defaults to `true` + */ + strictReservedNames?: boolean; + + /** + * Controls whether callbacks receive jPath as string or Matcher instance + * + * When `true` - callbacks receive jPath as string (backward compatible) + * + * When `false` - callbacks receive Matcher instance for advanced pattern matching + * + * Defaults to `true` + */ + jPath?: boolean; + + /** + * Function to sanitize dangerous property names + * + * @param name - The name of the property + * @returns {string} The sanitized name + * + * Defaults to `(name) => __name` + */ + onDangerousProperty?: (name: string) => string; +}; + +type strnumOptions = { + hex: boolean; + leadingZeros: boolean, + skipLike?: RegExp, + eNotation?: boolean +} + +type validationOptions = { + /** + * Whether to allow attributes without value + * + * Defaults to `false` + */ + allowBooleanAttributes?: boolean; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; +}; + +type XmlBuilderOptions = { + /** + * Give a prefix to the attribute name in the resulting JS object + * + * Defaults to '@_' + */ + attributeNamePrefix?: string; + + /** + * A name to group all attributes of a tag under, or `false` to disable + * + * Defaults to `false` + */ + attributesGroupName?: false | string; + + /** + * The name of the next node in the resulting JS + * + * Defaults to `#text` + */ + textNodeName?: string; + + /** + * Whether to ignore attributes when building + * + * When `true` - ignores all the attributes + * + * When `false` - builds all the attributes + * + * When `Array` - filters out attributes that match provided patterns + * + * When `Function` - calls the function for each attribute and filters out those for which the function returned `true` + * + * Defaults to `true` + */ + ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean); + + /** + * Give a property name to set CDATA values to instead of merging to tag's text value + * + * Defaults to `false` + */ + cdataPropName?: false | string; + + /** + * If set, parse comments and set as this property + * + * Defaults to `false` + */ + commentPropName?: false | string; + + /** + * Whether to make output pretty instead of single line + * + * Defaults to `false` + */ + format?: boolean; + + + /** + * If `format` is set to `true`, sets the indent string + * + * Defaults to ` ` + */ + indentBy?: string; + + /** + * Give a name to a top-level array + * + * Defaults to `undefined` + */ + arrayNodeName?: string; + + /** + * Create empty tags for tags with no text value + * + * Defaults to `false` + */ + suppressEmptyNode?: boolean; + + /** + * Suppress an unpaired tag + * + * Defaults to `true` + */ + suppressUnpairedNode?: boolean; + + /** + * Don't put a value for boolean attributes + * + * Defaults to `true` + */ + suppressBooleanAttributes?: boolean; + + /** + * Preserve the order of tags in resulting JS object + * + * Defaults to `false` + */ + preserveOrder?: boolean; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; + + /** + * Nodes to stop parsing at + * + * Accepts string patterns or Expression objects from path-expression-matcher + * + * Defaults to `[]` + */ + stopNodes?: JPathOrExpression[]; + + /** + * Control how tag value should be parsed. Called only if tag value is not empty + * + * @returns {undefined|null} `undefined` or `null` to set original value. + * @returns {unknown} + * + * 1. Different value or value with different data type to set new value. + * 2. Same value to set parsed value if `parseTagValue: true`. + * + * Defaults to `(tagName, val, jPath, hasAttributes, isLeafNode) => val` + */ + tagValueProcessor?: (name: string, value: unknown) => unknown; + + /** + * Control how attribute value should be parsed + * + * @param attrName + * @param attrValue + * @param jPath + * @returns {undefined|null} `undefined` or `null` to set original value + * @returns {unknown} + * + * Defaults to `(attrName, val, jPath) => val` + */ + attributeValueProcessor?: (name: string, value: unknown) => unknown; + + /** + * Whether to process default and DOCTYPE entities + * + * Defaults to `true` + */ + processEntities?: boolean; + + + oneListGroup?: boolean; + + /** + * Maximum number of nested tags + * + * Defaults to `100` + */ + maxNestedTags?: number; +}; + +type ESchema = string | object | Array; + +type ValidationError = { + err: { + code: string; + msg: string, + line: number, + col: number + }; +}; + +declare class XMLParser { + constructor(options?: X2jOptions); + parse(xmlData: string | Uint8Array, validationOptions?: validationOptions | boolean): any; + /** + * Add Entity which is not by default supported by this library + * @param entityIdentifier {string} Eg: 'ent' for &ent; + * @param entityValue {string} Eg: '\r' + */ + addEntity(entityIdentifier: string, entityValue: string): void; + + /** + * Returns a Symbol that can be used to access the {@link XMLMetaData} + * property on a node. + * + * If Symbol is not available in the environment, an ordinary property is used + * and the name of the property is here returned. + * + * The XMLMetaData property is only present when {@link X2jOptions.captureMetaData} + * is true in the options. + */ + static getMetaDataSymbol(): Symbol; +} + +declare class XMLValidator { + static validate(xmlData: string, options?: validationOptions): true | ValidationError; +} +/** + * @deprecated Use npm package 'fast-xml-builder' instead + */ +declare class XMLBuilder { + constructor(options?: XmlBuilderOptions); + build(jObj: any): string; +} + + +/** + * This object is available on nodes via the symbol {@link XMLParser.getMetaDataSymbol} + * when {@link X2jOptions.captureMetaData} is true. + */ +declare interface XMLMetaData { + /** The index, if available, of the character where the XML node began in the input stream. */ + startIndex?: number; +} + +declare namespace fxp { + export { + XMLParser, + XMLValidator, + XMLBuilder, + XMLMetaData, + XmlBuilderOptions, + X2jOptions, + ESchema, + ValidationError, + strnumOptions, + validationOptions, + ProcessEntitiesOptions, + Expression, + ReadonlyMatcher, + MatcherView, + JPathOrMatcher, + JPathOrExpression, + EntityDecoderOptions + } +} + +export = fxp; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/lib/fxp.min.js b/node_modules/fast-xml-parser/lib/fxp.min.js new file mode 100644 index 0000000..f62f7ec --- /dev/null +++ b/node_modules/fast-xml-parser/lib/fxp.min.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.fxp=e():t.fxp=e()}(this,()=>(()=>{"use strict";var t={d:(e,r)=>{for(var i in r)t.o(r,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:r[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{XMLBuilder:()=>Wt,XMLParser:()=>Pt,XMLValidator:()=>Xt});var r=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",i=new RegExp("^["+r+"]["+r+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function n(t,e){for(var r=[],i=e.exec(t);i;){var n=[];n.startIndex=e.lastIndex-i[0].length;for(var s=i.length,a=0;a"!==t[s]&&" "!==t[s]&&"\t"!==t[s]&&"\n"!==t[s]&&"\r"!==t[s];s++)l+=t[s];if("/"===(l=l.trim())[l.length-1]&&(l=l.substring(0,l.length-1),s--),!y(l))return b("InvalidTag",0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",E(t,s));var c=g(t,s);if(!1===c)return b("InvalidAttr","Attributes for '"+l+"' have open quote.",E(t,s));var f=c.value;if(s=c.index,"/"===f[f.length-1]){var m=s-f.length,N=v(f=f.substring(0,f.length-1),e);if(!0!==N)return b(N.err.code,N.err.msg,E(t,m+N.err.line));i=!0}else if(o){if(!c.tagClosed)return b("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",E(t,s));if(f.trim().length>0)return b("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",E(t,a));if(0===r.length)return b("InvalidTag","Closing tag '"+l+"' has not been opened.",E(t,a));var w=r.pop();if(l!==w.tagName){var S=E(t,w.tagStartPos);return b("InvalidTag","Expected closing tag '"+w.tagName+"' (opened in line "+S.line+", col "+S.col+") instead of closing tag '"+l+"'.",E(t,a))}0==r.length&&(n=!0)}else{var _=v(f,e);if(!0!==_)return b(_.err.code,_.err.msg,E(t,s-f.length+_.err.line));if(!0===n)return b("InvalidXml","Multiple possible root nodes found.",E(t,s));-1!==e.unpairedTags.indexOf(l)||r.push({tagName:l,tagStartPos:a}),i=!0}for(s++;s0)||b("InvalidXml","Invalid '"+JSON.stringify(r.map(function(t){return t.tagName}),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):b("InvalidXml","Start tag expected.",1)}function u(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function p(t,e){for(var r=e;e5&&"xml"===i)return b("InvalidXml","XML declaration allowed only at the start of the document.",E(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}}return e}function d(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){var r=1;for(e+=8;e"===t[e]&&0===--r)break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}var c='"',f="'";function g(t,e){for(var r="",i="",n=!1;e"===t[e]&&""===i){n=!0;break}r+=t[e]}return""===i&&{value:r,index:e,tagClosed:n}}var m=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function v(t,e){for(var r=n(t,m),i={},s=0;s0?this.child.push(((r={})[t.tagname]=t.child,r[":@"]=t[":@"],r)):this.child.push(((i={})[t.tagname]=t.child,i)),void 0!==e&&(this.child[this.child.length-1][C]={startIndex:e})},t.getMetaDataSymbol=function(){return C},t}(),I=function(){function t(t){this.suppressValidationErr=!t,this.options=t}var e=t.prototype;return e.readDocType=function(t,e){var r=Object.create(null),i=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");e+=9;for(var n=1,s=!1,a=!1;e"===t[e]){if(a?"-"===t[e-1]&&"-"===t[e-2]&&(a=!1,n--):n--,0===n)break}else"["===t[e]?s=!0:t[e];else{if(s&&D(t,"!ENTITY",e)){e+=7;var o,h=void 0,l=this.readEntityExp(t,e+1,this.suppressValidationErr);if(o=l[0],h=l[1],e=l[2],-1===h.indexOf("&")){if(!1!==this.options.enabled&&null!=this.options.maxEntityCount&&i>=this.options.maxEntityCount)throw new Error("Entity count ("+(i+1)+") exceeds maximum allowed ("+this.options.maxEntityCount+")");r[o]=h,i++}}else if(s&&D(t,"!ELEMENT",e))e+=8,e=this.readElementExp(t,e+1).index;else if(s&&D(t,"!ATTLIST",e))e+=8;else if(s&&D(t,"!NOTATION",e))e+=9,e=this.readNotationExp(t,e+1,this.suppressValidationErr).index;else{if(!D(t,"!--",e))throw new Error("Invalid DOCTYPE");a=!0}n++}if(0!==n)throw new Error("Unclosed DOCTYPE");return{entities:r,i:e}},e.readEntityExp=function(t,e){for(var r=e=j(t,e);ethis.options.maxEntitySize)throw new Error('Entity "'+i+'" size ('+n.length+") exceeds maximum allowed size ("+this.options.maxEntitySize+")");return[i,n,--e]},e.readNotationExp=function(t,e){for(var r=e=j(t,e);et.length)&&(e=t.length);for(var r=0,i=Array(e);r0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const r=e[e.length-1];return void 0!==r.values&&t in r.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class G{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new R(this)}push(t,e=null,r=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const i=this.path.length;this.siblingStacks[i]||(this.siblingStacks[i]=new Map);const n=this.siblingStacks[i],s=r?`${r}:${t}`:t,a=n.get(s)||0;let o=0;for(const t of n.values())o+=t;n.set(s,a+1);const h={tag:t,position:o,counter:a};null!=r&&(h.namespace=r),null!=e&&(h.values=e),this.path.push(h)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const r=t||this.separator;if(r===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(r);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(r)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e=0&&e>=0;){const i=t[r];if("deep-wildcard"===i.type){if(r--,r<0)return!0;const i=t[r];let n=!1;for(let t=e;t>=0;t--)if(this._matchSegment(i,this.path[t],t===this.path.length-1)){e=t-1,r--,n=!0;break}if(!n)return!1}else{if(!this._matchSegment(i,this.path[e],e===this.path.length-1))return!1;e--,r--}}return r<0}_matchSegment(t,e,r){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!r)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!r)return!1;const i=e.counter??0;if("first"===t.position&&0!==i)return!1;if("odd"===t.position&&i%2!=1)return!1;if("even"===t.position&&i%2!=0)return!1;if("nth"===t.position&&i!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}class U{constructor(t,e={},r){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=r,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let r=0,i="";for(;r",lt:"<",quot:'"'},Y={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},z=new Set("!?\\\\/[]$%{}^&*()<>|+");function q(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(z.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function Z(...t){const e=Object.create(null);for(const r of t)if(r)for(const t of Object.keys(r)){const i=r[t];if("string"==typeof i)e[t]=i;else if(i&&"object"==typeof i&&void 0!==i.val){const r=i.val;"string"==typeof r&&(e[t]=r)}}return e}const J="external",K="base",Q="all",H=Object.freeze({allow:0,leave:1,remove:2,throw:3}),tt=new Set([9,10,13]);class et{constructor(t={}){var e;this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitTiers=(e=this._limit.applyLimitsTo??J)&&e!==J?e===Q?new Set([Q]):e===K?new Set([K]):Array.isArray(e)?new Set(e):new Set([J]):new Set([J]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=Z(X,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const r=function(t){if(!t)return{xmlVersion:1,onLevel:H.allow,nullLevel:H.remove};const e=1.1===t.xmlVersion?1.1:1,r=H[t.onNCR]??H.allow,i=H[t.nullNCR]??H.remove;return{xmlVersion:e,onLevel:r,nullLevel:Math.max(i,H.remove)}}(t.ncr);this._ncrXmlVersion=r.xmlVersion,this._ncrOnLevel=r.onLevel,this._ncrNullLevel=r.nullLevel}setExternalEntities(t){if(t)for(const e of Object.keys(t))q(e);this._externalMap=Z(t)}addExternalEntity(t,e){q(t),"string"==typeof e&&-1===e.indexOf("&")&&(this._externalMap[t]=e)}addInputEntities(t){this._totalExpansions=0,this._expandedLength=0,this._inputMap=Z(t)}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=1.1===t?1.1:1}decode(t){if("string"!=typeof t||0===t.length)return t;const e=t,r=[],i=t.length;let n=0,s=0;const a=this._maxTotalExpansions>0,o=this._maxExpandedLength>0,h=a||o;for(;s=i||59!==t.charCodeAt(e)){s++;continue}const l=t.slice(s+1,e);if(0===l.length){s++;continue}let u,p;if(this._removeSet.has(l))u="",void 0===p&&(p=J);else{if(this._leaveSet.has(l)){s++;continue}if(35===l.charCodeAt(0)){const t=this._resolveNCR(l);if(void 0===t){s++;continue}u=t,p=K}else{const t=this._resolveName(l);u=t?.value,p=t?.tier}}if(void 0!==u){if(s>n&&r.push(t.slice(n,s)),r.push(u),n=e+1,s=n,h&&this._tierCounts(p)){if(a&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(o){const t=u.length-(l.length+2);if(t>0&&(this._expandedLength+=t,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else s++}n=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!tt.has(t)?H.remove:-1}_applyNCRAction(t,e,r){switch(t){case H.allow:return String.fromCodePoint(r);case H.remove:return"";case H.leave:return;case H.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${r.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(r)}}_resolveNCR(t){const e=t.charCodeAt(1);let r;if(r=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(r)||r<0||r>1114111)return;const i=this._classifyNCR(r);if(!this._numericAllowed&&i0){var r=t.substring(0,e);if("xmlns"!==r)return r}}}var st=function(t){var e;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=ut,this.parseTextData=at,this.resolveNameSpace=ot,this.buildAttributesMap=lt,this.isItStopNode=ft,this.replaceEntitiesValue=dt,this.readStopNodeData=xt,this.saveTextToParentTag=ct,this.addChild=pt,this.ignoreAttributesFn="function"==typeof(e=this.options.ignoreAttributes)?e:Array.isArray(e)?function(t){for(var r,i=function(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,e){if(t){if("string"==typeof t)return F(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?F(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var i=0;return function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(e);!(r=i()).done;){var n=r.value;if("string"==typeof n&&t===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}}:function(){return!1},this.entityExpansionCount=0,this.currentExpandedLength=0;var r=rt({},X);this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?r=this.options.htmlEntities:!0===this.options.htmlEntities&&(r=rt({},Y,W)),this.entityDecoder=new et({namedEntities:r,numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo}})),this.matcher=new G,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new B;var i=this.options.stopNodes;if(i&&i.length>0){for(var n=0;n0)){a||(t=this.replaceEntitiesValue(t,e,r));var h=o.jPath?r.toString():r,l=o.tagValueProcessor(e,t,h,n,s);return null==l?t:typeof l!=typeof t||l!==t?l:o.trimValues||t.trim()===t?bt(t,o.parseTagValue,o.numberParseOptions):t}}function ot(t){if(this.options.removeNSPrefix){var e=t.split(":"),r="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=r+e[1])}return t}var ht=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function lt(t,e,r,i){void 0===i&&(i=!1);var s=this.options;if(!0===i||!0!==s.ignoreAttributes&&"string"==typeof t){for(var a=n(t,ht),o=a.length,h={},l=new Array(o),u=!1,p={},d=0;d",o,"Closing Tag is not closed."),u=t.substring(o+2,l).trim();if(n.removeNSPrefix){var p=u.indexOf(":");-1!==p&&(u=u.substr(p+1))}u=Nt(n.transformTagName,u,"",n).tagName,r&&(i=this.saveTextToParentTag(i,r,this.readonlyMatcher));var d=this.matcher.getCurrentTag();if(u&&n.unpairedTagsSet.has(u))throw new Error("Unpaired tag can not be used as closing tag: ");d&&n.unpairedTagsSet.has(d)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,r=this.tagsNodeStack.pop(),i="",o=l}else if(63===h){var c=vt(t,o,!1,"?>");if(!c)throw new Error("Pi Tag is not closed.");i=this.saveTextToParentTag(i,r,this.readonlyMatcher);var f=this.buildAttributesMap(c.tagExp,this.matcher,c.tagName,!0);if(f){var g=f[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(g)||1)}if(n.ignoreDeclaration&&"?xml"===c.tagName||n.ignorePiTags);else{var m=new O(c.tagName);m.add(n.textNodeName,""),c.tagName!==c.tagExp&&c.attrExpPresent&&!0!==n.ignoreAttributes&&(m[":@"]=f),this.addChild(r,m,this.readonlyMatcher,o)}o=c.closeIndex+1}else if(33===h&&45===t.charCodeAt(o+2)&&45===t.charCodeAt(o+3)){var v=gt(t,"--\x3e",o+4,"Comment is not closed.");if(n.commentPropName){var x,b=t.substring(o+4,v-2);i=this.saveTextToParentTag(i,r,this.readonlyMatcher),r.add(n.commentPropName,[(x={},x[n.textNodeName]=b,x)])}o=v}else if(33===h&&68===t.charCodeAt(o+2)){var N=s.readDocType(t,o);this.entityDecoder.addInputEntities(N.entities),o=N.i}else if(33===h&&91===t.charCodeAt(o+2)){var y=gt(t,"]]>",o,"CDATA is not closed.")-2,E=t.substring(o+9,y);i=this.saveTextToParentTag(i,r,this.readonlyMatcher);var w,S=this.parseTextData(E,r.tagname,this.readonlyMatcher,!0,!1,!0,!0);null==S&&(S=""),n.cdataPropName?r.add(n.cdataPropName,[(w={},w[n.textNodeName]=E,w)]):r.add(n.textNodeName,S),o=y+2}else{var _=vt(t,o,n.removeNSPrefix);if(!_){var A=t.substring(Math.max(0,o-50),Math.min(a,o+50));throw new Error("readTagExp returned undefined at position "+o+'. Context: "'+A+'"')}var T=_.tagName,C=_.rawTagName,P=_.tagExp,j=_.attrExpPresent,D=_.closeIndex,$=Nt(n.transformTagName,T,P,n);if(T=$.tagName,P=$.tagExp,n.strictReservedNames&&(T===n.commentPropName||T===n.cdataPropName||T===n.textNodeName||T===n.attributesGroupName))throw new Error("Invalid tag name: "+T);r&&i&&"!xml"!==r.tagname&&(i=this.saveTextToParentTag(i,r,this.readonlyMatcher,!1));var M=r;M&&n.unpairedTagsSet.has(M.tagname)&&(r=this.tagsNodeStack.pop(),this.matcher.pop());var V=!1;P.length>0&&P.lastIndexOf("/")===P.length-1&&(V=!0,P="/"===T[T.length-1]?T=T.substr(0,T.length-1):P.substr(0,P.length-1),j=T!==P);var L,k=null;L=nt(C),T!==e.tagname&&this.matcher.push(T,{},L),T!==P&&j&&(k=this.buildAttributesMap(P,this.matcher,T))&&it(k,n),T!==e.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());var F=o;if(this.isCurrentNodeStopNode){var R="";if(V)o=_.closeIndex;else if(n.unpairedTagsSet.has(T))o=_.closeIndex;else{var G=this.readStopNodeData(t,C,D+1);if(!G)throw new Error("Unexpected end of "+C);o=G.i,R=G.tagContent}var U=new O(T);k&&(U[":@"]=k),U.add(n.textNodeName,R),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(r,U,this.readonlyMatcher,F)}else{if(V){var B=Nt(n.transformTagName,T,P,n);T=B.tagName,P=B.tagExp;var W=new O(T);k&&(W[":@"]=k),this.addChild(r,W,this.readonlyMatcher,F),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else{if(n.unpairedTagsSet.has(T)){var X=new O(T);k&&(X[":@"]=k),this.addChild(r,X,this.readonlyMatcher,F),this.matcher.pop(),this.isCurrentNodeStopNode=!1,o=_.closeIndex;continue}var Y=new O(T);if(this.tagsNodeStack.length>n.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(r),k&&(Y[":@"]=k),this.addChild(r,Y,this.readonlyMatcher,F),r=Y}i="",o=D}}}else i+=t[o];return e.child};function pt(t,e,r,i){this.options.captureMetaData||(i=void 0);var n=this.options.jPath?r.toString():r,s=this.options.updateTag(e.tagname,n,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e,i)):t.addChild(e,i))}function dt(t,e,r){var i=this.options.processEntities;if(!i||!i.enabled)return t;if(i.allowedTags){var n=this.options.jPath?r.toString():r;if(!(Array.isArray(i.allowedTags)?i.allowedTags.includes(e):i.allowedTags(e,n)))return t}if(i.tagFilter){var s=this.options.jPath?r.toString():r;if(!i.tagFilter(e,s))return t}return this.entityDecoder.decode(t)}function ct(t,e,r,i){return t&&(void 0===i&&(i=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,r,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,i))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function ft(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function gt(t,e,r,i){var n=t.indexOf(e,r);if(-1===n)throw new Error(i);return n+e.length-1}function mt(t,e,r,i){var n=t.indexOf(e,r);if(-1===n)throw new Error(i);return n}function vt(t,e,r,i){void 0===i&&(i=">");var n=function(t,e,r){void 0===r&&(r=">");for(var i=0,n=[],s=t.length,a=r.charCodeAt(0),o=r.length>1?r.charCodeAt(1):-1,h=e;h",r,e+" is not closed");if(t.substring(r+2,o).trim()===e&&0===--n)return{tagContent:t.substring(i,r),i:o};r=o}else if(63===a)r=gt(t,"?>",r+1,"StopNode is not closed.");else if(33===a&&45===t.charCodeAt(r+2)&&45===t.charCodeAt(r+3))r=gt(t,"--\x3e",r+3,"StopNode is not closed.");else if(33===a&&91===t.charCodeAt(r+2))r=gt(t,"]]>",r,"StopNode is not closed.")-2;else{var h=vt(t,r,">");h&&((h&&h.tagName)===e&&"/"!==h.tagExp[h.tagExp.length-1]&&n++,r=h.closeIndex)}}}function bt(t,e,r){if(e&&"string"==typeof t){var i=t.trim();return"true"===i||"false"!==i&&function(t,e={}){if(e=Object.assign({},L,e),!t||"string"!=typeof t)return t;let r=t.trim();if(0===r.length)return t;if(void 0!==e.skipLike&&e.skipLike.test(r))return t;if("0"===r)return 0;if(e.hex&&M.test(r))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(r);if(isFinite(r)){if(r.includes("e")||r.includes("E"))return function(t,e,r){if(!r.eNotation)return t;const i=e.match(k);if(i){let n=i[1]||"";const s=-1===i[3].indexOf("e")?"E":"e",a=i[2],o=n?t[a.length+1]===s:t[a.length]===s;return a.length>1&&o?t:(1!==a.length||!i[3].startsWith(`.${s}`)&&i[3][0]!==s)&&a.length>0?r.leadingZeros&&!o?(e=(i[1]||"")+i[3],Number(e)):t:Number(e)}return t}(t,r,e);{const n=V.exec(r);if(n){const s=n[1]||"",a=n[2];let o=(i=n[3])&&-1!==i.indexOf(".")?("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1)),i):i;const h=s?"."===t[a.length+1]:"."===t[a.length];if(!e.leadingZeros&&(a.length>1||1===a.length&&!h))return t;{const i=Number(r),n=String(i);if(0===i)return i;if(-1!==n.search(/[eE]/))return e.eNotation?i:t;if(-1!==r.indexOf("."))return"0"===n||n===o||n===`${s}${o}`?i:t;let h=a?o:r;return a?h===n||s+h===n?i:t:h===n||h===s+n?i:t}}return t}}var i;return function(t,e,r){const i=e===1/0;switch(r.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return i?"Infinity":"-Infinity";default:return t}}(t,Number(r),e)}(t,r)}return void 0!==t?t:""}function Nt(t,e,r,i){if(t){var n=t(e);r===e&&(r=n),e=n}return{tagName:e=yt(e,i),tagExp:r}}function yt(t,e){if(o.includes(t))throw new Error('[SECURITY] Invalid name: "'+t+'" is a reserved JavaScript keyword that could cause prototype pollution');return a.includes(t)?e.onDangerousProperty(t):t}var Et=O.getMetaDataSymbol();function wt(t,e){if(!t||"object"!=typeof t)return{};if(!e)return t;var r={};for(var i in t)i.startsWith(e)?r[i.substring(e.length)]=t[i]:r[i]=t[i];return r}function St(t,e,r,i){return _t(t,e,r,i)}function _t(t,e,r,i){for(var n,s={},a=0;a0&&(s[e.textNodeName]=n):void 0!==n&&(s[e.textNodeName]=n),s}function At(t){for(var e=Object.keys(t),r=0;r0&&(r="\n");const i=[];if(e.stopNodes&&Array.isArray(e.stopNodes))for(let t=0;te.maxNestedTags)throw new Error("Maximum nested tags exceeded");if(!Array.isArray(t)){if(null!=t){let r=t.toString();return r=kt(r,e),r}return""}for(let o=0;o/g,"]]]]>")}]]>`,a=!1,i.pop();continue}if(l===e.commentPropName){const t=h[l][0][e.textNodeName];s+=r+`\x3c!--${String(t).replace(/--/g,"- -").replace(/-$/,"- ")}--\x3e`,a=!0,i.pop();continue}if("?"===l[0]){const t=Vt(h[":@"],e,p),n="?xml"===l?"":r;let o=h[l][0][e.textNodeName];o=0!==o.length?" "+o:"",s+=n+`<${l}${o}${t}?>`,a=!0,i.pop();continue}let d=r;""!==d&&(d+=e.indentBy);const c=r+`<${l}${Vt(h[":@"],e,p)}`;let f;f=p?Dt(h[l],e):It(h[l],e,d,i,n),-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?s+=c+">":s+=c+"/>":f&&0!==f.length||!e.suppressEmptyNode?f&&f.endsWith(">")?s+=c+`>${f}${r}`:(s+=c+">",f&&""!==r&&(f.includes("/>")||f.includes("`):s+=c+"/>",a=!0,i.pop()}return s}function jt(t,e){if(!t||e.ignoreAttributes)return null;const r={};let i=!1;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n.startsWith(e.attributeNamePrefix)?n.substr(e.attributeNamePrefix.length):n]=t[n],i=!0);return i?r:null}function Dt(t,e){if(!Array.isArray(t))return null!=t?t.toString():"";let r="";for(let i=0;i${i}`:r+=`<${s}${t}/>`}}}return r}function $t(t,e){let r="";if(t&&!e.ignoreAttributes)for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let n=t[i];!0===n&&e.suppressBooleanAttributes?r+=` ${i.substr(e.attributeNamePrefix.length)}`:r+=` ${i.substr(e.attributeNamePrefix.length)}="${n}"`}return r}function Mt(t){const e=Object.keys(t);for(let r=0;r0&&e.processEntities)for(let r=0;r","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1,maxNestedTags:100,jPath:!0};function Rt(t){if(this.options=Object.assign({},Ft,t),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(let t=0;t{for(const r of e){if("string"==typeof r&&t===r)return!0;if(r instanceof RegExp&&r.test(t))return!0}}:()=>!1,this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Bt),this.processTextOrObjNode=Gt,this.options.format?(this.indentate=Ut,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function Gt(t,e,r,i){const n=this.extractAttributes(t);if(i.push(e,n),this.checkStopNode(i)){const n=this.buildRawContent(t),s=this.buildAttributesForStopNode(t);return i.pop(),this.buildObjectNode(n,e,s,r)}const s=this.j2x(t,r+1,i);return i.pop(),void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,s.attrStr,r,i):this.buildObjectNode(s.val,e,s.attrStr,r)}function Ut(t){return this.options.indentBy.repeat(t)}function Bt(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}Rt.prototype.build=function(t){if(this.options.preserveOrder)return Ot(t,this.options);{Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t});const e=new G;return this.j2x(t,0,e).val}},Rt.prototype.j2x=function(t,e,r){let i="",n="";if(this.options.maxNestedTags&&r.getDepth()>=this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");const s=this.options.jPath?r.toString():r,a=this.checkStopNode(r);for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(void 0===t[o])this.isAttribute(o)&&(n+="");else if(null===t[o])this.isAttribute(o)||o===this.options.cdataPropName?n+="":"?"===o[0]?n+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:n+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)n+=this.buildTextValNode(t[o],o,"",e,r);else if("object"!=typeof t[o]){const h=this.isAttribute(o);if(h&&!this.ignoreAttributesFn(h,s))i+=this.buildAttrPairStr(h,""+t[o],a);else if(!h)if(o===this.options.textNodeName){let e=this.options.tagValueProcessor(o,""+t[o]);n+=this.replaceEntitiesValue(e)}else{r.push(o);const i=this.checkStopNode(r);if(r.pop(),i){const r=""+t[o];n+=""===r?this.indentate(e)+"<"+o+this.closeTag(o)+this.tagEndChar:this.indentate(e)+"<"+o+">"+r+""+t+"${t}`;else if("object"==typeof t&&null!==t){const i=this.buildRawContent(t),n=this.buildAttributesForStopNode(t);e+=""===i?`<${r}${n}/>`:`<${r}${n}>${i}`}}else if("object"==typeof i&&null!==i){const t=this.buildRawContent(i),n=this.buildAttributesForStopNode(i);e+=""===t?`<${r}${n}/>`:`<${r}${n}>${t}`}else e+=`<${r}>${i}`}return e},Rt.prototype.buildAttributesForStopNode=function(t){if(!t||"object"!=typeof t)return"";let e="";if(this.options.attributesGroupName&&t[this.options.attributesGroupName]){const r=t[this.options.attributesGroupName];for(let t in r){if(!Object.prototype.hasOwnProperty.call(r,t))continue;const i=t.startsWith(this.options.attributeNamePrefix)?t.substring(this.options.attributeNamePrefix.length):t,n=r[t];!0===n&&this.options.suppressBooleanAttributes?e+=" "+i:e+=" "+i+'="'+n+'"'}}else for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;const i=this.isAttribute(r);if(i){const n=t[r];!0===n&&this.options.suppressBooleanAttributes?e+=" "+i:e+=" "+i+'="'+n+'"'}}return e},Rt.prototype.buildObjectNode=function(t,e,r,i){if(""===t)return"?"===e[0]?this.indentate(i)+"<"+e+r+"?"+this.tagEndChar:this.indentate(i)+"<"+e+r+this.closeTag(e)+this.tagEndChar;{let n=""+t+n}},Rt.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>/g,"]]]]>");return this.indentate(i)+``+this.newLine}if(!1!==this.options.commentPropName&&e===this.options.commentPropName){const e=String(t).replace(/--/g,"- -").replace(/-$/,"- ");return this.indentate(i)+`\x3c!--${e}--\x3e`+this.newLine}if("?"===e[0])return this.indentate(i)+"<"+e+r+"?"+this.tagEndChar;{let n=this.options.tagValueProcessor(e,t);return n=this.replaceEntitiesValue(n),""===n?this.indentate(i)+"<"+e+r+this.closeTag(e)+this.tagEndChar:this.indentate(i)+"<"+e+r+">"+n+"0&&this.options.processEntities)for(let e=0;e {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","'use strict';\n\nconst nameStartChar = ':A-Za-z_\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD';\nconst nameChar = nameStartChar + '\\\\-.\\\\d\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040';\nexport const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*';\nconst regexName = new RegExp('^' + nameRegexp + '$');\n\nexport function getAllMatches(string, regex) {\n const matches = [];\n let match = regex.exec(string);\n while (match) {\n const allmatches = [];\n allmatches.startIndex = regex.lastIndex - match[0].length;\n const len = match.length;\n for (let index = 0; index < len; index++) {\n allmatches.push(match[index]);\n }\n matches.push(allmatches);\n match = regex.exec(string);\n }\n return matches;\n}\n\nexport const isName = function (string) {\n const match = regexName.exec(string);\n return !(match === null || typeof match === 'undefined');\n}\n\nexport function isExist(v) {\n return typeof v !== 'undefined';\n}\n\nexport function isEmptyObject(obj) {\n return Object.keys(obj).length === 0;\n}\n\nexport function getValue(v) {\n if (exports.isExist(v)) {\n return v;\n } else {\n return '';\n }\n}\n\n/**\n * Dangerous property names that could lead to prototype pollution or security issues\n */\nexport const DANGEROUS_PROPERTY_NAMES = [\n // '__proto__',\n // 'constructor',\n // 'prototype',\n 'hasOwnProperty',\n 'toString',\n 'valueOf',\n '__defineGetter__',\n '__defineSetter__',\n '__lookupGetter__',\n '__lookupSetter__'\n];\n\nexport const criticalProperties = [\"__proto__\", \"constructor\", \"prototype\"];","'use strict';\n\nimport { getAllMatches, isName } from './util.js';\n\nconst defaultOptions = {\n allowBooleanAttributes: false, //A tag can have attributes without any value\n unpairedTags: []\n};\n\n//const tagsPattern = new RegExp(\"<\\\\/?([\\\\w:\\\\-_\\.]+)\\\\s*\\/?>\",\"g\");\nexport function validate(xmlData, options) {\n options = Object.assign({}, defaultOptions, options);\n\n //xmlData = xmlData.replace(/(\\r\\n|\\n|\\r)/gm,\"\");//make it single line\n //xmlData = xmlData.replace(/(^\\s*<\\?xml.*?\\?>)/g,\"\");//Remove XML starting tag\n //xmlData = xmlData.replace(/()/g,\"\");//Remove DOCTYPE\n const tags = [];\n let tagFound = false;\n\n //indicates that the root tag has been closed (aka. depth 0 has been reached)\n let reachedRoot = false;\n\n if (xmlData[0] === '\\ufeff') {\n // check for byte order mark (BOM)\n xmlData = xmlData.substr(1);\n }\n\n for (let i = 0; i < xmlData.length; i++) {\n\n if (xmlData[i] === '<' && xmlData[i + 1] === '?') {\n i += 2;\n i = readPI(xmlData, i);\n if (i.err) return i;\n } else if (xmlData[i] === '<') {\n //starting of tag\n //read until you reach to '>' avoiding any '>' in attribute value\n let tagStartPos = i;\n i++;\n\n if (xmlData[i] === '!') {\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else {\n let closingTag = false;\n if (xmlData[i] === '/') {\n //closing tag\n closingTag = true;\n i++;\n }\n //read tagname\n let tagName = '';\n for (; i < xmlData.length &&\n xmlData[i] !== '>' &&\n xmlData[i] !== ' ' &&\n xmlData[i] !== '\\t' &&\n xmlData[i] !== '\\n' &&\n xmlData[i] !== '\\r'; i++\n ) {\n tagName += xmlData[i];\n }\n tagName = tagName.trim();\n //console.log(tagName);\n\n if (tagName[tagName.length - 1] === '/') {\n //self closing tag without attributes\n tagName = tagName.substring(0, tagName.length - 1);\n //continue;\n i--;\n }\n if (!validateTagName(tagName)) {\n let msg;\n if (tagName.trim().length === 0) {\n msg = \"Invalid space after '<'.\";\n } else {\n msg = \"Tag '\" + tagName + \"' is an invalid name.\";\n }\n return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));\n }\n\n const result = readAttributeStr(xmlData, i);\n if (result === false) {\n return getErrorObject('InvalidAttr', \"Attributes for '\" + tagName + \"' have open quote.\", getLineNumberForPosition(xmlData, i));\n }\n let attrStr = result.value;\n i = result.index;\n\n if (attrStr[attrStr.length - 1] === '/') {\n //self closing tag\n const attrStrStart = i - attrStr.length;\n attrStr = attrStr.substring(0, attrStr.length - 1);\n const isValid = validateAttributeString(attrStr, options);\n if (isValid === true) {\n tagFound = true;\n //continue; //text may presents after self closing tag\n } else {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));\n }\n } else if (closingTag) {\n if (!result.tagClosed) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' doesn't have proper closing.\", getLineNumberForPosition(xmlData, i));\n } else if (attrStr.trim().length > 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' can't have attributes or invalid starting.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else if (tags.length === 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' has not been opened.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else {\n const otg = tags.pop();\n if (tagName !== otg.tagName) {\n let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);\n return getErrorObject('InvalidTag',\n \"Expected closing tag '\" + otg.tagName + \"' (opened in line \" + openPos.line + \", col \" + openPos.col + \") instead of closing tag '\" + tagName + \"'.\",\n getLineNumberForPosition(xmlData, tagStartPos));\n }\n\n //when there are no more tags, we reached the root level.\n if (tags.length == 0) {\n reachedRoot = true;\n }\n }\n } else {\n const isValid = validateAttributeString(attrStr, options);\n if (isValid !== true) {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));\n }\n\n //if the root level has been reached before ...\n if (reachedRoot === true) {\n return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));\n } else if (options.unpairedTags.indexOf(tagName) !== -1) {\n //don't push into stack\n } else {\n tags.push({ tagName, tagStartPos });\n }\n tagFound = true;\n }\n\n //skip tag text value\n //It may include comments and CDATA value\n for (i++; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n if (xmlData[i + 1] === '!') {\n //comment or CADATA\n i++;\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else if (xmlData[i + 1] === '?') {\n i = readPI(xmlData, ++i);\n if (i.err) return i;\n } else {\n break;\n }\n } else if (xmlData[i] === '&') {\n const afterAmp = validateAmpersand(xmlData, i);\n if (afterAmp == -1)\n return getErrorObject('InvalidChar', \"char '&' is not expected.\", getLineNumberForPosition(xmlData, i));\n i = afterAmp;\n } else {\n if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {\n return getErrorObject('InvalidXml', \"Extra text at the end\", getLineNumberForPosition(xmlData, i));\n }\n }\n } //end of reading tag text value\n if (xmlData[i] === '<') {\n i--;\n }\n }\n } else {\n if (isWhiteSpace(xmlData[i])) {\n continue;\n }\n return getErrorObject('InvalidChar', \"char '\" + xmlData[i] + \"' is not expected.\", getLineNumberForPosition(xmlData, i));\n }\n }\n\n if (!tagFound) {\n return getErrorObject('InvalidXml', 'Start tag expected.', 1);\n } else if (tags.length == 1) {\n return getErrorObject('InvalidTag', \"Unclosed tag '\" + tags[0].tagName + \"'.\", getLineNumberForPosition(xmlData, tags[0].tagStartPos));\n } else if (tags.length > 0) {\n return getErrorObject('InvalidXml', \"Invalid '\" +\n JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\\r?\\n/g, '') +\n \"' found.\", { line: 1, col: 1 });\n }\n\n return true;\n};\n\nfunction isWhiteSpace(char) {\n return char === ' ' || char === '\\t' || char === '\\n' || char === '\\r';\n}\n/**\n * Read Processing insstructions and skip\n * @param {*} xmlData\n * @param {*} i\n */\nfunction readPI(xmlData, i) {\n const start = i;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] == '?' || xmlData[i] == ' ') {\n //tagname\n const tagname = xmlData.substr(start, i - start);\n if (i > 5 && tagname === 'xml') {\n return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));\n } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {\n //check if valid attribut string\n i++;\n break;\n } else {\n continue;\n }\n }\n }\n return i;\n}\n\nfunction readCommentAndCDATA(xmlData, i) {\n if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {\n //comment\n for (i += 3; i < xmlData.length; i++) {\n if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n } else if (\n xmlData.length > i + 8 &&\n xmlData[i + 1] === 'D' &&\n xmlData[i + 2] === 'O' &&\n xmlData[i + 3] === 'C' &&\n xmlData[i + 4] === 'T' &&\n xmlData[i + 5] === 'Y' &&\n xmlData[i + 6] === 'P' &&\n xmlData[i + 7] === 'E'\n ) {\n let angleBracketsCount = 1;\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n angleBracketsCount++;\n } else if (xmlData[i] === '>') {\n angleBracketsCount--;\n if (angleBracketsCount === 0) {\n break;\n }\n }\n }\n } else if (\n xmlData.length > i + 9 &&\n xmlData[i + 1] === '[' &&\n xmlData[i + 2] === 'C' &&\n xmlData[i + 3] === 'D' &&\n xmlData[i + 4] === 'A' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'A' &&\n xmlData[i + 7] === '['\n ) {\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n }\n\n return i;\n}\n\nconst doubleQuote = '\"';\nconst singleQuote = \"'\";\n\n/**\n * Keep reading xmlData until '<' is found outside the attribute value.\n * @param {string} xmlData\n * @param {number} i\n */\nfunction readAttributeStr(xmlData, i) {\n let attrStr = '';\n let startChar = '';\n let tagClosed = false;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {\n if (startChar === '') {\n startChar = xmlData[i];\n } else if (startChar !== xmlData[i]) {\n //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa\n } else {\n startChar = '';\n }\n } else if (xmlData[i] === '>') {\n if (startChar === '') {\n tagClosed = true;\n break;\n }\n }\n attrStr += xmlData[i];\n }\n if (startChar !== '') {\n return false;\n }\n\n return {\n value: attrStr,\n index: i,\n tagClosed: tagClosed\n };\n}\n\n/**\n * Select all the attributes whether valid or invalid.\n */\nconst validAttrStrRegxp = new RegExp('(\\\\s*)([^\\\\s=]+)(\\\\s*=)?(\\\\s*([\\'\"])(([\\\\s\\\\S])*?)\\\\5)?', 'g');\n\n//attr, =\"sd\", a=\"amit's\", a=\"sd\"b=\"saf\", ab cd=\"\"\n\nfunction validateAttributeString(attrStr, options) {\n //console.log(\"start:\"+attrStr+\":end\");\n\n //if(attrStr.trim().length === 0) return true; //empty string\n\n const matches = getAllMatches(attrStr, validAttrStrRegxp);\n const attrNames = {};\n\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][1].length === 0) {\n //nospace before attribute name: a=\"sd\"b=\"saf\"\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' has no space in starting.\", getPositionFromMatch(matches[i]))\n } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' is without value.\", getPositionFromMatch(matches[i]));\n } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {\n //independent attribute: ab\n return getErrorObject('InvalidAttr', \"boolean attribute '\" + matches[i][2] + \"' is not allowed.\", getPositionFromMatch(matches[i]));\n }\n /* else if(matches[i][6] === undefined){//attribute without value: ab=\n return { err: { code:\"InvalidAttr\",msg:\"attribute \" + matches[i][2] + \" has no value assigned.\"}};\n } */\n const attrName = matches[i][2];\n if (!validateAttrName(attrName)) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is an invalid name.\", getPositionFromMatch(matches[i]));\n }\n if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) {\n //check for duplicate attribute.\n attrNames[attrName] = 1;\n } else {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is repeated.\", getPositionFromMatch(matches[i]));\n }\n }\n\n return true;\n}\n\nfunction validateNumberAmpersand(xmlData, i) {\n let re = /\\d/;\n if (xmlData[i] === 'x') {\n i++;\n re = /[\\da-fA-F]/;\n }\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === ';')\n return i;\n if (!xmlData[i].match(re))\n break;\n }\n return -1;\n}\n\nfunction validateAmpersand(xmlData, i) {\n // https://www.w3.org/TR/xml/#dt-charref\n i++;\n if (xmlData[i] === ';')\n return -1;\n if (xmlData[i] === '#') {\n i++;\n return validateNumberAmpersand(xmlData, i);\n }\n let count = 0;\n for (; i < xmlData.length; i++, count++) {\n if (xmlData[i].match(/\\w/) && count < 20)\n continue;\n if (xmlData[i] === ';')\n break;\n return -1;\n }\n return i;\n}\n\nfunction getErrorObject(code, message, lineNumber) {\n return {\n err: {\n code: code,\n msg: message,\n line: lineNumber.line || lineNumber,\n col: lineNumber.col,\n },\n };\n}\n\nfunction validateAttrName(attrName) {\n return isName(attrName);\n}\n\n// const startsWithXML = /^xml/i;\n\nfunction validateTagName(tagname) {\n return isName(tagname) /* && !tagname.match(startsWithXML) */;\n}\n\n//this function returns the line number for the character at the given index\nfunction getLineNumberForPosition(xmlData, index) {\n const lines = xmlData.substring(0, index).split(/\\r?\\n/);\n return {\n line: lines.length,\n\n // column number is last line's length + 1, because column numbering starts at 1:\n col: lines[lines.length - 1].length + 1\n };\n}\n\n//this function returns the position of the first character of match within attrStr\nfunction getPositionFromMatch(match) {\n return match.startIndex + match[1].length;\n}\n","import { DANGEROUS_PROPERTY_NAMES, criticalProperties } from \"../util.js\";\nimport { COMMON_HTML, CURRENCY } from '@nodable/entities';\n\nconst defaultOnDangerousProperty = (name) => {\n if (DANGEROUS_PROPERTY_NAMES.includes(name)) {\n return \"__\" + name;\n }\n return name;\n};\n\n\nexport const defaultOptions = {\n preserveOrder: false,\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n removeNSPrefix: false, // remove NS from tag name or attribute name if true\n allowBooleanAttributes: false, //a tag can have attributes without any value\n //ignoreRootElement : false,\n parseTagValue: true,\n parseAttributeValue: false,\n trimValues: true, //Trim string values of tag and attributes\n cdataPropName: false,\n numberParseOptions: {\n hex: true,\n leadingZeros: true,\n eNotation: true\n },\n tagValueProcessor: function (tagName, val) {\n return val;\n },\n attributeValueProcessor: function (attrName, val) {\n return val;\n },\n stopNodes: [], //nested tags will not be parsed even for errors\n alwaysCreateTextNode: false,\n isArray: () => false,\n commentPropName: false,\n unpairedTags: [],\n processEntities: true,\n htmlEntities: false,\n entityDecoder: null,\n ignoreDeclaration: false,\n ignorePiTags: false,\n transformTagName: false,\n transformAttributeName: false,\n updateTag: function (tagName, jPath, attrs) {\n return tagName\n },\n // skipEmptyListItem: false\n captureMetaData: false,\n maxNestedTags: 100,\n strictReservedNames: true,\n jPath: true, // if true, pass jPath string to callbacks; if false, pass matcher instance\n onDangerousProperty: defaultOnDangerousProperty\n};\n\n\n/**\n * Validates that a property name is safe to use\n * @param {string} propertyName - The property name to validate\n * @param {string} optionName - The option field name (for error message)\n * @throws {Error} If property name is dangerous\n */\nfunction validatePropertyName(propertyName, optionName) {\n if (typeof propertyName !== 'string') {\n return; // Only validate string property names\n }\n\n const normalized = propertyName.toLowerCase();\n if (DANGEROUS_PROPERTY_NAMES.some(dangerous => normalized === dangerous.toLowerCase())) {\n throw new Error(\n `[SECURITY] Invalid ${optionName}: \"${propertyName}\" is a reserved JavaScript keyword that could cause prototype pollution`\n );\n }\n\n if (criticalProperties.some(dangerous => normalized === dangerous.toLowerCase())) {\n throw new Error(\n `[SECURITY] Invalid ${optionName}: \"${propertyName}\" is a reserved JavaScript keyword that could cause prototype pollution`\n );\n }\n}\n\n/**\n * Normalizes processEntities option for backward compatibility\n * @param {boolean|object} value \n * @returns {object} Always returns normalized object\n */\nfunction normalizeProcessEntities(value, htmlEntities) {\n // Boolean backward compatibility\n if (typeof value === 'boolean') {\n return {\n enabled: value, // true or false\n maxEntitySize: 10000,\n maxExpansionDepth: 10000,\n maxTotalExpansions: Infinity,\n maxExpandedLength: 100000,\n maxEntityCount: 1000,\n allowedTags: null,\n tagFilter: null,\n appliesTo: \"all\",\n };\n }\n\n // Object config - merge with defaults\n if (typeof value === 'object' && value !== null) {\n return {\n enabled: value.enabled !== false,\n maxEntitySize: Math.max(1, value.maxEntitySize ?? 10000),\n maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 10000),\n maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity),\n maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 100000),\n maxEntityCount: Math.max(1, value.maxEntityCount ?? 1000),\n allowedTags: value.allowedTags ?? null,\n tagFilter: value.tagFilter ?? null,\n appliesTo: value.appliesTo ?? \"all\",\n };\n }\n\n // Default to enabled with limits\n return normalizeProcessEntities(true);\n}\n\nexport const buildOptions = function (options) {\n const built = Object.assign({}, defaultOptions, options);\n\n // Validate property names to prevent prototype pollution\n const propertyNameOptions = [\n { value: built.attributeNamePrefix, name: 'attributeNamePrefix' },\n { value: built.attributesGroupName, name: 'attributesGroupName' },\n { value: built.textNodeName, name: 'textNodeName' },\n { value: built.cdataPropName, name: 'cdataPropName' },\n { value: built.commentPropName, name: 'commentPropName' }\n ];\n\n for (const { value, name } of propertyNameOptions) {\n if (value) {\n validatePropertyName(value, name);\n }\n }\n\n if (built.onDangerousProperty === null) {\n built.onDangerousProperty = defaultOnDangerousProperty;\n }\n\n // Always normalize processEntities for backward compatibility and validation\n built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities);\n built.unpairedTagsSet = new Set(built.unpairedTags);\n // Convert old-style stopNodes for backward compatibility\n if (built.stopNodes && Array.isArray(built.stopNodes)) {\n built.stopNodes = built.stopNodes.map(node => {\n if (typeof node === 'string' && node.startsWith('*.')) {\n // Old syntax: *.tagname meant \"tagname anywhere\"\n // Convert to new syntax: ..tagname\n return '..' + node.substring(2);\n }\n return node;\n });\n }\n //console.debug(built.processEntities)\n return built;\n};","'use strict';\n\nlet METADATA_SYMBOL;\n\nif (typeof Symbol !== \"function\") {\n METADATA_SYMBOL = \"@@xmlMetadata\";\n} else {\n METADATA_SYMBOL = Symbol(\"XML Node Metadata\");\n}\n\nexport default class XmlNode {\n constructor(tagname) {\n this.tagname = tagname;\n this.child = []; //nested tags, text, cdata, comments in order\n this[\":@\"] = Object.create(null); //attributes map\n }\n add(key, val) {\n // this.child.push( {name : key, val: val, isCdata: isCdata });\n if (key === \"__proto__\") key = \"#__proto__\";\n this.child.push({ [key]: val });\n }\n addChild(node, startIndex) {\n if (node.tagname === \"__proto__\") node.tagname = \"#__proto__\";\n if (node[\":@\"] && Object.keys(node[\":@\"]).length > 0) {\n this.child.push({ [node.tagname]: node.child, [\":@\"]: node[\":@\"] });\n } else {\n this.child.push({ [node.tagname]: node.child });\n }\n // if requested, add the startIndex\n if (startIndex !== undefined) {\n // Note: for now we just overwrite the metadata. If we had more complex metadata,\n // we might need to do an object append here: metadata = { ...metadata, startIndex }\n this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex };\n }\n }\n /** symbol used for metadata */\n static getMetaDataSymbol() {\n return METADATA_SYMBOL;\n }\n}\n","import { isName } from '../util.js';\n\nexport default class DocTypeReader {\n constructor(options) {\n this.suppressValidationErr = !options;\n this.options = options;\n }\n\n readDocType(xmlData, i) {\n const entities = Object.create(null);\n let entityCount = 0;\n\n if (xmlData[i + 3] === 'O' &&\n xmlData[i + 4] === 'C' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'Y' &&\n xmlData[i + 7] === 'P' &&\n xmlData[i + 8] === 'E') {\n i = i + 9;\n let angleBracketsCount = 1;\n let hasBody = false, comment = false;\n let exp = \"\";\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === '<' && !comment) { //Determine the tag type\n if (hasBody && hasSeq(xmlData, \"!ENTITY\", i)) {\n i += 7;\n let entityName, val;\n [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr);\n if (val.indexOf(\"&\") === -1) { //Parameter entities are not supported\n if (this.options.enabled !== false &&\n this.options.maxEntityCount != null &&\n entityCount >= this.options.maxEntityCount) {\n throw new Error(\n `Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`\n );\n }\n //const escaped = entityName.replace(/[.\\-+*:]/g, '\\\\.');\n //const escaped = entityName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n entities[entityName] = val;\n entityCount++;\n }\n }\n else if (hasBody && hasSeq(xmlData, \"!ELEMENT\", i)) {\n i += 8;//Not supported\n const { index } = this.readElementExp(xmlData, i + 1);\n i = index;\n } else if (hasBody && hasSeq(xmlData, \"!ATTLIST\", i)) {\n i += 8;//Not supported\n // const {index} = this.readAttlistExp(xmlData,i+1);\n // i = index;\n } else if (hasBody && hasSeq(xmlData, \"!NOTATION\", i)) {\n i += 9;//Not supported\n const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr);\n i = index;\n } else if (hasSeq(xmlData, \"!--\", i)) comment = true;\n else throw new Error(`Invalid DOCTYPE`);\n\n angleBracketsCount++;\n exp = \"\";\n } else if (xmlData[i] === '>') { //Read tag content\n if (comment) {\n if (xmlData[i - 1] === \"-\" && xmlData[i - 2] === \"-\") {\n comment = false;\n angleBracketsCount--;\n }\n } else {\n angleBracketsCount--;\n }\n if (angleBracketsCount === 0) {\n break;\n }\n } else if (xmlData[i] === '[') {\n hasBody = true;\n } else {\n exp += xmlData[i];\n }\n }\n if (angleBracketsCount !== 0) {\n throw new Error(`Unclosed DOCTYPE`);\n }\n } else {\n throw new Error(`Invalid Tag instead of DOCTYPE`);\n }\n return { entities, i };\n }\n readEntityExp(xmlData, i) {\n //External entities are not supported\n // \n\n //Parameter entities are not supported\n // \n\n //Internal entities are supported\n // \n\n // Skip leading whitespace after this.options.maxEntitySize) {\n throw new Error(\n `Entity \"${entityName}\" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`\n );\n }\n\n i--;\n return [entityName, entityValue, i];\n }\n\n readNotationExp(xmlData, i) {\n // Skip leading whitespace after \n // \n // \n // \n // \n\n // Skip leading whitespace after {\n while (index < data.length && /\\s/.test(data[index])) {\n index++;\n }\n return index;\n};\n\n\n\nfunction hasSeq(data, seq, i) {\n for (let j = 0; j < seq.length; j++) {\n if (seq[j] !== data[i + j + 1]) return false;\n }\n return true;\n}\n\nfunction validateEntityName(name) {\n if (isName(name))\n return name;\n else\n throw new Error(`Invalid entity name ${name}`);\n}","const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;\nconst numRegex = /^([\\-\\+])?(0*)([0-9]*(\\.[0-9]*)?)$/;\n// const octRegex = /^0x[a-z0-9]+/;\n// const binRegex = /0x[a-z0-9]+/;\n\n\nconst consider = {\n hex: true,\n // oct: false,\n leadingZeros: true,\n decimalPoint: \"\\.\",\n eNotation: true,\n //skipLike: /regex/,\n infinity: \"original\", // \"null\", \"infinity\" (Infinity type), \"string\" (\"Infinity\" (the string literal))\n};\n\nexport default function toNumber(str, options = {}) {\n options = Object.assign({}, consider, options);\n if (!str || typeof str !== \"string\") return str;\n\n let trimmedStr = str.trim();\n\n if (trimmedStr.length === 0) return str;\n else if (options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;\n else if (trimmedStr === \"0\") return 0;\n else if (options.hex && hexRegex.test(trimmedStr)) {\n return parse_int(trimmedStr, 16);\n // }else if (options.oct && octRegex.test(str)) {\n // return Number.parseInt(val, 8);\n } else if (!isFinite(trimmedStr)) { //Infinity\n return handleInfinity(str, Number(trimmedStr), options);\n } else if (trimmedStr.includes('e') || trimmedStr.includes('E')) { //eNotation\n return resolveEnotation(str, trimmedStr, options);\n // }else if (options.parseBin && binRegex.test(str)) {\n // return Number.parseInt(val, 2);\n } else {\n //separate negative sign, leading zeros, and rest number\n const match = numRegex.exec(trimmedStr);\n // +00.123 => [ , '+', '00', '.123', ..\n if (match) {\n const sign = match[1] || \"\";\n const leadingZeros = match[2];\n let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros\n const decimalAdjacentToLeadingZeros = sign ? // 0., -00., 000.\n str[leadingZeros.length + 1] === \".\"\n : str[leadingZeros.length] === \".\";\n\n //trim ending zeros for floating number\n if (!options.leadingZeros //leading zeros are not allowed\n && (leadingZeros.length > 1\n || (leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros))) {\n // 00, 00.3, +03.24, 03, 03.24\n return str;\n }\n else {//no leading zeros or leading zeros are allowed\n const num = Number(trimmedStr);\n const parsedStr = String(num);\n\n if (num === 0) return num;\n if (parsedStr.search(/[eE]/) !== -1) { //given number is long and parsed to eNotation\n if (options.eNotation) return num;\n else return str;\n } else if (trimmedStr.indexOf(\".\") !== -1) { //floating number\n if (parsedStr === \"0\") return num; //0.0\n else if (parsedStr === numTrimmedByZeros) return num; //0.456. 0.79000\n else if (parsedStr === `${sign}${numTrimmedByZeros}`) return num;\n else return str;\n }\n\n let n = leadingZeros ? numTrimmedByZeros : trimmedStr;\n if (leadingZeros) {\n // -009 => -9\n return (n === parsedStr) || (sign + n === parsedStr) ? num : str\n } else {\n // +9\n return (n === parsedStr) || (n === sign + parsedStr) ? num : str\n }\n }\n } else { //non-numeric string\n return str;\n }\n }\n}\n\nconst eNotationRegx = /^([-+])?(0*)(\\d*(\\.\\d*)?[eE][-\\+]?\\d+)$/;\nfunction resolveEnotation(str, trimmedStr, options) {\n if (!options.eNotation) return str;\n const notation = trimmedStr.match(eNotationRegx);\n if (notation) {\n let sign = notation[1] || \"\";\n const eChar = notation[3].indexOf(\"e\") === -1 ? \"E\" : \"e\";\n const leadingZeros = notation[2];\n const eAdjacentToLeadingZeros = sign ? // 0E.\n str[leadingZeros.length + 1] === eChar\n : str[leadingZeros.length] === eChar;\n\n if (leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str;\n else if (leadingZeros.length === 1\n && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)) {\n return Number(trimmedStr);\n } else if (leadingZeros.length > 0) {\n // Has leading zeros — only accept if leadingZeros option allows it\n if (options.leadingZeros && !eAdjacentToLeadingZeros) {\n trimmedStr = (notation[1] || \"\") + notation[3];\n return Number(trimmedStr);\n } else return str;\n } else {\n // No leading zeros — always valid e-notation, parse it\n return Number(trimmedStr);\n }\n } else {\n return str;\n }\n}\n\n/**\n * \n * @param {string} numStr without leading zeros\n * @returns \n */\nfunction trimZeros(numStr) {\n if (numStr && numStr.indexOf(\".\") !== -1) {//float\n numStr = numStr.replace(/0+$/, \"\"); //remove ending zeros\n if (numStr === \".\") numStr = \"0\";\n else if (numStr[0] === \".\") numStr = \"0\" + numStr;\n else if (numStr[numStr.length - 1] === \".\") numStr = numStr.substring(0, numStr.length - 1);\n return numStr;\n }\n return numStr;\n}\n\nfunction parse_int(numStr, base) {\n //polyfill\n if (parseInt) return parseInt(numStr, base);\n else if (Number.parseInt) return Number.parseInt(numStr, base);\n else if (window && window.parseInt) return window.parseInt(numStr, base);\n else throw new Error(\"parseInt, Number.parseInt, window.parseInt are not supported\")\n}\n\n/**\n * Handle infinite values based on user option\n * @param {string} str - original input string\n * @param {number} num - parsed number (Infinity or -Infinity)\n * @param {object} options - user options\n * @returns {string|number|null} based on infinity option\n */\nfunction handleInfinity(str, num, options) {\n const isPositive = num === Infinity;\n\n switch (options.infinity.toLowerCase()) {\n case \"null\":\n return null;\n case \"infinity\":\n return num; // Return Infinity or -Infinity\n case \"string\":\n return isPositive ? \"Infinity\" : \"-Infinity\";\n case \"original\":\n default:\n return str; // Return original string like \"1e1000\"\n }\n}","import ExpressionSet from \"./ExpressionSet.js\";\n\n/**\n * MatcherView - A lightweight read-only view over a Matcher's internal state.\n *\n * Created once by Matcher and reused across all callbacks. Holds a direct\n * reference to the parent Matcher so it always reflects current parser state\n * with zero copying or freezing overhead.\n *\n * Users receive this via {@link Matcher#readOnly} or directly from parser\n * callbacks. It exposes all query and matching methods but has no mutation\n * methods — misuse is caught at the TypeScript level rather than at runtime.\n *\n * @example\n * const matcher = new Matcher();\n * const view = matcher.readOnly();\n *\n * matcher.push(\"root\", {});\n * view.getCurrentTag(); // \"root\"\n * view.getDepth(); // 1\n */\nexport class MatcherView {\n /**\n * @param {Matcher} matcher - The parent Matcher instance to read from.\n */\n constructor(matcher) {\n this._matcher = matcher;\n }\n\n /**\n * Get the path separator used by the parent matcher.\n * @returns {string}\n */\n get separator() {\n return this._matcher.separator;\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return undefined;\n return path[path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return false;\n const current = path[path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this._matcher.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n return this._matcher.toString(separator, includeNamespace);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this._matcher.path.map(n => n.tag);\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n return this._matcher.matches(expression);\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this._matcher);\n }\n}\n\n/**\n * Matcher - Tracks current path in XML/JSON tree and matches against Expressions.\n *\n * The matcher maintains a stack of nodes representing the current path from root to\n * current tag. It only stores attribute values for the current (top) node to minimize\n * memory usage. Sibling tracking is used to auto-calculate position and counter.\n *\n * Use {@link Matcher#readOnly} to obtain a {@link MatcherView} safe to pass to\n * user callbacks — it always reflects current state with no Proxy overhead.\n *\n * @example\n * const matcher = new Matcher();\n * matcher.push(\"root\", {});\n * matcher.push(\"users\", {});\n * matcher.push(\"user\", { id: \"123\", type: \"admin\" });\n *\n * const expr = new Expression(\"root.users.user\");\n * matcher.matches(expr); // true\n */\nexport default class Matcher {\n /**\n * Create a new Matcher.\n * @param {Object} [options={}]\n * @param {string} [options.separator='.'] - Default path separator\n */\n constructor(options = {}) {\n this.separator = options.separator || '.';\n this.path = [];\n this.siblingStacks = [];\n // Each path node: { tag, values, position, counter, namespace? }\n // values only present for current (last) node\n // Each siblingStacks entry: Map tracking occurrences at each level\n this._pathStringCache = null;\n this._view = new MatcherView(this);\n }\n\n /**\n * Push a new tag onto the path.\n * @param {string} tagName\n * @param {Object|null} [attrValues=null]\n * @param {string|null} [namespace=null]\n */\n push(tagName, attrValues = null, namespace = null) {\n this._pathStringCache = null;\n\n // Remove values from previous current node (now becoming ancestor)\n if (this.path.length > 0) {\n this.path[this.path.length - 1].values = undefined;\n }\n\n // Get or create sibling tracking for current level\n const currentLevel = this.path.length;\n if (!this.siblingStacks[currentLevel]) {\n this.siblingStacks[currentLevel] = new Map();\n }\n\n const siblings = this.siblingStacks[currentLevel];\n\n // Create a unique key for sibling tracking that includes namespace\n const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;\n\n // Calculate counter (how many times this tag appeared at this level)\n const counter = siblings.get(siblingKey) || 0;\n\n // Calculate position (total children at this level so far)\n let position = 0;\n for (const count of siblings.values()) {\n position += count;\n }\n\n // Update sibling count for this tag\n siblings.set(siblingKey, counter + 1);\n\n // Create new node\n const node = {\n tag: tagName,\n position: position,\n counter: counter\n };\n\n if (namespace !== null && namespace !== undefined) {\n node.namespace = namespace;\n }\n\n if (attrValues !== null && attrValues !== undefined) {\n node.values = attrValues;\n }\n\n this.path.push(node);\n }\n\n /**\n * Pop the last tag from the path.\n * @returns {Object|undefined} The popped node\n */\n pop() {\n if (this.path.length === 0) return undefined;\n this._pathStringCache = null;\n\n const node = this.path.pop();\n\n if (this.siblingStacks.length > this.path.length + 1) {\n this.siblingStacks.length = this.path.length + 1;\n }\n\n return node;\n }\n\n /**\n * Update current node's attribute values.\n * Useful when attributes are parsed after push.\n * @param {Object} attrValues\n */\n updateCurrent(attrValues) {\n if (this.path.length > 0) {\n const current = this.path[this.path.length - 1];\n if (attrValues !== null && attrValues !== undefined) {\n current.values = attrValues;\n }\n }\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n return this.path.length > 0 ? this.path[this.path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n return this.path.length > 0 ? this.path[this.path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n if (this.path.length === 0) return undefined;\n return this.path[this.path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n if (this.path.length === 0) return false;\n const current = this.path[this.path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n const sep = separator || this.separator;\n const isDefault = (sep === this.separator && includeNamespace === true);\n\n if (isDefault) {\n if (this._pathStringCache !== null) {\n return this._pathStringCache;\n }\n const result = this.path.map(n =>\n (n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n this._pathStringCache = result;\n return result;\n }\n\n return this.path.map(n =>\n (includeNamespace && n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this.path.map(n => n.tag);\n }\n\n /**\n * Reset the path to empty.\n */\n reset() {\n this._pathStringCache = null;\n this.path = [];\n this.siblingStacks = [];\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n const segments = expression.segments;\n\n if (segments.length === 0) {\n return false;\n }\n\n if (expression.hasDeepWildcard()) {\n return this._matchWithDeepWildcard(segments);\n }\n\n return this._matchSimple(segments);\n }\n\n /**\n * @private\n */\n _matchSimple(segments) {\n if (this.path.length !== segments.length) {\n return false;\n }\n\n for (let i = 0; i < segments.length; i++) {\n if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * @private\n */\n _matchWithDeepWildcard(segments) {\n let pathIdx = this.path.length - 1;\n let segIdx = segments.length - 1;\n\n while (segIdx >= 0 && pathIdx >= 0) {\n const segment = segments[segIdx];\n\n if (segment.type === 'deep-wildcard') {\n segIdx--;\n\n if (segIdx < 0) {\n return true;\n }\n\n const nextSeg = segments[segIdx];\n let found = false;\n\n for (let i = pathIdx; i >= 0; i--) {\n if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) {\n pathIdx = i - 1;\n segIdx--;\n found = true;\n break;\n }\n }\n\n if (!found) {\n return false;\n }\n } else {\n if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) {\n return false;\n }\n pathIdx--;\n segIdx--;\n }\n }\n\n return segIdx < 0;\n }\n\n /**\n * @private\n */\n _matchSegment(segment, node, isCurrentNode) {\n if (segment.tag !== '*' && segment.tag !== node.tag) {\n return false;\n }\n\n if (segment.namespace !== undefined) {\n if (segment.namespace !== '*' && segment.namespace !== node.namespace) {\n return false;\n }\n }\n\n if (segment.attrName !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n if (!node.values || !(segment.attrName in node.values)) {\n return false;\n }\n\n if (segment.attrValue !== undefined) {\n if (String(node.values[segment.attrName]) !== String(segment.attrValue)) {\n return false;\n }\n }\n }\n\n if (segment.position !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n const counter = node.counter ?? 0;\n\n if (segment.position === 'first' && counter !== 0) {\n return false;\n } else if (segment.position === 'odd' && counter % 2 !== 1) {\n return false;\n } else if (segment.position === 'even' && counter % 2 !== 0) {\n return false;\n } else if (segment.position === 'nth' && counter !== segment.positionValue) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this);\n }\n\n /**\n * Create a snapshot of current state.\n * @returns {Object}\n */\n snapshot() {\n return {\n path: this.path.map(node => ({ ...node })),\n siblingStacks: this.siblingStacks.map(map => new Map(map))\n };\n }\n\n /**\n * Restore state from snapshot.\n * @param {Object} snapshot\n */\n restore(snapshot) {\n this._pathStringCache = null;\n this.path = snapshot.path.map(node => ({ ...node }));\n this.siblingStacks = snapshot.siblingStacks.map(map => new Map(map));\n }\n\n /**\n * Return the read-only {@link MatcherView} for this matcher.\n *\n * The same instance is returned on every call — no allocation occurs.\n * It always reflects the current parser state and is safe to pass to\n * user callbacks without risk of accidental mutation.\n *\n * @returns {MatcherView}\n *\n * @example\n * const view = matcher.readOnly();\n * // pass view to callbacks — it stays in sync automatically\n * view.matches(expr); // ✓\n * view.getCurrentTag(); // ✓\n * // view.push(...) // ✗ method does not exist — caught by TypeScript\n */\n readOnly() {\n return this._view;\n }\n}","/**\n * Expression - Parses and stores a tag pattern expression\n * \n * Patterns are parsed once and stored in an optimized structure for fast matching.\n * \n * @example\n * const expr = new Expression(\"root.users.user\");\n * const expr2 = new Expression(\"..user[id]:first\");\n * const expr3 = new Expression(\"root/users/user\", { separator: '/' });\n */\nexport default class Expression {\n /**\n * Create a new Expression\n * @param {string} pattern - Pattern string (e.g., \"root.users.user\", \"..user[id]\")\n * @param {Object} options - Configuration options\n * @param {string} options.separator - Path separator (default: '.')\n */\n constructor(pattern, options = {}, data) {\n this.pattern = pattern;\n this.separator = options.separator || '.';\n this.segments = this._parse(pattern);\n this.data = data;\n // Cache expensive checks for performance (O(1) instead of O(n))\n this._hasDeepWildcard = this.segments.some(seg => seg.type === 'deep-wildcard');\n this._hasAttributeCondition = this.segments.some(seg => seg.attrName !== undefined);\n this._hasPositionSelector = this.segments.some(seg => seg.position !== undefined);\n }\n\n /**\n * Parse pattern string into segments\n * @private\n * @param {string} pattern - Pattern to parse\n * @returns {Array} Array of segment objects\n */\n _parse(pattern) {\n const segments = [];\n\n // Split by separator but handle \"..\" specially\n let i = 0;\n let currentPart = '';\n\n while (i < pattern.length) {\n if (pattern[i] === this.separator) {\n // Check if next char is also separator (deep wildcard)\n if (i + 1 < pattern.length && pattern[i + 1] === this.separator) {\n // Flush current part if any\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n currentPart = '';\n }\n // Add deep wildcard\n segments.push({ type: 'deep-wildcard' });\n i += 2; // Skip both separators\n } else {\n // Regular separator\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n currentPart = '';\n i++;\n }\n } else {\n currentPart += pattern[i];\n i++;\n }\n }\n\n // Flush remaining part\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n\n return segments;\n }\n\n /**\n * Parse a single segment\n * @private\n * @param {string} part - Segment string (e.g., \"user\", \"ns::user\", \"user[id]\", \"ns::user:first\")\n * @returns {Object} Segment object\n */\n _parseSegment(part) {\n const segment = { type: 'tag' };\n\n // NEW NAMESPACE SYNTAX (v2.0):\n // ============================\n // Namespace uses DOUBLE colon (::)\n // Position uses SINGLE colon (:)\n // \n // Examples:\n // \"user\" → tag\n // \"user:first\" → tag + position\n // \"user[id]\" → tag + attribute\n // \"user[id]:first\" → tag + attribute + position\n // \"ns::user\" → namespace + tag\n // \"ns::user:first\" → namespace + tag + position\n // \"ns::user[id]\" → namespace + tag + attribute\n // \"ns::user[id]:first\" → namespace + tag + attribute + position\n // \"ns::first\" → namespace + tag named \"first\" (NO ambiguity!)\n //\n // This eliminates all ambiguity:\n // :: = namespace separator\n // : = position selector\n // [] = attributes\n\n // Step 1: Extract brackets [attr] or [attr=value]\n let bracketContent = null;\n let withoutBrackets = part;\n\n const bracketMatch = part.match(/^([^\\[]+)(\\[[^\\]]*\\])(.*)$/);\n if (bracketMatch) {\n withoutBrackets = bracketMatch[1] + bracketMatch[3];\n if (bracketMatch[2]) {\n const content = bracketMatch[2].slice(1, -1);\n if (content) {\n bracketContent = content;\n }\n }\n }\n\n // Step 2: Check for namespace (double colon ::)\n let namespace = undefined;\n let tagAndPosition = withoutBrackets;\n\n if (withoutBrackets.includes('::')) {\n const nsIndex = withoutBrackets.indexOf('::');\n namespace = withoutBrackets.substring(0, nsIndex).trim();\n tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim(); // Skip ::\n\n if (!namespace) {\n throw new Error(`Invalid namespace in pattern: ${part}`);\n }\n }\n\n // Step 3: Parse tag and position (single colon :)\n let tag = undefined;\n let positionMatch = null;\n\n if (tagAndPosition.includes(':')) {\n const colonIndex = tagAndPosition.lastIndexOf(':'); // Use last colon for position\n const tagPart = tagAndPosition.substring(0, colonIndex).trim();\n const posPart = tagAndPosition.substring(colonIndex + 1).trim();\n\n // Verify position is a valid keyword\n const isPositionKeyword = ['first', 'last', 'odd', 'even'].includes(posPart) ||\n /^nth\\(\\d+\\)$/.test(posPart);\n\n if (isPositionKeyword) {\n tag = tagPart;\n positionMatch = posPart;\n } else {\n // Not a valid position keyword, treat whole thing as tag\n tag = tagAndPosition;\n }\n } else {\n tag = tagAndPosition;\n }\n\n if (!tag) {\n throw new Error(`Invalid segment pattern: ${part}`);\n }\n\n segment.tag = tag;\n if (namespace) {\n segment.namespace = namespace;\n }\n\n // Step 4: Parse attributes\n if (bracketContent) {\n if (bracketContent.includes('=')) {\n const eqIndex = bracketContent.indexOf('=');\n segment.attrName = bracketContent.substring(0, eqIndex).trim();\n segment.attrValue = bracketContent.substring(eqIndex + 1).trim();\n } else {\n segment.attrName = bracketContent.trim();\n }\n }\n\n // Step 5: Parse position selector\n if (positionMatch) {\n const nthMatch = positionMatch.match(/^nth\\((\\d+)\\)$/);\n if (nthMatch) {\n segment.position = 'nth';\n segment.positionValue = parseInt(nthMatch[1], 10);\n } else {\n segment.position = positionMatch;\n }\n }\n\n return segment;\n }\n\n /**\n * Get the number of segments\n * @returns {number}\n */\n get length() {\n return this.segments.length;\n }\n\n /**\n * Check if expression contains deep wildcard\n * @returns {boolean}\n */\n hasDeepWildcard() {\n return this._hasDeepWildcard;\n }\n\n /**\n * Check if expression has attribute conditions\n * @returns {boolean}\n */\n hasAttributeCondition() {\n return this._hasAttributeCondition;\n }\n\n /**\n * Check if expression has position selectors\n * @returns {boolean}\n */\n hasPositionSelector() {\n return this._hasPositionSelector;\n }\n\n /**\n * Get string representation\n * @returns {string}\n */\n toString() {\n return this.pattern;\n }\n}","/**\n * ExpressionSet - An indexed collection of Expressions for efficient bulk matching\n *\n * Instead of iterating all expressions on every tag, ExpressionSet pre-indexes\n * them at insertion time by depth and terminal tag name. At match time, only\n * the relevant bucket is evaluated — typically reducing checks from O(E) to O(1)\n * lookup plus O(small bucket) matches.\n *\n * Three buckets are maintained:\n * - `_byDepthAndTag` — exact depth + exact tag name (tightest, used first)\n * - `_wildcardByDepth` — exact depth + wildcard tag `*` (depth-matched only)\n * - `_deepWildcards` — expressions containing `..` (cannot be depth-indexed)\n *\n * @example\n * import { Expression, ExpressionSet } from 'fast-xml-tagger';\n *\n * // Build once at config time\n * const stopNodes = new ExpressionSet();\n * stopNodes.add(new Expression('root.users.user'));\n * stopNodes.add(new Expression('root.config.setting'));\n * stopNodes.add(new Expression('..script'));\n *\n * // Query on every tag — hot path\n * if (stopNodes.matchesAny(matcher)) { ... }\n */\nexport default class ExpressionSet {\n constructor() {\n /** @type {Map} depth:tag → expressions */\n this._byDepthAndTag = new Map();\n\n /** @type {Map} depth → wildcard-tag expressions */\n this._wildcardByDepth = new Map();\n\n /** @type {import('./Expression.js').default[]} expressions containing deep wildcard (..) */\n this._deepWildcards = [];\n\n /** @type {Set} pattern strings already added — used for deduplication */\n this._patterns = new Set();\n\n /** @type {boolean} whether the set is sealed against further additions */\n this._sealed = false;\n }\n\n /**\n * Add an Expression to the set.\n * Duplicate patterns (same pattern string) are silently ignored.\n *\n * @param {import('./Expression.js').default} expression - A pre-constructed Expression instance\n * @returns {this} for chaining\n * @throws {TypeError} if called after seal()\n *\n * @example\n * set.add(new Expression('root.users.user'));\n * set.add(new Expression('..script'));\n */\n add(expression) {\n if (this._sealed) {\n throw new TypeError(\n 'ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.'\n );\n }\n\n // Deduplicate by pattern string\n if (this._patterns.has(expression.pattern)) return this;\n this._patterns.add(expression.pattern);\n\n if (expression.hasDeepWildcard()) {\n this._deepWildcards.push(expression);\n return this;\n }\n\n const depth = expression.length;\n const lastSeg = expression.segments[expression.segments.length - 1];\n const tag = lastSeg?.tag;\n\n if (!tag || tag === '*') {\n // Can index by depth but not by tag\n if (!this._wildcardByDepth.has(depth)) this._wildcardByDepth.set(depth, []);\n this._wildcardByDepth.get(depth).push(expression);\n } else {\n // Tightest bucket: depth + tag\n const key = `${depth}:${tag}`;\n if (!this._byDepthAndTag.has(key)) this._byDepthAndTag.set(key, []);\n this._byDepthAndTag.get(key).push(expression);\n }\n\n return this;\n }\n\n /**\n * Add multiple expressions at once.\n *\n * @param {import('./Expression.js').default[]} expressions - Array of Expression instances\n * @returns {this} for chaining\n *\n * @example\n * set.addAll([\n * new Expression('root.users.user'),\n * new Expression('root.config.setting'),\n * ]);\n */\n addAll(expressions) {\n for (const expr of expressions) this.add(expr);\n return this;\n }\n\n /**\n * Check whether a pattern string is already present in the set.\n *\n * @param {import('./Expression.js').default} expression\n * @returns {boolean}\n */\n has(expression) {\n return this._patterns.has(expression.pattern);\n }\n\n /**\n * Number of expressions in the set.\n * @type {number}\n */\n get size() {\n return this._patterns.size;\n }\n\n /**\n * Seal the set against further modifications.\n * Useful to prevent accidental mutations after config is built.\n * Calling add() or addAll() on a sealed set throws a TypeError.\n *\n * @returns {this}\n */\n seal() {\n this._sealed = true;\n return this;\n }\n\n /**\n * Whether the set has been sealed.\n * @type {boolean}\n */\n get isSealed() {\n return this._sealed;\n }\n\n /**\n * Test whether the matcher's current path matches any expression in the set.\n *\n * Evaluation order (cheapest → most expensive):\n * 1. Exact depth + tag bucket — O(1) lookup, typically 0–2 expressions\n * 2. Depth-only wildcard bucket — O(1) lookup, rare\n * 3. Deep-wildcard list — always checked, but usually small\n *\n * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)\n * @returns {boolean} true if any expression matches the current path\n *\n * @example\n * if (stopNodes.matchesAny(matcher)) {\n * // handle stop node\n * }\n */\n matchesAny(matcher) {\n return this.findMatch(matcher) !== null;\n }\n /**\n * Find and return the first Expression that matches the matcher's current path.\n *\n * Uses the same evaluation order as matchesAny (cheapest → most expensive):\n * 1. Exact depth + tag bucket\n * 2. Depth-only wildcard bucket\n * 3. Deep-wildcard list\n *\n * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)\n * @returns {import('./Expression.js').default | null} the first matching Expression, or null\n *\n * @example\n * const expr = stopNodes.findMatch(matcher);\n * if (expr) {\n * // access expr.config, expr.pattern, etc.\n * }\n */\n findMatch(matcher) {\n const depth = matcher.getDepth();\n const tag = matcher.getCurrentTag();\n\n // 1. Tightest bucket — most expressions live here\n const exactKey = `${depth}:${tag}`;\n const exactBucket = this._byDepthAndTag.get(exactKey);\n if (exactBucket) {\n for (let i = 0; i < exactBucket.length; i++) {\n if (matcher.matches(exactBucket[i])) return exactBucket[i];\n }\n }\n\n // 2. Depth-matched wildcard-tag expressions\n const wildcardBucket = this._wildcardByDepth.get(depth);\n if (wildcardBucket) {\n for (let i = 0; i < wildcardBucket.length; i++) {\n if (matcher.matches(wildcardBucket[i])) return wildcardBucket[i];\n }\n }\n\n // 3. Deep wildcards — cannot be pre-filtered by depth or tag\n for (let i = 0; i < this._deepWildcards.length; i++) {\n if (matcher.matches(this._deepWildcards[i])) return this._deepWildcards[i];\n }\n\n return null;\n }\n}\n","// ---------------------------------------------------------------------------\n// Complete HTML5 named entity reference\n// Organized by logical categories for easy maintenance and selective importing\n// ---------------------------------------------------------------------------\n\n/**\n * Basic Latin & Special Characters\n * @type {Record}\n */\nexport const BASIC_LATIN = {\n amp: '&',\n AMP: '&',\n lt: '<',\n LT: '<',\n gt: '>',\n GT: '>',\n quot: '\"',\n QUOT: '\"',\n apos: \"'\",\n lsquo: '‘',\n rsquo: '’',\n ldquo: '“',\n rdquo: '”',\n lsquor: '‚',\n rsquor: '’',\n ldquor: '„',\n bdquo: '„',\n comma: ',',\n period: '.',\n colon: ':',\n semi: ';',\n excl: '!',\n quest: '?',\n num: '#',\n dollar: '$',\n percent: '%',\n amp: '&',\n ast: '*',\n commat: '@',\n lowbar: '_',\n verbar: '|',\n vert: '|',\n sol: '/',\n bsol: '\\\\',\n lbrace: '{',\n rbrace: '}',\n lbrack: '[',\n rbrack: ']',\n lpar: '(',\n rpar: ')',\n nbsp: '\\u00a0',\n iexcl: '¡',\n cent: '¢',\n pound: '£',\n curren: '¤',\n yen: '¥',\n brvbar: '¦',\n sect: '§',\n uml: '¨',\n copy: '©',\n COPY: '©',\n ordf: 'ª',\n laquo: '«',\n not: '¬',\n shy: '\\u00ad',\n reg: '®',\n REG: '®',\n macr: '¯',\n deg: '°',\n plusmn: '±',\n sup2: '²',\n sup3: '³',\n acute: '´',\n micro: 'µ',\n para: '¶',\n middot: '·',\n cedil: '¸',\n sup1: '¹',\n ordm: 'º',\n raquo: '»',\n frac14: '¼',\n frac12: '½',\n half: '½',\n frac34: '¾',\n iquest: '¿',\n times: '×',\n div: '÷',\n divide: '÷',\n};\n\n/**\n * Latin Extended & Accented Letters (A-Z)\n * @type {Record}\n */\nexport const LATIN_ACCENTS = {\n Agrave: 'À',\n agrave: 'à',\n Aacute: 'Á',\n aacute: 'á',\n Acirc: 'Â',\n acirc: 'â',\n Atilde: 'Ã',\n atilde: 'ã',\n Auml: 'Ä',\n auml: 'ä',\n Aring: 'Å',\n aring: 'å',\n AElig: 'Æ',\n aelig: 'æ',\n Ccedil: 'Ç',\n ccedil: 'ç',\n Egrave: 'È',\n egrave: 'è',\n Eacute: 'É',\n eacute: 'é',\n Ecirc: 'Ê',\n ecirc: 'ê',\n Euml: 'Ë',\n euml: 'ë',\n Igrave: 'Ì',\n igrave: 'ì',\n Iacute: 'Í',\n iacute: 'í',\n Icirc: 'Î',\n icirc: 'î',\n Iuml: 'Ï',\n iuml: 'ï',\n ETH: 'Ð',\n eth: 'ð',\n Ntilde: 'Ñ',\n ntilde: 'ñ',\n Ograve: 'Ò',\n ograve: 'ò',\n Oacute: 'Ó',\n oacute: 'ó',\n Ocirc: 'Ô',\n ocirc: 'ô',\n Otilde: 'Õ',\n otilde: 'õ',\n Ouml: 'Ö',\n ouml: 'ö',\n Oslash: 'Ø',\n oslash: 'ø',\n Ugrave: 'Ù',\n ugrave: 'ù',\n Uacute: 'Ú',\n uacute: 'ú',\n Ucirc: 'Û',\n ucirc: 'û',\n Uuml: 'Ü',\n uuml: 'ü',\n Yacute: 'Ý',\n yacute: 'ý',\n THORN: 'Þ',\n thorn: 'þ',\n szlig: 'ß',\n yuml: 'ÿ',\n Yuml: 'Ÿ',\n};\n\n/**\n * Latin Extended (Letters with diacritics)\n * @type {Record}\n */\nexport const LATIN_EXTENDED = {\n Amacr: 'Ā',\n amacr: 'ā',\n Abreve: 'Ă',\n abreve: 'ă',\n Aogon: 'Ą',\n aogon: 'ą',\n Cacute: 'Ć',\n cacute: 'ć',\n Ccirc: 'Ĉ',\n ccirc: 'ĉ',\n Cdot: 'Ċ',\n cdot: 'ċ',\n Ccaron: 'Č',\n ccaron: 'č',\n Dcaron: 'Ď',\n dcaron: 'ď',\n Dstrok: 'Đ',\n dstrok: 'đ',\n Emacr: 'Ē',\n emacr: 'ē',\n Ecaron: 'Ě',\n ecaron: 'ě',\n Edot: 'Ė',\n edot: 'ė',\n Eogon: 'Ę',\n eogon: 'ę',\n Gcirc: 'Ĝ',\n gcirc: 'ĝ',\n Gbreve: 'Ğ',\n gbreve: 'ğ',\n Gdot: 'Ġ',\n gdot: 'ġ',\n Gcedil: 'Ģ',\n Hcirc: 'Ĥ',\n hcirc: 'ĥ',\n Hstrok: 'Ħ',\n hstrok: 'ħ',\n Itilde: 'Ĩ',\n itilde: 'ĩ',\n Imacr: 'Ī',\n imacr: 'ī',\n Iogon: 'Į',\n iogon: 'į',\n Idot: 'İ',\n IJlig: 'IJ',\n ijlig: 'ij',\n Jcirc: 'Ĵ',\n jcirc: 'ĵ',\n Kcedil: 'Ķ',\n kcedil: 'ķ',\n kgreen: 'ĸ',\n Lacute: 'Ĺ',\n lacute: 'ĺ',\n Lcedil: 'Ļ',\n lcedil: 'ļ',\n Lcaron: 'Ľ',\n lcaron: 'ľ',\n Lmidot: 'Ŀ',\n lmidot: 'ŀ',\n Lstrok: 'Ł',\n lstrok: 'ł',\n Nacute: 'Ń',\n nacute: 'ń',\n Ncaron: 'Ň',\n ncaron: 'ň',\n Ncedil: 'Ņ',\n ncedil: 'ņ',\n ENG: 'Ŋ',\n eng: 'ŋ',\n Omacr: 'Ō',\n omacr: 'ō',\n Odblac: 'Ő',\n odblac: 'ő',\n OElig: 'Œ',\n oelig: 'œ',\n Racute: 'Ŕ',\n racute: 'ŕ',\n Rcaron: 'Ř',\n rcaron: 'ř',\n Rcedil: 'Ŗ',\n rcedil: 'ŗ',\n Sacute: 'Ś',\n sacute: 'ś',\n Scirc: 'Ŝ',\n scirc: 'ŝ',\n Scedil: 'Ş',\n scedil: 'ş',\n Scaron: 'Š',\n scaron: 'š',\n Tcedil: 'Ţ',\n tcedil: 'ţ',\n Tcaron: 'Ť',\n tcaron: 'ť',\n Tstrok: 'Ŧ',\n tstrok: 'ŧ',\n Utilde: 'Ũ',\n utilde: 'ũ',\n Umacr: 'Ū',\n umacr: 'ū',\n Ubreve: 'Ŭ',\n ubreve: 'ŭ',\n Uring: 'Ů',\n uring: 'ů',\n Udblac: 'Ű',\n udblac: 'ű',\n Uogon: 'Ų',\n uogon: 'ų',\n Wcirc: 'Ŵ',\n wcirc: 'ŵ',\n Ycirc: 'Ŷ',\n ycirc: 'ŷ',\n Zacute: 'Ź',\n zacute: 'ź',\n Zdot: 'Ż',\n zdot: 'ż',\n Zcaron: 'Ž',\n zcaron: 'ž',\n};\n\n/**\n * Greek Letters\n * @type {Record}\n */\nexport const GREEK = {\n Alpha: 'Α',\n alpha: 'α',\n Beta: 'Β',\n beta: 'β',\n Gamma: 'Γ',\n gamma: 'γ',\n Delta: 'Δ',\n delta: 'δ',\n Epsilon: 'Ε',\n epsilon: 'ε',\n epsiv: 'ϵ',\n varepsilon: 'ϵ',\n Zeta: 'Ζ',\n zeta: 'ζ',\n Eta: 'Η',\n eta: 'η',\n Theta: 'Θ',\n theta: 'θ',\n thetasym: 'ϑ',\n vartheta: 'ϑ',\n Iota: 'Ι',\n iota: 'ι',\n Kappa: 'Κ',\n kappa: 'κ',\n kappav: 'ϰ',\n varkappa: 'ϰ',\n Lambda: 'Λ',\n lambda: 'λ',\n Mu: 'Μ',\n mu: 'μ',\n Nu: 'Ν',\n nu: 'ν',\n Xi: 'Ξ',\n xi: 'ξ',\n Omicron: 'Ο',\n omicron: 'ο',\n Pi: 'Π',\n pi: 'π',\n piv: 'ϖ',\n varpi: 'ϖ',\n Rho: 'Ρ',\n rho: 'ρ',\n rhov: 'ϱ',\n varrho: 'ϱ',\n Sigma: 'Σ',\n sigma: 'σ',\n sigmaf: 'ς',\n sigmav: 'ς',\n varsigma: 'ς',\n Tau: 'Τ',\n tau: 'τ',\n Upsilon: 'Υ',\n upsilon: 'υ',\n upsi: 'υ',\n Upsi: 'ϒ',\n upsih: 'ϒ',\n Phi: 'Φ',\n phi: 'φ',\n phiv: 'ϕ',\n varphi: 'ϕ',\n Chi: 'Χ',\n chi: 'χ',\n Psi: 'Ψ',\n psi: 'ψ',\n Omega: 'Ω',\n omega: 'ω',\n ohm: 'Ω',\n Gammad: 'Ϝ',\n gammad: 'ϝ',\n digamma: 'ϝ',\n};\n\n/**\n * Cyrillic Letters\n * @type {Record}\n */\nexport const CYRILLIC = {\n Afr: '𝔄',\n afr: '𝔞',\n Acy: 'А',\n acy: 'а',\n Bcy: 'Б',\n bcy: 'б',\n Vcy: 'В',\n vcy: 'в',\n Gcy: 'Г',\n gcy: 'г',\n Dcy: 'Д',\n dcy: 'д',\n IEcy: 'Е',\n iecy: 'е',\n IOcy: 'Ё',\n iocy: 'ё',\n ZHcy: 'Ж',\n zhcy: 'ж',\n Zcy: 'З',\n zcy: 'з',\n Icy: 'И',\n icy: 'и',\n Jcy: 'Й',\n jcy: 'й',\n Kcy: 'К',\n kcy: 'к',\n Lcy: 'Л',\n lcy: 'л',\n Mcy: 'М',\n mcy: 'м',\n Ncy: 'Н',\n ncy: 'н',\n Ocy: 'О',\n ocy: 'о',\n Pcy: 'П',\n pcy: 'п',\n Rcy: 'Р',\n rcy: 'р',\n Scy: 'С',\n scy: 'с',\n Tcy: 'Т',\n tcy: 'т',\n Ucy: 'У',\n ucy: 'у',\n Fcy: 'Ф',\n fcy: 'ф',\n KHcy: 'Х',\n khcy: 'х',\n TScy: 'Ц',\n tscy: 'ц',\n CHcy: 'Ч',\n chcy: 'ч',\n SHcy: 'Ш',\n shcy: 'ш',\n SHCHcy: 'Щ',\n shchcy: 'щ',\n HARDcy: 'Ъ',\n hardcy: 'ъ',\n Ycy: 'Ы',\n ycy: 'ы',\n SOFTcy: 'Ь',\n softcy: 'ь',\n Ecy: 'Э',\n ecy: 'э',\n YUcy: 'Ю',\n yucy: 'ю',\n YAcy: 'Я',\n yacy: 'я',\n DJcy: 'Ђ',\n djcy: 'ђ',\n GJcy: 'Ѓ',\n gjcy: 'ѓ',\n Jukcy: 'Є',\n jukcy: 'є',\n DScy: 'Ѕ',\n dscy: 'ѕ',\n Iukcy: 'І',\n iukcy: 'і',\n YIcy: 'Ї',\n yicy: 'ї',\n Jsercy: 'Ј',\n jsercy: 'ј',\n LJcy: 'Љ',\n ljcy: 'љ',\n NJcy: 'Њ',\n njcy: 'њ',\n TSHcy: 'Ћ',\n tshcy: 'ћ',\n KJcy: 'Ќ',\n kjcy: 'ќ',\n Ubrcy: 'Ў',\n ubrcy: 'ў',\n DZcy: 'Џ',\n dzcy: 'џ',\n};\n\n/**\n * Mathematical Operators & Relations\n * @type {Record}\n */\nexport const MATH = {\n plus: '+',\n minus: '−',\n mnplus: '∓',\n mp: '∓',\n pm: '±',\n times: '×',\n div: '÷',\n divide: '÷',\n sdot: '⋅',\n star: '☆',\n starf: '★',\n bigstar: '★',\n lowast: '∗',\n ast: '*',\n midast: '*',\n compfn: '∘',\n smallcircle: '∘',\n bullet: '•',\n bull: '•',\n nbsp: '\\u00a0',\n hellip: '…',\n mldr: '…',\n prime: '′',\n Prime: '″',\n tprime: '‴',\n bprime: '‵',\n backprime: '‵',\n minus: '−',\n minusd: '∸',\n dotminus: '∸',\n plusdo: '∔',\n dotplus: '∔',\n plusmn: '±',\n minusplus: '∓',\n mnplus: '∓',\n mp: '∓',\n setminus: '∖',\n smallsetminus: '∖',\n Backslash: '∖',\n setmn: '∖',\n ssetmn: '∖',\n lowbar: '_',\n verbar: '|',\n vert: '|',\n VerticalLine: '|',\n colon: ':',\n Colon: '∷',\n Proportion: '∷',\n ratio: '∶',\n equals: '=',\n ne: '≠',\n nequiv: '≢',\n equiv: '≡',\n Congruent: '≡',\n sim: '∼',\n thicksim: '∼',\n thksim: '∼',\n sime: '≃',\n simeq: '≃',\n TildeEqual: '≃',\n asymp: '≈',\n approx: '≈',\n thickapprox: '≈',\n thkap: '≈',\n TildeTilde: '≈',\n ncong: '≇',\n cong: '≅',\n TildeFullEqual: '≅',\n asympeq: '≍',\n CupCap: '≍',\n bump: '≎',\n Bumpeq: '≎',\n HumpDownHump: '≎',\n bumpe: '≏',\n bumpeq: '≏',\n HumpEqual: '≏',\n dotminus: '∸',\n minusd: '∸',\n plusdo: '∔',\n dotplus: '∔',\n le: '≤',\n LessEqual: '≤',\n ge: '≥',\n GreaterEqual: '≥',\n lesseqgtr: '⋚',\n lesseqqgtr: '⪋',\n greater: '>',\n less: '<',\n};\n\n/**\n * Mathematical Operators (Advanced)\n * @type {Record}\n */\nexport const MATH_ADVANCED = {\n alefsym: 'ℵ',\n aleph: 'ℵ',\n beth: 'ℶ',\n gimel: 'ℷ',\n daleth: 'ℸ',\n forall: '∀',\n ForAll: '∀',\n part: '∂',\n PartialD: '∂',\n exist: '∃',\n Exists: '∃',\n nexist: '∄',\n nexists: '∄',\n empty: '∅',\n emptyset: '∅',\n emptyv: '∅',\n varnothing: '∅',\n nabla: '∇',\n Del: '∇',\n isin: '∈',\n isinv: '∈',\n in: '∈',\n Element: '∈',\n notin: '∉',\n notinva: '∉',\n ni: '∋',\n niv: '∋',\n SuchThat: '∋',\n ReverseElement: '∋',\n notni: '∌',\n notniva: '∌',\n prod: '∏',\n Product: '∏',\n coprod: '∐',\n Coproduct: '∐',\n sum: '∑',\n Sum: '∑',\n minus: '−',\n mp: '∓',\n plusdo: '∔',\n dotplus: '∔',\n setminus: '∖',\n lowast: '∗',\n radic: '√',\n Sqrt: '√',\n prop: '∝',\n propto: '∝',\n Proportional: '∝',\n varpropto: '∝',\n infin: '∞',\n infintie: '⧝',\n ang: '∠',\n angle: '∠',\n angmsd: '∡',\n measuredangle: '∡',\n angsph: '∢',\n mid: '∣',\n VerticalBar: '∣',\n nmid: '∤',\n nsmid: '∤',\n npar: '∦',\n parallel: '∥',\n spar: '∥',\n nparallel: '∦',\n nspar: '∦',\n and: '∧',\n wedge: '∧',\n or: '∨',\n vee: '∨',\n cap: '∩',\n cup: '∪',\n int: '∫',\n Integral: '∫',\n conint: '∮',\n ContourIntegral: '∮',\n Conint: '∯',\n DoubleContourIntegral: '∯',\n Cconint: '∰',\n there4: '∴',\n therefore: '∴',\n Therefore: '∴',\n becaus: '∵',\n because: '∵',\n Because: '∵',\n ratio: '∶',\n Proportion: '∷',\n minusd: '∸',\n dotminus: '∸',\n mDDot: '∺',\n homtht: '∻',\n sim: '∼',\n bsimg: '∽',\n backsim: '∽',\n ac: '∾',\n mstpos: '∾',\n acd: '∿',\n VerticalTilde: '≀',\n wr: '≀',\n wreath: '≀',\n nsime: '≄',\n nsimeq: '≄',\n nsimeq: '≄',\n ncong: '≇',\n simne: '≆',\n ncongdot: '⩭̸',\n ngsim: '≵',\n nsim: '≁',\n napprox: '≉',\n nap: '≉',\n ngeq: '≱',\n nge: '≱',\n nleq: '≰',\n nle: '≰',\n ngtr: '≯',\n ngt: '≯',\n nless: '≮',\n nlt: '≮',\n nprec: '⊀',\n npr: '⊀',\n nsucc: '⊁',\n nsc: '⊁',\n};\n\n/**\n * Arrows\n * @type {Record}\n */\nexport const ARROWS = {\n larr: '←',\n leftarrow: '←',\n LeftArrow: '←',\n uarr: '↑',\n uparrow: '↑',\n UpArrow: '↑',\n rarr: '→',\n rightarrow: '→',\n RightArrow: '→',\n darr: '↓',\n downarrow: '↓',\n DownArrow: '↓',\n harr: '↔',\n leftrightarrow: '↔',\n LeftRightArrow: '↔',\n varr: '↕',\n updownarrow: '↕',\n UpDownArrow: '↕',\n nwarr: '↖',\n nwarrow: '↖',\n UpperLeftArrow: '↖',\n nearr: '↗',\n nearrow: '↗',\n UpperRightArrow: '↗',\n searr: '↘',\n searrow: '↘',\n LowerRightArrow: '↘',\n swarr: '↙',\n swarrow: '↙',\n LowerLeftArrow: '↙',\n lArr: '⇐',\n Leftarrow: '⇐',\n uArr: '⇑',\n Uparrow: '⇑',\n rArr: '⇒',\n Rightarrow: '⇒',\n dArr: '⇓',\n Downarrow: '⇓',\n hArr: '⇔',\n Leftrightarrow: '⇔',\n iff: '⇔',\n vArr: '⇕',\n Updownarrow: '⇕',\n lAarr: '⇚',\n Lleftarrow: '⇚',\n rAarr: '⇛',\n Rrightarrow: '⇛',\n lrarr: '⇆',\n leftrightarrows: '⇆',\n rlarr: '⇄',\n rightleftarrows: '⇄',\n lrhar: '⇋',\n leftrightharpoons: '⇋',\n ReverseEquilibrium: '⇋',\n rlhar: '⇌',\n rightleftharpoons: '⇌',\n Equilibrium: '⇌',\n udarr: '⇅',\n UpArrowDownArrow: '⇅',\n duarr: '⇵',\n DownArrowUpArrow: '⇵',\n llarr: '⇇',\n leftleftarrows: '⇇',\n rrarr: '⇉',\n rightrightarrows: '⇉',\n ddarr: '⇊',\n downdownarrows: '⇊',\n har: '↽',\n lhard: '↽',\n leftharpoondown: '↽',\n lharu: '↼',\n leftharpoonup: '↼',\n rhard: '⇁',\n rightharpoondown: '⇁',\n rharu: '⇀',\n rightharpoonup: '⇀',\n lsh: '↰',\n Lsh: '↰',\n rsh: '↱',\n Rsh: '↱',\n ldsh: '↲',\n rdsh: '↳',\n hookleftarrow: '↩',\n hookrightarrow: '↪',\n mapstoleft: '↤',\n mapstoup: '↥',\n map: '↦',\n mapsto: '↦',\n mapstodown: '↧',\n crarr: '↵',\n nwarrow: '↖',\n nearrow: '↗',\n searrow: '↘',\n swarrow: '↙',\n nleftarrow: '↚',\n nleftrightarrow: '↮',\n nrightarrow: '↛',\n nrarr: '↛',\n larrtl: '↢',\n rarrtl: '↣',\n leftarrowtail: '↢',\n rightarrowtail: '↣',\n twoheadleftarrow: '↞',\n twoheadrightarrow: '↠',\n Larr: '↞',\n Rarr: '↠',\n larrhk: '↩',\n rarrhk: '↪',\n larrlp: '↫',\n looparrowleft: '↫',\n rarrlp: '↬',\n looparrowright: '↬',\n harrw: '↭',\n leftrightsquigarrow: '↭',\n nrarrw: '↝̸',\n rarrw: '↝',\n rightsquigarrow: '↝',\n larrbfs: '⤟',\n rarrbfs: '⤠',\n nvHarr: '⤄',\n nvlArr: '⤂',\n nvrArr: '⤃',\n larrfs: '⤝',\n rarrfs: '⤞',\n Map: '⤅',\n larrsim: '⥳',\n rarrsim: '⥴',\n harrcir: '⥈',\n Uarrocir: '⥉',\n lurdshar: '⥊',\n ldrdhar: '⥧',\n ldrushar: '⥋',\n rdldhar: '⥩',\n lrhard: '⥭',\n rlhar: '⇌',\n uharr: '↾',\n uharl: '↿',\n dharr: '⇂',\n dharl: '⇃',\n Uarr: '↟',\n Darr: '↡',\n zigrarr: '⇝',\n nwArr: '⇖',\n neArr: '⇗',\n seArr: '⇘',\n swArr: '⇙',\n nharr: '↮',\n nhArr: '⇎',\n nlarr: '↚',\n nlArr: '⇍',\n nrarr: '↛',\n nrArr: '⇏',\n larrb: '⇤',\n LeftArrowBar: '⇤',\n rarrb: '⇥',\n RightArrowBar: '⇥',\n};\n\n/**\n * Geometric Shapes\n * @type {Record}\n */\nexport const SHAPES = {\n square: '□',\n Square: '□',\n squ: '□',\n squf: '▪',\n squarf: '▪',\n blacksquar: '▪',\n blacksquare: '▪',\n FilledVerySmallSquare: '▪',\n blk34: '▓',\n blk12: '▒',\n blk14: '░',\n block: '█',\n srect: '▭',\n rect: '▭',\n sdot: '⋅',\n sdotb: '⊡',\n dotsquare: '⊡',\n triangle: '▵',\n tri: '▵',\n trine: '▵',\n utri: '▵',\n triangledown: '▿',\n dtri: '▿',\n tridown: '▿',\n triangleleft: '◃',\n ltri: '◃',\n triangleright: '▹',\n rtri: '▹',\n blacktriangle: '▴',\n utrif: '▴',\n blacktriangledown: '▾',\n dtrif: '▾',\n blacktriangleleft: '◂',\n ltrif: '◂',\n blacktriangleright: '▸',\n rtrif: '▸',\n loz: '◊',\n lozenge: '◊',\n blacklozenge: '⧫',\n lozf: '⧫',\n bigcirc: '◯',\n xcirc: '◯',\n circ: 'ˆ',\n Circle: '○',\n cir: '○',\n o: '○',\n bullet: '•',\n bull: '•',\n hellip: '…',\n mldr: '…',\n nldr: '‥',\n boxh: '─',\n HorizontalLine: '─',\n boxv: '│',\n boxdr: '┌',\n boxdl: '┐',\n boxur: '└',\n boxul: '┘',\n boxvr: '├',\n boxvl: '┤',\n boxhd: '┬',\n boxhu: '┴',\n boxvh: '┼',\n boxH: '═',\n boxV: '║',\n boxdR: '╒',\n boxDr: '╓',\n boxDR: '╔',\n boxDl: '╕',\n boxdL: '╖',\n boxDL: '╗',\n boxuR: '╘',\n boxUr: '╙',\n boxUR: '╚',\n boxUl: '╜',\n boxuL: '╛',\n boxUL: '╝',\n boxvR: '╞',\n boxVr: '╟',\n boxVR: '╠',\n boxVl: '╢',\n boxvL: '╡',\n boxVL: '╣',\n boxHd: '╤',\n boxhD: '╥',\n boxHD: '╦',\n boxHu: '╧',\n boxhU: '╨',\n boxHU: '╩',\n boxvH: '╪',\n boxVh: '╫',\n boxVH: '╬',\n};\n\n/**\n * Punctuation & Diacritics\n * @type {Record}\n */\nexport const PUNCTUATION = {\n excl: '!',\n iexcl: '¡',\n brvbar: '¦',\n sect: '§',\n uml: '¨',\n copy: '©',\n ordf: 'ª',\n laquo: '«',\n not: '¬',\n shy: '\\u00ad',\n reg: '®',\n macr: '¯',\n deg: '°',\n plusmn: '±',\n sup2: '²',\n sup3: '³',\n acute: '´',\n micro: 'µ',\n para: '¶',\n middot: '·',\n cedil: '¸',\n sup1: '¹',\n ordm: 'º',\n raquo: '»',\n frac14: '¼',\n frac12: '½',\n frac34: '¾',\n iquest: '¿',\n nbsp: '\\u00a0',\n comma: ',',\n period: '.',\n colon: ':',\n semi: ';',\n vert: '|',\n Verbar: '‖',\n verbar: '|',\n dblac: '˝',\n circ: 'ˆ',\n caron: 'ˇ',\n breve: '˘',\n dot: '˙',\n ring: '˚',\n ogon: '˛',\n tilde: '˜',\n DiacriticalGrave: '`',\n DiacriticalAcute: '´',\n DiacriticalTilde: '˜',\n DiacriticalDot: '˙',\n DiacriticalDoubleAcute: '˝',\n grave: '`',\n acute: '´',\n};\n\n/**\n * Currency Symbols\n * @type {Record}\n */\nexport const CURRENCY = {\n cent: '¢',\n pound: '£',\n curren: '¤',\n yen: '¥',\n euro: '€',\n dollar: '$',\n euro: '€',\n fnof: 'ƒ',\n inr: '₹',\n af: '؋',\n birr: 'ብር',\n peso: '₱',\n rub: '₽',\n won: '₩',\n yuan: '¥',\n cedil: '¸',\n};\n\n/**\n * Fractions\n * @type {Record}\n */\nexport const FRACTIONS = {\n frac12: '½',\n half: '½',\n frac13: '⅓',\n frac14: '¼',\n frac15: '⅕',\n frac16: '⅙',\n frac18: '⅛',\n frac23: '⅔',\n frac25: '⅖',\n frac34: '¾',\n frac35: '⅗',\n frac38: '⅜',\n frac45: '⅘',\n frac56: '⅚',\n frac58: '⅝',\n frac78: '⅞',\n frasl: '⁄',\n};\n\n/**\n * Miscellaneous Symbols\n * @type {Record}\n */\nexport const MISC_SYMBOLS = {\n trade: '™',\n TRADE: '™',\n telrec: '⌕',\n target: '⌖',\n ulcorn: '⌜',\n ulcorner: '⌜',\n urcorn: '⌝',\n urcorner: '⌝',\n dlcorn: '⌞',\n llcorner: '⌞',\n drcorn: '⌟',\n lrcorner: '⌟',\n intercal: '⊺',\n intcal: '⊺',\n oplus: '⊕',\n CirclePlus: '⊕',\n ominus: '⊖',\n CircleMinus: '⊖',\n otimes: '⊗',\n CircleTimes: '⊗',\n osol: '⊘',\n odot: '⊙',\n CircleDot: '⊙',\n oast: '⊛',\n circledast: '⊛',\n odash: '⊝',\n circleddash: '⊝',\n ocirc: '⊚',\n circledcirc: '⊚',\n boxplus: '⊞',\n plusb: '⊞',\n boxminus: '⊟',\n minusb: '⊟',\n boxtimes: '⊠',\n timesb: '⊠',\n boxdot: '⊡',\n sdotb: '⊡',\n veebar: '⊻',\n vee: '∨',\n barvee: '⊽',\n and: '∧',\n wedge: '∧',\n Cap: '⋒',\n Cup: '⋓',\n Fork: '⋔',\n pitchfork: '⋔',\n epar: '⋕',\n ltlarr: '⥶',\n nvap: '≍⃒',\n nvsim: '∼⃒',\n nvge: '≥⃒',\n nvle: '≤⃒',\n nvlt: '<⃒',\n nvgt: '>⃒',\n nvltrie: '⊴⃒',\n nvrtrie: '⊵⃒',\n Vdash: '⊩',\n dashv: '⊣',\n vDash: '⊨',\n Vdash: '⊩',\n Vvdash: '⊪',\n nvdash: '⊬',\n nvDash: '⊭',\n nVdash: '⊮',\n nVDash: '⊯',\n};\n\n/**\n * All entities combined (if you need everything)\n * @type {Record}\n */\nexport const ALL_ENTITIES = {\n ...BASIC_LATIN,\n ...LATIN_ACCENTS,\n ...LATIN_EXTENDED,\n ...GREEK,\n ...CYRILLIC,\n ...MATH,\n ...MATH_ADVANCED,\n ...ARROWS,\n ...SHAPES,\n ...PUNCTUATION,\n ...CURRENCY,\n ...FRACTIONS,\n ...MISC_SYMBOLS,\n};\n\nexport const XML = {\n amp: \"&\",\n apos: \"'\",\n gt: \">\",\n lt: \"<\",\n quot: \"\\\"\"\n}\nexport const COMMON_HTML = {\n nbsp: '\\u00a0',\n copy: '\\u00a9',\n reg: '\\u00ae',\n trade: '\\u2122',\n mdash: '\\u2014',\n ndash: '\\u2013',\n hellip: '\\u2026',\n laquo: '\\u00ab',\n raquo: '\\u00bb',\n lsquo: '\\u2018',\n rsquo: '\\u2019',\n ldquo: '\\u201c',\n rdquo: '\\u201d',\n bull: '\\u2022',\n para: '\\u00b6',\n sect: '\\u00a7',\n deg: '\\u00b0',\n frac12: '\\u00bd',\n frac14: '\\u00bc',\n frac34: '\\u00be',\n}\n// ---------------------------------------------------------------------------\n// Note: NUMERIC_ENTITIES (&#NNN; / &#xHH;) are handled by the scanner directly\n// via String.fromCodePoint() without any map lookup.\n// ---------------------------------------------------------------------------","// ---------------------------------------------------------------------------\n// Built-in named entity map (name → replacement string)\n// No regex, no {regex,val} objects — just flat key/value pairs.\n// ---------------------------------------------------------------------------\n\nimport { XML as DEFAULT_XML_ENTITIES } from \"./entities.js\"\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst SPECIAL_CHARS = new Set('!?\\\\\\\\/[]$%{}^&*()<>|+');\n\n/**\n * Validate that an entity name contains no dangerous characters.\n * @param {string} name\n * @returns {string} the name, unchanged\n * @throws {Error} on invalid characters\n */\nfunction validateEntityName(name) {\n if (name[0] === '#') {\n throw new Error(`[EntityReplacer] Invalid character '#' in entity name: \"${name}\"`);\n }\n for (const ch of name) {\n if (SPECIAL_CHARS.has(ch)) {\n throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: \"${name}\"`);\n }\n }\n return name;\n}\n\n/**\n * Merge one or more entity maps into a flat name→string map.\n * Accepts either:\n * - plain string values: { amp: '&' }\n * - legacy {regex,val} / {regx,val}: { lt: { regex: /.../, val: '<' } }\n *\n * Values containing '&' are skipped (recursive expansion risk).\n *\n * @param {...object} maps\n * @returns {Record}\n */\nfunction mergeEntityMaps(...maps) {\n const out = Object.create(null);\n for (const map of maps) {\n if (!map) continue;\n for (const key of Object.keys(map)) {\n const raw = map[key];\n if (typeof raw === 'string') {\n out[key] = raw;\n } else if (raw && typeof raw === 'object' && raw.val !== undefined) {\n // Legacy {regex,val} or {regx,val} — extract the string val only\n const val = raw.val;\n if (typeof val === 'string') {\n out[key] = val;\n }\n // function vals are not supported in the scanner — skip\n }\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// applyLimitsTo helpers\n// ---------------------------------------------------------------------------\n\nconst LIMIT_TIER_EXTERNAL = 'external'; // input/runtime + persistent external maps\nconst LIMIT_TIER_BASE = 'base'; // DEFAULT_XML_ENTITIES + namedEntities (system) maps\nconst LIMIT_TIER_ALL = 'all'; // every entity regardless of tier\n\n/**\n * Resolve `applyLimitsTo` option into a normalised Set of tier strings.\n * Accepted values: 'external' | 'base' | 'all' | string[]\n * Default: 'external' (only untrusted injected entities are counted).\n * @param {string|string[]|undefined} raw\n * @returns {Set}\n */\nfunction parseLimitTiers(raw) {\n if (!raw || raw === LIMIT_TIER_EXTERNAL) return new Set([LIMIT_TIER_EXTERNAL]);\n if (raw === LIMIT_TIER_ALL) return new Set([LIMIT_TIER_ALL]);\n if (raw === LIMIT_TIER_BASE) return new Set([LIMIT_TIER_BASE]);\n if (Array.isArray(raw)) return new Set(raw);\n return new Set([LIMIT_TIER_EXTERNAL]); // safe default for unrecognised values\n}\n\n// ---------------------------------------------------------------------------\n// NCR (Numeric Character Reference) classification\n// ---------------------------------------------------------------------------\n\n// Severity order — higher number = stricter action.\n// Used to enforce minimum action levels for specific codepoint ranges.\nconst NCR_LEVEL = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 });\n\n// XML 1.0 §2.2: allowed chars are #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]\n// Restricted C0: U+0001–U+001F excluding U+0009, U+000A, U+000D\nconst XML10_ALLOWED_C0 = new Set([0x09, 0x0A, 0x0D]);\n\n/**\n * Parse the `ncr` constructor option into flat, hot-path-friendly fields.\n * @param {object|undefined} ncr\n * @returns {{ xmlVersion: number, onLevel: number, nullLevel: number }}\n */\nfunction parseNCRConfig(ncr) {\n if (!ncr) {\n return { xmlVersion: 1.0, onLevel: NCR_LEVEL.allow, nullLevel: NCR_LEVEL.remove };\n }\n const xmlVersion = ncr.xmlVersion === 1.1 ? 1.1 : 1.0;\n const onLevel = NCR_LEVEL[ncr.onNCR] ?? NCR_LEVEL.allow;\n const nullLevel = NCR_LEVEL[ncr.nullNCR] ?? NCR_LEVEL.remove;\n // 'allow' is not meaningful for null — clamp to at least 'remove'\n const clampedNull = Math.max(nullLevel, NCR_LEVEL.remove);\n return { xmlVersion, onLevel, nullLevel: clampedNull };\n}\n\n// ---------------------------------------------------------------------------\n// EntityReplacer\n// ---------------------------------------------------------------------------\n\n/**\n * Single-pass, zero-regex entity replacer for XML/HTML content.\n *\n * Algorithm: scan the string once for '&', read to ';', resolve via map\n * or direct codepoint conversion, build output chunks, join once at the end.\n *\n * Entity lookup priority (highest → lowest):\n * 1. input / runtime (DOCTYPE entities for current document)\n * 2. persistent external (survive across documents)\n * 3. base named map (DEFAULT_XML_ENTITIES + user-supplied namedEntities)\n *\n * Both input and external resolve as the 'external' tier for limit purposes.\n * Base map entities resolve as the 'base' tier.\n *\n * Numeric / hex references (&#NNN; / &#xHH;) are resolved directly via\n * String.fromCodePoint() — no map needed. They count as 'base' tier.\n *\n * @example\n * const replacer = new EntityReplacer({ namedEntities: COMMON_HTML });\n * replacer.setExternalEntities({ brand: 'Acme' });\n *\n * const instance = replacer.reset();\n * instance.addInputEntities({ version: '1.0' });\n * instance.encode('&brand; v&version; <'); // 'Acme v1.0 <'\n */\nexport default class EntityDecoder {\n /**\n * @param {object} [options]\n * @param {object|null} [options.namedEntities] — extra named entities merged into base map\n * @param {object} [options.limit] — security limits\n * @param {number} [options.limit.maxTotalExpansions=0] — 0 = unlimited\n * @param {number} [options.limit.maxExpandedLength=0] — 0 = unlimited\n * @param {'external'|'base'|'all'|string[]} [options.limit.applyLimitsTo='external']\n * Which entity tiers count against the security limits:\n * - 'external' (default) — only input/runtime + persistent external entities\n * - 'base' — only DEFAULT_XML_ENTITIES + namedEntities\n * - 'all' — every entity regardless of tier\n * - string[] — explicit combination, e.g. ['external', 'base']\n * @param {((resolved: string, original: string) => string)|null} [options.postCheck=null]\n * @param {string[]} [options.remove=[]] — entity names (e.g. ['nbsp', '#13']) to delete (replace with empty string)\n * @param {string[]} [options.leave=[]] — entity names to keep as literal (unchanged in output)\n * @param {object} [options.ncr] — Numeric Character Reference controls\n * @param {1.0|1.1} [options.ncr.xmlVersion=1.0]\n * XML version governing which codepoint ranges are restricted:\n * - 1.0 — C0 controls U+0001–U+001F (except U+0009/000A/000D) are prohibited\n * - 1.1 — C0 controls are allowed when written as NCRs; C1 (U+007F–U+009F) decoded as-is\n * @param {'allow'|'leave'|'remove'|'throw'} [options.ncr.onNCR='allow']\n * Base action for numeric references. Severity order: allow < leave < remove < throw.\n * For codepoint ranges that carry a minimum level (surrogates → remove, XML 1.0 C0 → remove),\n * the effective action is max(onNCR, rangeMinimum).\n * @param {'remove'|'throw'} [options.ncr.nullNCR='remove']\n * Action for U+0000 (null). 'allow' and 'leave' are clamped to 'remove' since null is never safe.\n */\n constructor(options = {}) {\n this._limit = options.limit || {};\n this._maxTotalExpansions = this._limit.maxTotalExpansions || 0;\n this._maxExpandedLength = this._limit.maxExpandedLength || 0;\n this._postCheck = typeof options.postCheck === 'function' ? options.postCheck : r => r;\n this._limitTiers = parseLimitTiers(this._limit.applyLimitsTo ?? LIMIT_TIER_EXTERNAL);\n this._numericAllowed = options.numericAllowed ?? true;\n // Base map: DEFAULT_XML_ENTITIES + user-supplied extras. Immutable after construction.\n this._baseMap = mergeEntityMaps(DEFAULT_XML_ENTITIES, options.namedEntities || null);\n\n // Persistent external entities — survive across documents.\n // Stored as a separate map so reset() never touches them.\n /** @type {Record} */\n this._externalMap = Object.create(null);\n\n // Input / runtime entities — current document only, wiped on reset().\n /** @type {Record} */\n this._inputMap = Object.create(null);\n\n // Per-document counters\n this._totalExpansions = 0;\n this._expandedLength = 0;\n\n // --- New: remove / leave sets ---\n /** @type {Set} */\n this._removeSet = new Set(options.remove && Array.isArray(options.remove) ? options.remove : []);\n /** @type {Set} */\n this._leaveSet = new Set(options.leave && Array.isArray(options.leave) ? options.leave : []);\n\n // --- NCR config (parsed into flat fields for hot-path speed) ---\n const ncrCfg = parseNCRConfig(options.ncr);\n this._ncrXmlVersion = ncrCfg.xmlVersion;\n this._ncrOnLevel = ncrCfg.onLevel;\n this._ncrNullLevel = ncrCfg.nullLevel;\n }\n\n // -------------------------------------------------------------------------\n // Persistent external entity registration\n // -------------------------------------------------------------------------\n\n /**\n * Replace the full set of persistent external entities.\n * All keys are validated — throws on invalid characters.\n * @param {Record} map\n */\n setExternalEntities(map) {\n if (map) {\n for (const key of Object.keys(map)) {\n validateEntityName(key);\n }\n }\n this._externalMap = mergeEntityMaps(map);\n }\n\n /**\n * Add a single persistent external entity.\n * @param {string} key\n * @param {string} value\n */\n addExternalEntity(key, value) {\n validateEntityName(key);\n if (typeof value === 'string' && value.indexOf('&') === -1) {\n this._externalMap[key] = value;\n }\n }\n\n // -------------------------------------------------------------------------\n // Input / runtime entity registration (per document)\n // -------------------------------------------------------------------------\n\n /**\n * Inject DOCTYPE entities for the current document.\n * Also resets per-document expansion counters.\n * @param {Record} map\n */\n addInputEntities(map) {\n this._totalExpansions = 0;\n this._expandedLength = 0;\n this._inputMap = mergeEntityMaps(map);\n }\n\n // -------------------------------------------------------------------------\n // Per-document reset\n // -------------------------------------------------------------------------\n\n /**\n * Wipe input/runtime entities and reset counters.\n * Call this before processing each new document.\n * @returns {this}\n */\n reset() {\n this._inputMap = Object.create(null);\n this._totalExpansions = 0;\n this._expandedLength = 0;\n return this;\n }\n\n // -------------------------------------------------------------------------\n // XML version (can be set after construction, e.g. once parser reads )\n // -------------------------------------------------------------------------\n\n /**\n * Update the XML version used for NCR classification.\n * Call this as soon as the document's `` declaration is parsed.\n * @param {1.0|1.1|number} version\n */\n setXmlVersion(version) {\n this._ncrXmlVersion = version === 1.1 ? 1.1 : 1.0;\n }\n\n // -------------------------------------------------------------------------\n // Primary API\n // -------------------------------------------------------------------------\n\n /**\n * Replace all entity references in `str` in a single pass.\n *\n * @param {string} str\n * @returns {string}\n */\n decode(str) {\n if (typeof str !== 'string' || str.length === 0) return str;\n //TODO: check if needed\n //if (str.indexOf('&') === -1) return str; // fast path — no entities at all\n\n const original = str;\n const chunks = [];\n const len = str.length;\n let last = 0; // start of next unprocessed literal chunk\n let i = 0;\n\n const limitExpansions = this._maxTotalExpansions > 0;\n const limitLength = this._maxExpandedLength > 0;\n const checkLimits = limitExpansions || limitLength;\n\n while (i < len) {\n // Scan forward to next '&'\n if (str.charCodeAt(i) !== 38 /* '&' */) { i++; continue; }\n\n // --- Found '&' at position i ---\n\n // Scan forward to ';'\n let j = i + 1;\n while (j < len && str.charCodeAt(j) !== 59 /* ';' */ && (j - i) <= 32) j++;\n\n if (j >= len || str.charCodeAt(j) !== 59) {\n // No closing ';' within window — treat '&' as literal\n i++;\n continue;\n }\n\n // Raw token between '&' and ';' (exclusive)\n const token = str.slice(i + 1, j);\n if (token.length === 0) { i++; continue; }\n\n let replacement;\n let tier; // which limit tier this entity belongs to\n\n if (this._removeSet.has(token)) {\n // Remove entity: replace with empty string\n replacement = '';\n // If entity was unknown (replacement undefined), we still need a tier for limits.\n // Treat as external tier because it's user-directed removal of an unknown reference.\n if (tier === undefined) {\n tier = LIMIT_TIER_EXTERNAL;\n }\n } else if (this._leaveSet.has(token)) {\n // Do not replace — keep original &token; as literal\n i++;\n continue;\n } else if (token.charCodeAt(0) === 35 /* '#' */) {\n // ---- Numeric / NCR reference ----\n // NCR classification always runs first — prohibited codepoints must be\n // caught regardless of numericAllowed.\n const ncrResult = this._resolveNCR(token);\n if (ncrResult === undefined) {\n // 'leave' action — keep original &token; as-is\n i++;\n continue;\n }\n replacement = ncrResult; // '' for remove, char string for allow\n tier = LIMIT_TIER_BASE;\n } else {\n // ---- Named reference ----\n const resolved = this._resolveName(token);\n replacement = resolved?.value;\n tier = resolved?.tier;\n }\n\n if (replacement === undefined) {\n // Unknown entity — leave as-is, advance past '&' only\n i++;\n continue;\n }\n\n // Flush literal chunk before this entity\n if (i > last) chunks.push(str.slice(last, i));\n chunks.push(replacement);\n last = j + 1; // skip past ';'\n i = last;\n\n // Apply expansion limits only if this tier is being tracked\n if (checkLimits && this._tierCounts(tier)) {\n if (limitExpansions) {\n this._totalExpansions++;\n if (this._totalExpansions > this._maxTotalExpansions) {\n throw new Error(\n `[EntityReplacer] Entity expansion count limit exceeded: ` +\n `${this._totalExpansions} > ${this._maxTotalExpansions}`\n );\n }\n }\n if (limitLength) {\n // delta: replacement.length minus the raw &token; length (token.length + 2 for '&' and ';')\n const delta = replacement.length - (token.length + 2);\n if (delta > 0) {\n this._expandedLength += delta;\n if (this._expandedLength > this._maxExpandedLength) {\n throw new Error(\n `[EntityReplacer] Expanded content length limit exceeded: ` +\n `${this._expandedLength} > ${this._maxExpandedLength}`\n );\n }\n }\n }\n }\n }\n\n // Flush trailing literal\n if (last < len) chunks.push(str.slice(last));\n\n // If nothing was replaced, chunks is empty — return original\n const result = chunks.length === 0 ? str : chunks.join('');\n\n return this._postCheck(result, original);\n }\n\n // -------------------------------------------------------------------------\n // Private: limit tier check\n // -------------------------------------------------------------------------\n\n /**\n * Returns true if a resolved entity of the given tier should count\n * against the expansion/length limits.\n * @param {string} tier — LIMIT_TIER_EXTERNAL | LIMIT_TIER_BASE\n * @returns {boolean}\n */\n _tierCounts(tier) {\n if (this._limitTiers.has(LIMIT_TIER_ALL)) return true;\n return this._limitTiers.has(tier);\n }\n\n // -------------------------------------------------------------------------\n // Private: entity resolution\n // -------------------------------------------------------------------------\n\n /**\n * Resolve a named entity token (without & and ;).\n * Priority: inputMap > externalMap > baseMap\n * Returns the resolved value tagged with its limit tier.\n *\n * @param {string} name\n * @returns {{ value: string, tier: string }|undefined}\n */\n _resolveName(name) {\n // input and external both count as 'external' tier for limit purposes —\n // they are injected at runtime and are the untrusted surface.\n if (name in this._inputMap) return { value: this._inputMap[name], tier: LIMIT_TIER_EXTERNAL };\n if (name in this._externalMap) return { value: this._externalMap[name], tier: LIMIT_TIER_EXTERNAL };\n if (name in this._baseMap) return { value: this._baseMap[name], tier: LIMIT_TIER_BASE };\n return undefined;\n }\n\n /**\n * Classify a codepoint and return the minimum action level that must be applied.\n * Returns -1 when no minimum is imposed (normal allow path).\n *\n * Ranges checked (in priority order):\n * 1. U+0000 — null, governed by nullNCR (always ≥ remove)\n * 2. U+D800–U+DFFF — surrogates, always prohibited (min: remove)\n * 3. U+0001–U+001F \\ {0x09,0x0A,0x0D} — XML 1.0 restricted C0 (min: remove)\n * (skipped in XML 1.1 — C0 controls are allowed when written as NCRs)\n *\n * @param {number} cp — codepoint\n * @returns {number} — minimum NCR_LEVEL value, or -1 for no restriction\n */\n _classifyNCR(cp) {\n // 1. Null\n if (cp === 0) return this._ncrNullLevel;\n\n // 2. Surrogates — always prohibited, minimum 'remove'\n if (cp >= 0xD800 && cp <= 0xDFFF) return NCR_LEVEL.remove;\n\n // 3. XML 1.0 restricted C0 controls\n if (this._ncrXmlVersion === 1.0) {\n if (cp >= 0x01 && cp <= 0x1F && !XML10_ALLOWED_C0.has(cp)) return NCR_LEVEL.remove;\n }\n\n return -1; // no restriction\n }\n\n /**\n * Execute a resolved NCR action.\n *\n * @param {number} action — NCR_LEVEL value\n * @param {string} token — raw token (e.g. '#38') for error messages\n * @param {number} cp — codepoint, used only for error messages\n * @returns {string|undefined}\n * - decoded character string → 'allow'\n * - '' → 'remove'\n * - undefined → 'leave' (caller must skip past '&' only)\n * - throws Error → 'throw'\n */\n _applyNCRAction(action, token, cp) {\n switch (action) {\n case NCR_LEVEL.allow: return String.fromCodePoint(cp);\n case NCR_LEVEL.remove: return '';\n case NCR_LEVEL.leave: return undefined; // signal: keep literal\n case NCR_LEVEL.throw:\n throw new Error(\n `[EntityDecoder] Prohibited numeric character reference ` +\n `&${token}; (U+${cp.toString(16).toUpperCase().padStart(4, '0')})`\n );\n default: return String.fromCodePoint(cp);\n }\n }\n\n /**\n * Full NCR resolution pipeline for a numeric token.\n *\n * Steps:\n * 1. Parse the codepoint (decimal or hex).\n * 2. Validate the raw codepoint range (NaN, <0, >0x10FFFF).\n * 3. If numericAllowed is false and no minimum restriction applies → leave as-is.\n * 4. Classify the codepoint to find the minimum required action level.\n * 5. Resolve effective action = max(onNCR, minimum).\n * 6. Apply and return.\n *\n * @param {string} token — e.g. '#38', '#x26', '#X26'\n * @returns {string|undefined}\n * - string (incl. '') — replacement ('' = remove)\n * - undefined — leave original &token; as-is\n */\n _resolveNCR(token) {\n // Step 1: parse codepoint\n const second = token.charCodeAt(1);\n let cp;\n if (second === 120 /* x */ || second === 88 /* X */) {\n cp = parseInt(token.slice(2), 16);\n } else {\n cp = parseInt(token.slice(1), 10);\n }\n\n // Step 2: out-of-range → leave as-is unconditionally\n if (Number.isNaN(cp) || cp < 0 || cp > 0x10FFFF) return undefined;\n\n // Step 3: classify to get minimum action level\n const minimum = this._classifyNCR(cp);\n\n // Step 4: if numericAllowed is false and no hard minimum → leave\n if (!this._numericAllowed && minimum < NCR_LEVEL.remove) return undefined;\n\n // Step 5: effective action = max(configured onNCR, range minimum)\n const effective = minimum === -1\n ? this._ncrOnLevel\n : Math.max(this._ncrOnLevel, minimum);\n\n // Step 6: apply\n return this._applyNCRAction(effective, token, cp);\n }\n}","'use strict';\n///@ts-check\n\nimport { getAllMatches, isExist, DANGEROUS_PROPERTY_NAMES, criticalProperties } from '../util.js';\nimport xmlNode from './xmlNode.js';\nimport DocTypeReader from './DocTypeReader.js';\nimport toNumber from \"strnum\";\nimport getIgnoreAttributesFn from \"../ignoreAttributes.js\";\nimport { Expression, Matcher } from 'path-expression-matcher';\nimport { ExpressionSet } from 'path-expression-matcher';\nimport { EntityDecoder, XML, CURRENCY, COMMON_HTML } from '@nodable/entities';\n\n// const regx =\n// '<((!\\\\[CDATA\\\\[([\\\\s\\\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\\\/)(NAME)\\\\s*>))([^<]*)'\n// .replace(/NAME/g, util.nameRegexp);\n\n//const tagsRegx = new RegExp(\"<(\\\\/?[\\\\w:\\\\-\\._]+)([^>]*)>(\\\\s*\"+cdataRegx+\")*([^<]+)?\",\"g\");\n//const tagsRegx = new RegExp(\"<(\\\\/?)((\\\\w*:)?([\\\\w:\\\\-\\._]+))([^>]*)>([^<]*)(\"+cdataRegx+\"([^<]*))*([^<]+)?\",\"g\");\n\n// Helper functions for attribute and namespace handling\n\n/**\n * Extract raw attributes (without prefix) from prefixed attribute map\n * @param {object} prefixedAttrs - Attributes with prefix from buildAttributesMap\n * @param {object} options - Parser options containing attributeNamePrefix\n * @returns {object} Raw attributes for matcher\n */\nfunction extractRawAttributes(prefixedAttrs, options) {\n if (!prefixedAttrs) return {};\n\n // Handle attributesGroupName option\n const attrs = options.attributesGroupName\n ? prefixedAttrs[options.attributesGroupName]\n : prefixedAttrs;\n\n if (!attrs) return {};\n\n const rawAttrs = {};\n for (const key in attrs) {\n // Remove the attribute prefix to get raw name\n if (key.startsWith(options.attributeNamePrefix)) {\n const rawName = key.substring(options.attributeNamePrefix.length);\n rawAttrs[rawName] = attrs[key];\n } else {\n // Attribute without prefix (shouldn't normally happen, but be safe)\n rawAttrs[key] = attrs[key];\n }\n }\n return rawAttrs;\n}\n\n/**\n * Extract namespace from raw tag name\n * @param {string} rawTagName - Tag name possibly with namespace (e.g., \"soap:Envelope\")\n * @returns {string|undefined} Namespace or undefined\n */\nfunction extractNamespace(rawTagName) {\n if (!rawTagName || typeof rawTagName !== 'string') return undefined;\n\n const colonIndex = rawTagName.indexOf(':');\n if (colonIndex !== -1 && colonIndex > 0) {\n const ns = rawTagName.substring(0, colonIndex);\n // Don't treat xmlns as a namespace\n if (ns !== 'xmlns') {\n return ns;\n }\n }\n return undefined;\n}\n\nexport default class OrderedObjParser {\n constructor(options) {\n this.options = options;\n this.currentNode = null;\n this.tagsNodeStack = [];\n this.parseXml = parseXml;\n this.parseTextData = parseTextData;\n this.resolveNameSpace = resolveNameSpace;\n this.buildAttributesMap = buildAttributesMap;\n this.isItStopNode = isItStopNode;\n this.replaceEntitiesValue = replaceEntitiesValue;\n this.readStopNodeData = readStopNodeData;\n this.saveTextToParentTag = saveTextToParentTag;\n this.addChild = addChild;\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.entityExpansionCount = 0;\n this.currentExpandedLength = 0;\n let namedEntities = { ...XML };\n if (this.options.entityDecoder) {\n this.entityDecoder = this.options.entityDecoder\n } else {\n if (typeof this.options.htmlEntities === \"object\") namedEntities = this.options.htmlEntities;\n else if (this.options.htmlEntities === true) namedEntities = { ...COMMON_HTML, ...CURRENCY };\n this.entityDecoder = new EntityDecoder({\n namedEntities: namedEntities,\n numericAllowed: this.options.htmlEntities,\n limit: {\n maxTotalExpansions: this.options.processEntities.maxTotalExpansions,\n maxExpandedLength: this.options.processEntities.maxExpandedLength,\n applyLimitsTo: this.options.processEntities.appliesTo,\n }\n //postCheck: resolved => resolved\n });\n }\n\n // Initialize path matcher for path-expression-matcher\n this.matcher = new Matcher();\n\n // Live read-only proxy of matcher — PEM creates and caches this internally.\n // All user callbacks receive this instead of the mutable matcher.\n this.readonlyMatcher = this.matcher.readOnly();\n\n // Flag to track if current node is a stop node (optimization)\n this.isCurrentNodeStopNode = false;\n\n // Pre-compile stopNodes expressions\n this.stopNodeExpressionsSet = new ExpressionSet();\n const stopNodesOpts = this.options.stopNodes;\n if (stopNodesOpts && stopNodesOpts.length > 0) {\n for (let i = 0; i < stopNodesOpts.length; i++) {\n const stopNodeExp = stopNodesOpts[i];\n if (typeof stopNodeExp === 'string') {\n // Convert string to Expression object\n this.stopNodeExpressionsSet.add(new Expression(stopNodeExp));\n } else if (stopNodeExp instanceof Expression) {\n // Already an Expression object\n this.stopNodeExpressionsSet.add(stopNodeExp);\n }\n }\n this.stopNodeExpressionsSet.seal();\n }\n }\n\n}\n\n\n/**\n * @param {string} val\n * @param {string} tagName\n * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath\n * @param {boolean} dontTrim\n * @param {boolean} hasAttributes\n * @param {boolean} isLeafNode\n * @param {boolean} escapeEntities\n */\nfunction parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {\n const options = this.options;\n if (val !== undefined) {\n if (options.trimValues && !dontTrim) {\n val = val.trim();\n }\n if (val.length > 0) {\n if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath);\n\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = options.jPath ? jPath.toString() : jPath;\n const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);\n if (newval === null || newval === undefined) {\n //don't parse\n return val;\n } else if (typeof newval !== typeof val || newval !== val) {\n //overwrite\n return newval;\n } else if (options.trimValues) {\n return parseValue(val, options.parseTagValue, options.numberParseOptions);\n } else {\n const trimmedVal = val.trim();\n if (trimmedVal === val) {\n return parseValue(val, options.parseTagValue, options.numberParseOptions);\n } else {\n return val;\n }\n }\n }\n }\n}\n\nfunction resolveNameSpace(tagname) {\n if (this.options.removeNSPrefix) {\n const tags = tagname.split(':');\n const prefix = tagname.charAt(0) === '/' ? '/' : '';\n if (tags[0] === 'xmlns') {\n return '';\n }\n if (tags.length === 2) {\n tagname = prefix + tags[1];\n }\n }\n return tagname;\n}\n\n//TODO: change regex to capture NS\n//const attrsRegx = new RegExp(\"([\\\\w\\\\-\\\\.\\\\:]+)\\\\s*=\\\\s*(['\\\"])((.|\\n)*?)\\\\2\",\"gm\");\nconst attrsRegx = new RegExp('([^\\\\s=]+)\\\\s*(=\\\\s*([\\'\"])([\\\\s\\\\S]*?)\\\\3)?', 'gm');\n\nfunction buildAttributesMap(attrStr, jPath, tagName, force = false) {\n const options = this.options;\n if (force === true || (options.ignoreAttributes !== true && typeof attrStr === 'string')) {\n // attrStr = attrStr.replace(/\\r?\\n/g, ' ');\n //attrStr = attrStr || attrStr.trim();\n\n const matches = getAllMatches(attrStr, attrsRegx);\n const len = matches.length; //don't make it inline\n const attrs = {};\n\n // Pre-process values once: trim + entity replacement\n // Reused in both matcher update and second pass\n const processedVals = new Array(len);\n let hasRawAttrs = false;\n const rawAttrsForMatcher = {};\n\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n const oldVal = matches[i][4];\n\n if (attrName.length && oldVal !== undefined) {\n let val = oldVal;\n if (options.trimValues) val = val.trim();\n val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher);\n processedVals[i] = val;\n\n rawAttrsForMatcher[attrName] = val;\n hasRawAttrs = true;\n }\n }\n\n // Update matcher ONCE before second pass, if applicable\n if (hasRawAttrs && typeof jPath === 'object' && jPath.updateCurrent) {\n jPath.updateCurrent(rawAttrsForMatcher);\n }\n\n // Hoist toString() once — path doesn't change during attribute processing\n const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;\n\n // Second pass: apply processors, build final attrs\n let hasAttrs = false;\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n\n if (this.ignoreAttributesFn(attrName, jPathStr)) continue;\n\n let aName = options.attributeNamePrefix + attrName;\n\n if (attrName.length) {\n if (options.transformAttributeName) {\n aName = options.transformAttributeName(aName);\n }\n aName = sanitizeName(aName, options);\n\n if (matches[i][4] !== undefined) {\n // Reuse already-processed value — no double entity replacement\n const oldVal = processedVals[i];\n\n const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);\n if (newVal === null || newVal === undefined) {\n attrs[aName] = oldVal;\n } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {\n attrs[aName] = newVal;\n } else {\n attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions);\n }\n hasAttrs = true;\n } else if (options.allowBooleanAttributes) {\n attrs[aName] = true;\n hasAttrs = true;\n }\n }\n }\n\n if (!hasAttrs) return;\n\n if (options.attributesGroupName) {\n const attrCollection = {};\n attrCollection[options.attributesGroupName] = attrs;\n return attrCollection;\n }\n return attrs;\n }\n}\nconst parseXml = function (xmlData) {\n xmlData = xmlData.replace(/\\r\\n?/g, \"\\n\"); //TODO: remove this line\n const xmlObj = new xmlNode('!xml');\n let currentNode = xmlObj;\n let textData = \"\";\n\n // Reset matcher for new document\n this.matcher.reset();\n this.entityDecoder.reset();\n\n // Reset entity expansion counters for this document\n this.entityExpansionCount = 0;\n this.currentExpandedLength = 0;\n const options = this.options;\n const docTypeReader = new DocTypeReader(options.processEntities);\n const xmlLen = xmlData.length;\n for (let i = 0; i < xmlLen; i++) {//for each char in XML data\n const ch = xmlData[i];\n if (ch === '<') {\n // const nextIndex = i+1;\n // const _2ndChar = xmlData[nextIndex];\n const c1 = xmlData.charCodeAt(i + 1);\n if (c1 === 47) {//Closing Tag '/'\n const closeIndex = findClosingIndex(xmlData, \">\", i, \"Closing Tag is not closed.\")\n let tagName = xmlData.substring(i + 2, closeIndex).trim();\n\n if (options.removeNSPrefix) {\n const colonIndex = tagName.indexOf(\":\");\n if (colonIndex !== -1) {\n tagName = tagName.substr(colonIndex + 1);\n }\n }\n\n tagName = transformTagName(options.transformTagName, tagName, \"\", options).tagName;\n\n if (currentNode) {\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n }\n\n //check if last tag of nested tag was unpaired tag\n const lastTagName = this.matcher.getCurrentTag();\n if (tagName && options.unpairedTagsSet.has(tagName)) {\n throw new Error(`Unpaired tag can not be used as closing tag: `);\n }\n if (lastTagName && options.unpairedTagsSet.has(lastTagName)) {\n // Pop the unpaired tag\n this.matcher.pop();\n this.tagsNodeStack.pop();\n }\n // Pop the closing tag\n this.matcher.pop();\n this.isCurrentNodeStopNode = false; // Reset flag when closing tag\n\n currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope\n textData = \"\";\n i = closeIndex;\n } else if (c1 === 63) { //'?'\n\n let tagData = readTagExp(xmlData, i, false, \"?>\");\n if (!tagData) throw new Error(\"Pi Tag is not closed.\");\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true);\n if (attsMap) {\n const ver = attsMap[this.options.attributeNamePrefix + \"version\"];\n this.entityDecoder.setXmlVersion(Number(ver) || 1.0);\n }\n if ((options.ignoreDeclaration && tagData.tagName === \"?xml\") || options.ignorePiTags) {\n //do nothing\n } else {\n\n const childNode = new xmlNode(tagData.tagName);\n childNode.add(options.textNodeName, \"\");\n\n if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) {\n childNode[\":@\"] = attsMap\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, i);\n }\n\n\n i = tagData.closeIndex + 1;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 45\n && xmlData.charCodeAt(i + 3) === 45) { //'!--'\n const endIndex = findClosingIndex(xmlData, \"-->\", i + 4, \"Comment is not closed.\")\n if (options.commentPropName) {\n const comment = xmlData.substring(i + 4, endIndex - 2);\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n\n currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]);\n }\n i = endIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 68) { //'!D'\n const result = docTypeReader.readDocType(xmlData, i);\n this.entityDecoder.addInputEntities(result.entities);\n i = result.i;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 91) { // '!['\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"CDATA is not closed.\") - 2;\n const tagExp = xmlData.substring(i + 9, closeIndex);\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n\n let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true);\n if (val == undefined) val = \"\";\n\n //cdata should be set even if it is 0 length string\n if (options.cdataPropName) {\n currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]);\n } else {\n currentNode.add(options.textNodeName, val);\n }\n\n i = closeIndex + 2;\n } else {//Opening tag\n let result = readTagExp(xmlData, i, options.removeNSPrefix);\n\n // Safety check: readTagExp can return undefined\n if (!result) {\n // Log context for debugging\n const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50));\n throw new Error(`readTagExp returned undefined at position ${i}. Context: \"${context}\"`);\n }\n\n let tagName = result.tagName;\n const rawTagName = result.rawTagName;\n let tagExp = result.tagExp;\n let attrExpPresent = result.attrExpPresent;\n let closeIndex = result.closeIndex;\n\n ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));\n\n if (options.strictReservedNames &&\n (tagName === options.commentPropName\n || tagName === options.cdataPropName\n || tagName === options.textNodeName\n || tagName === options.attributesGroupName\n )) {\n throw new Error(`Invalid tag name: ${tagName}`);\n }\n\n //save text as child node\n if (currentNode && textData) {\n if (currentNode.tagname !== '!xml') {\n //when nested tag is found\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false);\n }\n }\n\n //check if last tag was unpaired tag\n const lastTag = currentNode;\n if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) {\n currentNode = this.tagsNodeStack.pop();\n this.matcher.pop();\n }\n\n // Clean up self-closing syntax BEFORE processing attributes\n // This is where tagExp gets the trailing / removed\n let isSelfClosing = false;\n if (tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1) {\n isSelfClosing = true;\n if (tagName[tagName.length - 1] === \"/\") {\n tagName = tagName.substr(0, tagName.length - 1);\n tagExp = tagName;\n } else {\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n\n // Re-check attrExpPresent after cleaning\n attrExpPresent = (tagName !== tagExp);\n }\n\n // Now process attributes with CLEAN tagExp (no trailing /)\n let prefixedAttrs = null;\n let rawAttrs = {};\n let namespace = undefined;\n\n // Extract namespace from rawTagName\n namespace = extractNamespace(rawTagName);\n\n // Push tag to matcher FIRST (with empty attrs for now) so callbacks see correct path\n if (tagName !== xmlObj.tagname) {\n this.matcher.push(tagName, {}, namespace);\n }\n\n // Now build attributes - callbacks will see correct matcher state\n if (tagName !== tagExp && attrExpPresent) {\n // Build attributes (returns prefixed attributes for the tree)\n // Note: buildAttributesMap now internally updates the matcher with raw attributes\n prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName);\n\n if (prefixedAttrs) {\n // Extract raw attributes (without prefix) for our use\n //TODO: seems a performance overhead\n rawAttrs = extractRawAttributes(prefixedAttrs, options);\n }\n }\n\n // Now check if this is a stop node (after attributes are set)\n if (tagName !== xmlObj.tagname) {\n this.isCurrentNodeStopNode = this.isItStopNode();\n }\n\n const startIndex = i;\n if (this.isCurrentNodeStopNode) {\n let tagContent = \"\";\n\n // For self-closing tags, content is empty\n if (isSelfClosing) {\n i = result.closeIndex;\n }\n //unpaired tag\n else if (options.unpairedTagsSet.has(tagName)) {\n i = result.closeIndex;\n }\n //normal tag\n else {\n //read until closing tag is found\n const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);\n if (!result) throw new Error(`Unexpected end of ${rawTagName}`);\n i = result.i;\n tagContent = result.tagContent;\n }\n\n const childNode = new xmlNode(tagName);\n\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n\n // For stop nodes, store raw content as-is without any processing\n childNode.add(options.textNodeName, tagContent);\n\n this.matcher.pop(); // Pop the stop node tag\n this.isCurrentNodeStopNode = false; // Reset flag\n\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n } else {\n //selfClosing tag\n if (isSelfClosing) {\n ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));\n\n const childNode = new xmlNode(tagName);\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n this.matcher.pop(); // Pop self-closing tag\n this.isCurrentNodeStopNode = false; // Reset flag\n }\n else if (options.unpairedTagsSet.has(tagName)) {//unpaired tag\n const childNode = new xmlNode(tagName);\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n this.matcher.pop(); // Pop unpaired tag\n this.isCurrentNodeStopNode = false; // Reset flag\n i = result.closeIndex;\n // Continue to next iteration without changing currentNode\n continue;\n }\n //opening tag\n else {\n const childNode = new xmlNode(tagName);\n if (this.tagsNodeStack.length > options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n this.tagsNodeStack.push(currentNode);\n\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n currentNode = childNode;\n }\n textData = \"\";\n i = closeIndex;\n }\n }\n } else {\n textData += xmlData[i];\n }\n }\n return xmlObj.child;\n}\n\nfunction addChild(currentNode, childNode, matcher, startIndex) {\n // unset startIndex if not requested\n if (!this.options.captureMetaData) startIndex = undefined;\n\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher;\n const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[\":@\"])\n if (result === false) {\n //do nothing\n } else if (typeof result === \"string\") {\n childNode.tagname = result\n currentNode.addChild(childNode, startIndex);\n } else {\n currentNode.addChild(childNode, startIndex);\n }\n}\n\n/**\n * @param {object} val - Entity object with regex and val properties\n * @param {string} tagName - Tag name\n * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath\n */\nfunction replaceEntitiesValue(val, tagName, jPath) {\n const entityConfig = this.options.processEntities;\n\n if (!entityConfig || !entityConfig.enabled) {\n return val;\n }\n\n // Check if tag is allowed to contain entities\n if (entityConfig.allowedTags) {\n const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;\n const allowed = Array.isArray(entityConfig.allowedTags)\n ? entityConfig.allowedTags.includes(tagName)\n : entityConfig.allowedTags(tagName, jPathOrMatcher);\n\n if (!allowed) {\n return val;\n }\n }\n\n // Apply custom tag filter if provided\n if (entityConfig.tagFilter) {\n const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;\n if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) {\n return val; // Skip based on custom filter\n }\n }\n\n return this.entityDecoder.decode(val);\n}\n\n\nfunction saveTextToParentTag(textData, parentNode, matcher, isLeafNode) {\n if (textData) { //store previously collected data as textNode\n if (isLeafNode === undefined) isLeafNode = parentNode.child.length === 0\n\n textData = this.parseTextData(textData,\n parentNode.tagname,\n matcher,\n false,\n parentNode[\":@\"] ? Object.keys(parentNode[\":@\"]).length !== 0 : false,\n isLeafNode);\n\n if (textData !== undefined && textData !== \"\")\n parentNode.add(this.options.textNodeName, textData);\n textData = \"\";\n }\n return textData;\n}\n\n/**\n * @param {Array} stopNodeExpressions - Array of compiled Expression objects\n * @param {Matcher} matcher - Current path matcher\n */\nfunction isItStopNode() {\n if (this.stopNodeExpressionsSet.size === 0) return false;\n\n return this.matcher.matchesAny(this.stopNodeExpressionsSet);\n}\n\n/**\n * Returns the tag Expression and where it is ending handling single-double quotes situation\n * @param {string} xmlData \n * @param {number} i starting index\n * @returns \n */\nfunction tagExpWithClosingIndex(xmlData, i, closingChar = \">\") {\n let attrBoundary = 0;\n const chars = [];\n const len = xmlData.length;\n const closeCode0 = closingChar.charCodeAt(0);\n const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1;\n\n for (let index = i; index < len; index++) {\n const code = xmlData.charCodeAt(index);\n\n if (attrBoundary) {\n if (code === attrBoundary) attrBoundary = 0;\n } else if (code === 34 || code === 39) { // \" or '\n attrBoundary = code;\n } else if (code === closeCode0) {\n if (closeCode1 !== -1) {\n if (xmlData.charCodeAt(index + 1) === closeCode1) {\n return { data: String.fromCharCode(...chars), index };\n }\n } else {\n return { data: String.fromCharCode(...chars), index };\n }\n } else if (code === 9) { // \\t\n chars.push(32); // space\n continue;\n }\n\n chars.push(code);\n }\n}\n\nfunction findClosingIndex(xmlData, str, i, errMsg) {\n const closingIndex = xmlData.indexOf(str, i);\n if (closingIndex === -1) {\n throw new Error(errMsg)\n } else {\n return closingIndex + str.length - 1;\n }\n}\n\nfunction findClosingChar(xmlData, char, i, errMsg) {\n const closingIndex = xmlData.indexOf(char, i);\n if (closingIndex === -1) throw new Error(errMsg);\n return closingIndex; // no offset needed\n}\n\nfunction readTagExp(xmlData, i, removeNSPrefix, closingChar = \">\") {\n const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);\n if (!result) return;\n let tagExp = result.data;\n const closeIndex = result.index;\n const separatorIndex = tagExp.search(/\\s/);\n let tagName = tagExp;\n let attrExpPresent = true;\n if (separatorIndex !== -1) {//separate tag name and attributes expression\n tagName = tagExp.substring(0, separatorIndex);\n tagExp = tagExp.substring(separatorIndex + 1).trimStart();\n }\n\n const rawTagName = tagName;\n if (removeNSPrefix) {\n const colonIndex = tagName.indexOf(\":\");\n if (colonIndex !== -1) {\n tagName = tagName.substr(colonIndex + 1);\n attrExpPresent = tagName !== result.data.substr(colonIndex + 1);\n }\n }\n\n return {\n tagName: tagName,\n tagExp: tagExp,\n closeIndex: closeIndex,\n attrExpPresent: attrExpPresent,\n rawTagName: rawTagName,\n }\n}\n/**\n * find paired tag for a stop node\n * @param {string} xmlData \n * @param {string} tagName \n * @param {number} i \n */\nfunction readStopNodeData(xmlData, tagName, i) {\n const startIndex = i;\n // Starting at 1 since we already have an open tag\n let openTagCount = 1;\n\n const xmllen = xmlData.length;\n for (; i < xmllen; i++) {\n if (xmlData[i] === \"<\") {\n const c1 = xmlData.charCodeAt(i + 1);\n if (c1 === 47) {//close tag '/'\n const closeIndex = findClosingChar(xmlData, \">\", i, `${tagName} is not closed`);\n let closeTagName = xmlData.substring(i + 2, closeIndex).trim();\n if (closeTagName === tagName) {\n openTagCount--;\n if (openTagCount === 0) {\n return {\n tagContent: xmlData.substring(startIndex, i),\n i: closeIndex\n }\n }\n }\n i = closeIndex;\n } else if (c1 === 63) { //?\n const closeIndex = findClosingIndex(xmlData, \"?>\", i + 1, \"StopNode is not closed.\")\n i = closeIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 45\n && xmlData.charCodeAt(i + 3) === 45) { // '!--'\n const closeIndex = findClosingIndex(xmlData, \"-->\", i + 3, \"StopNode is not closed.\")\n i = closeIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 91) { // '!['\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"StopNode is not closed.\") - 2;\n i = closeIndex;\n } else {\n const tagData = readTagExp(xmlData, i, '>')\n\n if (tagData) {\n const openTagName = tagData && tagData.tagName;\n if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== \"/\") {\n openTagCount++;\n }\n i = tagData.closeIndex;\n }\n }\n }\n }//end for loop\n}\n\nfunction parseValue(val, shouldParse, options) {\n if (shouldParse && typeof val === 'string') {\n //console.log(options)\n const newval = val.trim();\n if (newval === 'true') return true;\n else if (newval === 'false') return false;\n else return toNumber(val, options);\n } else {\n if (isExist(val)) {\n return val;\n } else {\n return '';\n }\n }\n}\n\nfunction fromCodePoint(str, base, prefix) {\n const codePoint = Number.parseInt(str, base);\n\n if (codePoint >= 0 && codePoint <= 0x10FFFF) {\n return String.fromCodePoint(codePoint);\n } else {\n return prefix + str + \";\";\n }\n}\n\nfunction transformTagName(fn, tagName, tagExp, options) {\n if (fn) {\n const newTagName = fn(tagName);\n if (tagExp === tagName) {\n tagExp = newTagName\n }\n tagName = newTagName;\n }\n tagName = sanitizeName(tagName, options);\n return { tagName, tagExp };\n}\n\n\n\nfunction sanitizeName(name, options) {\n if (criticalProperties.includes(name)) {\n throw new Error(`[SECURITY] Invalid name: \"${name}\" is a reserved JavaScript keyword that could cause prototype pollution`);\n } else if (DANGEROUS_PROPERTY_NAMES.includes(name)) {\n return options.onDangerousProperty(name);\n }\n return name;\n}","export default function getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}","'use strict';\n\nimport XmlNode from './xmlNode.js';\nimport { Matcher } from 'path-expression-matcher';\n\nconst METADATA_SYMBOL = XmlNode.getMetaDataSymbol();\n\n/**\n * Helper function to strip attribute prefix from attribute map\n * @param {object} attrs - Attributes with prefix (e.g., {\"@_class\": \"code\"})\n * @param {string} prefix - Attribute prefix to remove (e.g., \"@_\")\n * @returns {object} Attributes without prefix (e.g., {\"class\": \"code\"})\n */\nfunction stripAttributePrefix(attrs, prefix) {\n if (!attrs || typeof attrs !== 'object') return {};\n if (!prefix) return attrs;\n\n const rawAttrs = {};\n for (const key in attrs) {\n if (key.startsWith(prefix)) {\n const rawName = key.substring(prefix.length);\n rawAttrs[rawName] = attrs[key];\n } else {\n // Attribute without prefix (shouldn't normally happen, but be safe)\n rawAttrs[key] = attrs[key];\n }\n }\n return rawAttrs;\n}\n\n/**\n * \n * @param {array} node \n * @param {any} options \n * @param {Matcher} matcher - Path matcher instance\n * @returns \n */\nexport default function prettify(node, options, matcher, readonlyMatcher) {\n return compress(node, options, matcher, readonlyMatcher);\n}\n\n/**\n * @param {array} arr \n * @param {object} options \n * @param {Matcher} matcher - Path matcher instance\n * @returns object\n */\nfunction compress(arr, options, matcher, readonlyMatcher) {\n let text;\n const compressedObj = {}; //This is intended to be a plain object\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const property = propName(tagObj);\n\n // Push current property to matcher WITH RAW ATTRIBUTES (no prefix)\n if (property !== undefined && property !== options.textNodeName) {\n const rawAttrs = stripAttributePrefix(\n tagObj[\":@\"] || {},\n options.attributeNamePrefix\n );\n matcher.push(property, rawAttrs);\n }\n\n if (property === options.textNodeName) {\n if (text === undefined) text = tagObj[property];\n else text += \"\" + tagObj[property];\n } else if (property === undefined) {\n continue;\n } else if (tagObj[property]) {\n\n let val = compress(tagObj[property], options, matcher, readonlyMatcher);\n const isLeaf = isLeafTag(val, options);\n\n if (tagObj[\":@\"]) {\n assignAttributes(val, tagObj[\":@\"], readonlyMatcher, options);\n } else if (Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode) {\n val = val[options.textNodeName];\n } else if (Object.keys(val).length === 0) {\n if (options.alwaysCreateTextNode) val[options.textNodeName] = \"\";\n else val = \"\";\n }\n\n if (tagObj[METADATA_SYMBOL] !== undefined && typeof val === \"object\" && val !== null) {\n val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL]; // copy over metadata\n }\n\n\n if (compressedObj[property] !== undefined && Object.prototype.hasOwnProperty.call(compressedObj, property)) {\n if (!Array.isArray(compressedObj[property])) {\n compressedObj[property] = [compressedObj[property]];\n }\n compressedObj[property].push(val);\n } else {\n //TODO: if a node is not an array, then check if it should be an array\n //also determine if it is a leaf node\n\n // Pass jPath string or readonlyMatcher based on options.jPath setting\n const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;\n if (options.isArray(property, jPathOrMatcher, isLeaf)) {\n compressedObj[property] = [val];\n } else {\n compressedObj[property] = val;\n }\n }\n\n // Pop property from matcher after processing\n if (property !== undefined && property !== options.textNodeName) {\n matcher.pop();\n }\n }\n\n }\n // if(text && text.length > 0) compressedObj[options.textNodeName] = text;\n if (typeof text === \"string\") {\n if (text.length > 0) compressedObj[options.textNodeName] = text;\n } else if (text !== undefined) compressedObj[options.textNodeName] = text;\n\n\n return compressedObj;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (key !== \":@\") return key;\n }\n}\n\nfunction assignAttributes(obj, attrMap, readonlyMatcher, options) {\n if (attrMap) {\n const keys = Object.keys(attrMap);\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n const atrrName = keys[i]; // This is the PREFIXED name (e.g., \"@_class\")\n\n // Strip prefix for matcher path (for isArray callback)\n const rawAttrName = atrrName.startsWith(options.attributeNamePrefix)\n ? atrrName.substring(options.attributeNamePrefix.length)\n : atrrName;\n\n // For attributes, we need to create a temporary path\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = options.jPath\n ? readonlyMatcher.toString() + \".\" + rawAttrName\n : readonlyMatcher;\n\n if (options.isArray(atrrName, jPathOrMatcher, true, true)) {\n obj[atrrName] = [attrMap[atrrName]];\n } else {\n obj[atrrName] = attrMap[atrrName];\n }\n }\n }\n}\n\nfunction isLeafTag(obj, options) {\n const { textNodeName } = options;\n const propCount = Object.keys(obj).length;\n\n if (propCount === 0) {\n return true;\n }\n\n if (\n propCount === 1 &&\n (obj[textNodeName] || typeof obj[textNodeName] === \"boolean\" || obj[textNodeName] === 0)\n ) {\n return true;\n }\n\n return false;\n}","import { buildOptions } from './OptionsBuilder.js';\nimport OrderedObjParser from './OrderedObjParser.js';\nimport prettify from './node2json.js';\nimport { validate } from \"../validator.js\";\nimport XmlNode from './xmlNode.js';\n\nexport default class XMLParser {\n\n constructor(options) {\n this.externalEntities = {};\n this.options = buildOptions(options);\n\n }\n /**\n * Parse XML dats to JS object \n * @param {string|Uint8Array} xmlData \n * @param {boolean|Object} validationOption \n */\n parse(xmlData, validationOption) {\n if (typeof xmlData !== \"string\" && xmlData.toString) {\n xmlData = xmlData.toString();\n } else if (typeof xmlData !== \"string\") {\n throw new Error(\"XML data is accepted in String or Bytes[] form.\")\n }\n\n if (validationOption) {\n if (validationOption === true) validationOption = {}; //validate with default options\n\n const result = validate(xmlData, validationOption);\n if (result !== true) {\n throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`)\n }\n }\n const orderedObjParser = new OrderedObjParser(this.options);\n orderedObjParser.entityDecoder.setExternalEntities(this.externalEntities);\n const orderedResult = orderedObjParser.parseXml(xmlData);\n if (this.options.preserveOrder || orderedResult === undefined) return orderedResult;\n else return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher);\n }\n\n /**\n * Add Entity which is not by default supported by this library\n * @param {string} key \n * @param {string} value \n */\n addEntity(key, value) {\n if (value.indexOf(\"&\") !== -1) {\n throw new Error(\"Entity value can't have '&'\")\n } else if (key.indexOf(\"&\") !== -1 || key.indexOf(\";\") !== -1) {\n throw new Error(\"An entity must be set without '&' and ';'. Eg. use '#xD' for ' '\")\n } else if (value === \"&\") {\n throw new Error(\"An entity with value '&' is not permitted\");\n } else {\n this.externalEntities[key] = value;\n }\n }\n\n /**\n * Returns a Symbol that can be used to access the metadata\n * property on a node.\n * \n * If Symbol is not available in the environment, an ordinary property is used\n * and the name of the property is here returned.\n * \n * The XMLMetaData property is only present when `captureMetaData`\n * is true in the options.\n */\n static getMetaDataSymbol() {\n return XmlNode.getMetaDataSymbol();\n }\n}","import { Expression, Matcher } from 'path-expression-matcher';\n\nconst EOL = \"\\n\";\n\n/**\n * \n * @param {array} jArray \n * @param {any} options \n * @returns \n */\nexport default function toXml(jArray, options) {\n let indentation = \"\";\n if (options.format && options.indentBy.length > 0) {\n indentation = EOL;\n }\n\n // Pre-compile stopNode expressions for pattern matching\n const stopNodeExpressions = [];\n if (options.stopNodes && Array.isArray(options.stopNodes)) {\n for (let i = 0; i < options.stopNodes.length; i++) {\n const node = options.stopNodes[i];\n if (typeof node === 'string') {\n stopNodeExpressions.push(new Expression(node));\n } else if (node instanceof Expression) {\n stopNodeExpressions.push(node);\n }\n }\n }\n\n // Initialize matcher for path tracking\n const matcher = new Matcher();\n\n return arrToStr(jArray, options, indentation, matcher, stopNodeExpressions);\n}\n\nfunction arrToStr(arr, options, indentation, matcher, stopNodeExpressions) {\n let xmlStr = \"\";\n let isPreviousElementTag = false;\n\n if (options.maxNestedTags && matcher.getDepth() > options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n\n if (!Array.isArray(arr)) {\n // Non-array values (e.g. string tag values) should be treated as text content\n if (arr !== undefined && arr !== null) {\n let text = arr.toString();\n text = replaceEntitiesValue(text, options);\n return text;\n }\n return \"\";\n }\n\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const tagName = propName(tagObj);\n if (tagName === undefined) continue;\n\n // Extract attributes from \":@\" property\n const attrValues = extractAttributeValues(tagObj[\":@\"], options);\n\n // Push tag to matcher WITH attributes\n matcher.push(tagName, attrValues);\n\n // Check if this is a stop node using Expression matching\n const isStopNode = checkStopNode(matcher, stopNodeExpressions);\n\n if (tagName === options.textNodeName) {\n let tagText = tagObj[tagName];\n if (!isStopNode) {\n tagText = options.tagValueProcessor(tagName, tagText);\n tagText = replaceEntitiesValue(tagText, options);\n }\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += tagText;\n isPreviousElementTag = false;\n matcher.pop();\n continue;\n } else if (tagName === options.cdataPropName) {\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n const val = tagObj[tagName][0][options.textNodeName];\n const safeVal = String(val).replace(/\\]\\]>/g, ']]]]>');\n xmlStr += ``;\n isPreviousElementTag = false;\n matcher.pop();\n continue;\n } else if (tagName === options.commentPropName) {\n const val = tagObj[tagName][0][options.textNodeName]\n const safeVal = String(val)\n .replace(/--/g, '- -') // -- is illegal anywhere in comment content\n .replace(/-$/, '- '); // trailing - would form -- with the closing -->\n xmlStr += indentation + ``;\n isPreviousElementTag = true;\n matcher.pop();\n continue;\n } else if (tagName[0] === \"?\") {\n const attStr = attr_to_str(tagObj[\":@\"], options, isStopNode);\n const tempInd = tagName === \"?xml\" ? \"\" : indentation;\n let piTextNodeName = tagObj[tagName][0][options.textNodeName];\n piTextNodeName = piTextNodeName.length !== 0 ? \" \" + piTextNodeName : \"\"; //remove extra spacing\n xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;\n isPreviousElementTag = true;\n matcher.pop();\n continue;\n }\n\n let newIdentation = indentation;\n if (newIdentation !== \"\") {\n newIdentation += options.indentBy;\n }\n\n // Pass isStopNode to attr_to_str so attributes are also not processed for stopNodes\n const attStr = attr_to_str(tagObj[\":@\"], options, isStopNode);\n const tagStart = indentation + `<${tagName}${attStr}`;\n\n // If this is a stopNode, get raw content without processing\n let tagValue;\n if (isStopNode) {\n tagValue = getRawContent(tagObj[tagName], options);\n } else {\n\n tagValue = arrToStr(tagObj[tagName], options, newIdentation, matcher, stopNodeExpressions);\n }\n\n if (options.unpairedTags.indexOf(tagName) !== -1) {\n if (options.suppressUnpairedNode) xmlStr += tagStart + \">\";\n else xmlStr += tagStart + \"/>\";\n } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {\n xmlStr += tagStart + \"/>\";\n } else if (tagValue && tagValue.endsWith(\">\")) {\n xmlStr += tagStart + `>${tagValue}${indentation}`;\n } else {\n xmlStr += tagStart + \">\";\n if (tagValue && indentation !== \"\" && (tagValue.includes(\"/>\") || tagValue.includes(\"`;\n }\n isPreviousElementTag = true;\n\n // Pop tag from matcher\n matcher.pop();\n }\n\n return xmlStr;\n}\n\n/**\n * Extract attribute values from the \":@\" object and return as plain object\n * for passing to matcher.push()\n */\nfunction extractAttributeValues(attrMap, options) {\n if (!attrMap || options.ignoreAttributes) return null;\n\n const attrValues = {};\n let hasAttrs = false;\n\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n // Remove the attribute prefix to get clean attribute name\n const cleanAttrName = attr.startsWith(options.attributeNamePrefix)\n ? attr.substr(options.attributeNamePrefix.length)\n : attr;\n attrValues[cleanAttrName] = attrMap[attr];\n hasAttrs = true;\n }\n\n return hasAttrs ? attrValues : null;\n}\n\n/**\n * Extract raw content from a stopNode without any processing\n * This preserves the content exactly as-is, including special characters\n */\nfunction getRawContent(arr, options) {\n if (!Array.isArray(arr)) {\n // Non-array values return as-is\n if (arr !== undefined && arr !== null) {\n return arr.toString();\n }\n return \"\";\n }\n\n let content = \"\";\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n const tagName = propName(item);\n\n if (tagName === options.textNodeName) {\n // Raw text content - NO processing, NO entity replacement\n content += item[tagName];\n } else if (tagName === options.cdataPropName) {\n // CDATA content\n content += item[tagName][0][options.textNodeName];\n } else if (tagName === options.commentPropName) {\n // Comment content\n content += item[tagName][0][options.textNodeName];\n } else if (tagName && tagName[0] === \"?\") {\n // Processing instruction - skip for stopNodes\n continue;\n } else if (tagName) {\n // Nested tags within stopNode\n // Recursively get raw content and reconstruct the tag\n // For stopNodes, we don't process attributes either\n const attStr = attr_to_str_raw(item[\":@\"], options);\n const nestedContent = getRawContent(item[tagName], options);\n\n if (!nestedContent || nestedContent.length === 0) {\n content += `<${tagName}${attStr}/>`;\n } else {\n content += `<${tagName}${attStr}>${nestedContent}`;\n }\n }\n }\n return content;\n}\n\n/**\n * Build attribute string for stopNodes - NO entity replacement\n */\nfunction attr_to_str_raw(attrMap, options) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n // For stopNodes, use raw value without processing\n let attrVal = attrMap[attr];\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${attrVal}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n if (key !== \":@\") return key;\n }\n}\n\nfunction attr_to_str(attrMap, options, isStopNode) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n let attrVal;\n\n if (isStopNode) {\n // For stopNodes, use raw value without any processing\n attrVal = attrMap[attr];\n } else {\n // Normal processing: apply attributeValueProcessor and entity replacement\n attrVal = options.attributeValueProcessor(attr, attrMap[attr]);\n attrVal = replaceEntitiesValue(attrVal, options);\n }\n\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${attrVal}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction checkStopNode(matcher, stopNodeExpressions) {\n if (!stopNodeExpressions || stopNodeExpressions.length === 0) return false;\n\n for (let i = 0; i < stopNodeExpressions.length; i++) {\n if (matcher.matches(stopNodeExpressions[i])) {\n return true;\n }\n }\n return false;\n}\n\nfunction replaceEntitiesValue(textValue, options) {\n if (textValue && textValue.length > 0 && options.processEntities) {\n for (let i = 0; i < options.entities.length; i++) {\n const entity = options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}\n\nfunction cdataVal(val) {\n\n}\n\nfunction commentVal(val) {\n\n}","'use strict';\n//parse Empty Node as self closing node\nimport buildFromOrderedJs from './orderedJs2Xml.js';\nimport getIgnoreAttributesFn from \"./ignoreAttributes.js\";\nimport { Expression, Matcher } from 'path-expression-matcher';\n\nconst defaultOptions = {\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n cdataPropName: false,\n format: false,\n indentBy: ' ',\n suppressEmptyNode: false,\n suppressUnpairedNode: true,\n suppressBooleanAttributes: true,\n tagValueProcessor: function (key, a) {\n return a;\n },\n attributeValueProcessor: function (attrName, a) {\n return a;\n },\n preserveOrder: false,\n commentPropName: false,\n unpairedTags: [],\n entities: [\n { regex: new RegExp(\"&\", \"g\"), val: \"&\" },//it must be on top\n { regex: new RegExp(\">\", \"g\"), val: \">\" },\n { regex: new RegExp(\"<\", \"g\"), val: \"<\" },\n { regex: new RegExp(\"\\'\", \"g\"), val: \"'\" },\n { regex: new RegExp(\"\\\"\", \"g\"), val: \""\" }\n ],\n processEntities: true,\n stopNodes: [],\n // transformTagName: false,\n // transformAttributeName: false,\n oneListGroup: false,\n maxNestedTags: 100,\n jPath: true // When true, callbacks receive string jPath; when false, receive Matcher instance\n};\n\nexport default function Builder(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n // Convert old-style stopNodes for backward compatibility\n // Old syntax: \"*.tag\" meant \"tag anywhere in tree\"\n // New syntax: \"..tag\" means \"tag anywhere in tree\"\n if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {\n this.options.stopNodes = this.options.stopNodes.map(node => {\n if (typeof node === 'string' && node.startsWith('*.')) {\n // Convert old wildcard syntax to deep wildcard\n return '..' + node.substring(2);\n }\n return node;\n });\n }\n\n // Pre-compile stopNode expressions for pattern matching\n this.stopNodeExpressions = [];\n if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {\n for (let i = 0; i < this.options.stopNodes.length; i++) {\n const node = this.options.stopNodes[i];\n if (typeof node === 'string') {\n this.stopNodeExpressions.push(new Expression(node));\n } else if (node instanceof Expression) {\n this.stopNodeExpressions.push(node);\n }\n }\n }\n\n if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {\n this.isAttribute = function (/*a*/) {\n return false;\n };\n } else {\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.attrPrefixLen = this.options.attributeNamePrefix.length;\n this.isAttribute = isAttribute;\n }\n\n this.processTextOrObjNode = processTextOrObjNode\n\n if (this.options.format) {\n this.indentate = indentate;\n this.tagEndChar = '>\\n';\n this.newLine = '\\n';\n } else {\n this.indentate = function () {\n return '';\n };\n this.tagEndChar = '>';\n this.newLine = '';\n }\n}\n\nBuilder.prototype.build = function (jObj) {\n if (this.options.preserveOrder) {\n return buildFromOrderedJs(jObj, this.options);\n } else {\n if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {\n jObj = {\n [this.options.arrayNodeName]: jObj\n }\n }\n // Initialize matcher for path tracking\n const matcher = new Matcher();\n return this.j2x(jObj, 0, matcher).val;\n }\n};\n\nBuilder.prototype.j2x = function (jObj, level, matcher) {\n let attrStr = '';\n let val = '';\n if (this.options.maxNestedTags && matcher.getDepth() >= this.options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n // Get jPath based on option: string for backward compatibility, or Matcher for new features\n const jPath = this.options.jPath ? matcher.toString() : matcher;\n\n // Check if current node is a stopNode (will be used for attribute encoding)\n const isCurrentStopNode = this.checkStopNode(matcher);\n\n for (let key in jObj) {\n if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;\n if (typeof jObj[key] === 'undefined') {\n // supress undefined node only if it is not an attribute\n if (this.isAttribute(key)) {\n val += '';\n }\n } else if (jObj[key] === null) {\n // null attribute should be ignored by the attribute list, but should not cause the tag closing\n if (this.isAttribute(key)) {\n val += '';\n } else if (key === this.options.cdataPropName) {\n val += '';\n } else if (key[0] === '?') {\n val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n }\n // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n } else if (jObj[key] instanceof Date) {\n val += this.buildTextValNode(jObj[key], key, '', level, matcher);\n } else if (typeof jObj[key] !== 'object') {\n //premitive type\n const attr = this.isAttribute(key);\n if (attr && !this.ignoreAttributesFn(attr, jPath)) {\n attrStr += this.buildAttrPairStr(attr, '' + jObj[key], isCurrentStopNode);\n } else if (!attr) {\n //tag value\n if (key === this.options.textNodeName) {\n let newval = this.options.tagValueProcessor(key, '' + jObj[key]);\n val += this.replaceEntitiesValue(newval);\n } else {\n // Check if this is a stopNode before building\n matcher.push(key);\n const isStopNode = this.checkStopNode(matcher);\n matcher.pop();\n\n if (isStopNode) {\n // Build as raw content without encoding\n const textValue = '' + jObj[key];\n if (textValue === '') {\n val += this.indentate(level) + '<' + key + this.closeTag(key) + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + key + '>' + textValue + '' + textValue + '${item}`;\n } else if (typeof item === 'object' && item !== null) {\n const nestedContent = this.buildRawContent(item);\n const nestedAttrs = this.buildAttributesForStopNode(item);\n if (nestedContent === '') {\n content += `<${key}${nestedAttrs}/>`;\n } else {\n content += `<${key}${nestedAttrs}>${nestedContent}`;\n }\n }\n }\n } else if (typeof value === 'object' && value !== null) {\n // Nested object\n const nestedContent = this.buildRawContent(value);\n const nestedAttrs = this.buildAttributesForStopNode(value);\n if (nestedContent === '') {\n content += `<${key}${nestedAttrs}/>`;\n } else {\n content += `<${key}${nestedAttrs}>${nestedContent}`;\n }\n } else {\n // Primitive value\n content += `<${key}>${value}`;\n }\n }\n\n return content;\n};\n\n// Build attribute string for stopNode (no entity encoding)\nBuilder.prototype.buildAttributesForStopNode = function (obj) {\n if (!obj || typeof obj !== 'object') return '';\n\n let attrStr = '';\n\n // Check for attributesGroupName (when attributes are grouped)\n if (this.options.attributesGroupName && obj[this.options.attributesGroupName]) {\n const attrGroup = obj[this.options.attributesGroupName];\n for (let attrKey in attrGroup) {\n if (!Object.prototype.hasOwnProperty.call(attrGroup, attrKey)) continue;\n const cleanKey = attrKey.startsWith(this.options.attributeNamePrefix)\n ? attrKey.substring(this.options.attributeNamePrefix.length)\n : attrKey;\n const val = attrGroup[attrKey];\n if (val === true && this.options.suppressBooleanAttributes) {\n attrStr += ' ' + cleanKey;\n } else {\n attrStr += ' ' + cleanKey + '=\"' + val + '\"'; // No encoding for stopNode\n }\n }\n } else {\n // Look for individual attributes\n for (let key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n const attr = this.isAttribute(key);\n if (attr) {\n const val = obj[key];\n if (val === true && this.options.suppressBooleanAttributes) {\n attrStr += ' ' + attr;\n } else {\n attrStr += ' ' + attr + '=\"' + val + '\"'; // No encoding for stopNode\n }\n }\n }\n }\n\n return attrStr;\n};\n\nBuilder.prototype.buildObjectNode = function (val, key, attrStr, level) {\n if (val === \"\") {\n if (key[0] === \"?\") return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n else {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n }\n } else {\n\n let tagEndExp = '' + val + tagEndExp);\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {\n return this.indentate(level) + `` + this.newLine;\n } else {\n return (\n this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +\n val +\n this.indentate(level) + tagEndExp);\n }\n }\n}\n\nBuilder.prototype.closeTag = function (key) {\n let closeTag = \"\";\n if (this.options.unpairedTags.indexOf(key) !== -1) { //unpaired\n if (!this.options.suppressUnpairedNode) closeTag = \"/\"\n } else if (this.options.suppressEmptyNode) { //empty\n closeTag = \"/\";\n } else {\n closeTag = `>/g, ']]]]>');\n return this.indentate(level) + `` + this.newLine;\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName) {\n const safeVal = String(val)\n .replace(/--/g, '- -') // -- is illegal anywhere in comment content\n .replace(/-$/, '- '); // trailing - would form -- with the closing -->\n return this.indentate(level) + `` + this.newLine;\n } else if (key[0] === \"?\") {//PI tag\n return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n } else {\n // Normal processing: apply tagValueProcessor and entity replacement\n let textValue = this.options.tagValueProcessor(key, val);\n textValue = this.replaceEntitiesValue(textValue);\n\n if (textValue === '') {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n } else {\n return this.indentate(level) + '<' + key + attrStr + '>' +\n textValue +\n ' 0 && this.options.processEntities) {\n for (let i = 0; i < this.options.entities.length; i++) {\n const entity = this.options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}\n\nfunction indentate(level) {\n return this.options.indentBy.repeat(level);\n}\n\nfunction isAttribute(name /*, options*/) {\n if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {\n return name.substr(this.attrPrefixLen);\n } else {\n return false;\n }\n}","export default function getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}","// Re-export from fast-xml-builder for backward compatibility\nimport XMLBuilder from 'fast-xml-builder';\nexport default XMLBuilder;\n\n// If there are any named exports you also want to re-export:\nexport * from 'fast-xml-builder';","'use strict';\n\nimport { validate } from './validator.js';\nimport XMLParser from './xmlparser/XMLParser.js';\nimport XMLBuilder from './xmlbuilder/json2xml.js';\n\nconst XMLValidator = {\n validate: validate\n}\nexport {\n XMLParser,\n XMLValidator,\n XMLBuilder\n};"],"names":["root","factory","exports","module","define","amd","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","nameStartChar","regexName","RegExp","getAllMatches","string","regex","matches","match","exec","allmatches","startIndex","lastIndex","length","len","index","push","isName","DANGEROUS_PROPERTY_NAMES","criticalProperties","defaultOptions","allowBooleanAttributes","unpairedTags","validate","xmlData","options","assign","tags","tagFound","reachedRoot","substr","i","readPI","err","isWhiteSpace","getErrorObject","getLineNumberForPosition","tagStartPos","readCommentAndCDATA","closingTag","tagName","trim","substring","validateTagName","result","readAttributeStr","attrStr","attrStrStart","isValid","validateAttributeString","code","msg","line","tagClosed","otg","pop","openPos","col","indexOf","afterAmp","validateAmpersand","JSON","stringify","map","t","replace","char","start","tagname","angleBracketsCount","doubleQuote","singleQuote","startChar","validAttrStrRegxp","attrNames","getPositionFromMatch","undefined","attrName","validateAttrName","re","validateNumberAmpersand","count","message","lineNumber","lines","split","defaultOnDangerousProperty","name","includes","preserveOrder","attributeNamePrefix","attributesGroupName","textNodeName","ignoreAttributes","removeNSPrefix","parseTagValue","parseAttributeValue","trimValues","cdataPropName","numberParseOptions","hex","leadingZeros","eNotation","tagValueProcessor","val","attributeValueProcessor","stopNodes","alwaysCreateTextNode","isArray","commentPropName","processEntities","htmlEntities","entityDecoder","ignoreDeclaration","ignorePiTags","transformTagName","transformAttributeName","updateTag","jPath","attrs","captureMetaData","maxNestedTags","strictReservedNames","onDangerousProperty","validatePropertyName","propertyName","optionName","normalized","toLowerCase","some","dangerous","Error","normalizeProcessEntities","enabled","maxEntitySize","maxExpansionDepth","maxTotalExpansions","Infinity","maxExpandedLength","maxEntityCount","allowedTags","tagFilter","appliesTo","Math","max","_value$maxEntitySize","_value$maxExpansionDe","_value$maxTotalExpans","_value$maxExpandedLen","_value$maxEntityCount","_value$allowedTags","_value$tagFilter","_value$appliesTo","METADATA_SYMBOL","buildOptions","built","_i","_propertyNameOptions","_propertyNameOptions$","unpairedTagsSet","Set","Array","node","startsWith","XmlNode","child","create","_proto","add","_this$child$push","addChild","_this$child$push2","_this$child$push3","keys","getMetaDataSymbol","DocTypeReader","suppressValidationErr","readDocType","entities","entityCount","hasBody","comment","hasSeq","entityName","_this$readEntityExp","readEntityExp","readElementExp","readNotationExp","skipWhitespace","test","validateEntityName","toUpperCase","entityValue","_this$readIdentifierV","readIdentifierVal","notationName","identifierType","publicIdentifier","systemIdentifier","_this$readIdentifierV2","_this$readIdentifierV3","_this$readIdentifierV4","type","identifierVal","elementName","contentModel","readAttlistExp","attributeName","attributeType","allowedNotations","notation","join","defaultValue","_this$readIdentifierV5","data","seq","j","hexRegex","numRegex","consider","decimalPoint","infinity","eNotationRegx","MatcherView","constructor","matcher","_matcher","separator","getCurrentTag","path","tag","getCurrentNamespace","namespace","getAttrValue","values","hasAttr","current","getPosition","position","getCounter","counter","getIndex","getDepth","toString","includeNamespace","toArray","n","expression","matchesAny","exprSet","Matcher","siblingStacks","_pathStringCache","_view","attrValues","currentLevel","Map","siblings","siblingKey","set","updateCurrent","sep","reset","segments","hasDeepWildcard","_matchWithDeepWildcard","_matchSimple","_matchSegment","pathIdx","segIdx","segment","nextSeg","found","isCurrentNode","attrValue","String","positionValue","snapshot","restore","readOnly","Expression","pattern","_parse","_hasDeepWildcard","seg","_hasAttributeCondition","_hasPositionSelector","currentPart","_parseSegment","part","bracketContent","withoutBrackets","bracketMatch","content","slice","tagAndPosition","nsIndex","positionMatch","colonIndex","lastIndexOf","tagPart","posPart","eqIndex","nthMatch","parseInt","hasAttributeCondition","hasPositionSelector","ExpressionSet","_byDepthAndTag","_wildcardByDepth","_deepWildcards","_patterns","_sealed","TypeError","has","depth","lastSeg","addAll","expressions","expr","size","seal","isSealed","findMatch","exactKey","exactBucket","wildcardBucket","CURRENCY","cent","pound","curren","yen","euro","dollar","fnof","inr","af","birr","peso","rub","won","yuan","cedil","XML","amp","apos","gt","lt","quot","COMMON_HTML","nbsp","copy","reg","trade","mdash","ndash","hellip","laquo","raquo","lsquo","rsquo","ldquo","rdquo","bull","para","sect","deg","frac12","frac14","frac34","SPECIAL_CHARS","ch","mergeEntityMaps","maps","out","raw","LIMIT_TIER_EXTERNAL","LIMIT_TIER_BASE","LIMIT_TIER_ALL","NCR_LEVEL","freeze","allow","leave","remove","throw","XML10_ALLOWED_C0","EntityDecoder","_limit","limit","_maxTotalExpansions","_maxExpandedLength","_postCheck","postCheck","r","_limitTiers","applyLimitsTo","_numericAllowed","numericAllowed","_baseMap","DEFAULT_XML_ENTITIES","namedEntities","_externalMap","_inputMap","_totalExpansions","_expandedLength","_removeSet","_leaveSet","ncrCfg","ncr","xmlVersion","onLevel","nullLevel","onNCR","nullNCR","parseNCRConfig","_ncrXmlVersion","_ncrOnLevel","_ncrNullLevel","setExternalEntities","addExternalEntity","addInputEntities","setXmlVersion","version","decode","str","original","chunks","last","limitExpansions","limitLength","checkLimits","charCodeAt","token","replacement","tier","ncrResult","_resolveNCR","resolved","_resolveName","_tierCounts","delta","_classifyNCR","cp","_applyNCRAction","action","fromCodePoint","padStart","second","Number","isNaN","minimum","effective","_extends","bind","e","arguments","apply","extractRawAttributes","prefixedAttrs","rawAttrs","extractNamespace","rawTagName","ns","OrderedObjParser","currentNode","tagsNodeStack","parseXml","parseTextData","resolveNameSpace","buildAttributesMap","isItStopNode","replaceEntitiesValue","readStopNodeData","saveTextToParentTag","ignoreAttributesFn","_step","_iterator","_createForOfIteratorHelperLoose","done","entityExpansionCount","currentExpandedLength","readonlyMatcher","isCurrentNodeStopNode","stopNodeExpressionsSet","stopNodesOpts","stopNodeExp","dontTrim","hasAttributes","isLeafNode","escapeEntities","jPathOrMatcher","newval","parseValue","prefix","charAt","attrsRegx","force","processedVals","hasRawAttrs","rawAttrsForMatcher","oldVal","jPathStr","hasAttrs","aName","sanitizeName","newVal","attrCollection","xmlObj","xmlNode","textData","docTypeReader","xmlLen","c1","closeIndex","findClosingIndex","lastTagName","tagData","readTagExp","attsMap","tagExp","ver","childNode","attrExpPresent","endIndex","_ref","_ref2","context","min","_transformTagName","lastTag","isSelfClosing","tagContent","_transformTagName2","entityConfig","parentNode","errMsg","closingIndex","findClosingChar","closingChar","attrBoundary","chars","closeCode0","closeCode1","fromCharCode","tagExpWithClosingIndex","separatorIndex","search","trimStart","openTagCount","xmllen","shouldParse","trimmedStr","skipLike","numStr","window","parse_int","isFinite","sign","eChar","eAdjacentToLeadingZeros","resolveEnotation","numTrimmedByZeros","decimalAdjacentToLeadingZeros","num","parsedStr","isPositive","handleInfinity","toNumber","fn","newTagName","stripAttributePrefix","prettify","compress","arr","text","compressedObj","tagObj","property","propName","isLeaf","isLeafTag","assignAttributes","attrMap","atrrName","rawAttrName","propCount","XMLParser","externalEntities","parse","validationOption","orderedObjParser","orderedResult","addEntity","toXml","jArray","indentation","format","indentBy","stopNodeExpressions","arrToStr","xmlStr","isPreviousElementTag","extractAttributeValues","isStopNode","checkStopNode","tagText","attStr","attr_to_str","tempInd","piTextNodeName","newIdentation","tagStart","tagValue","getRawContent","suppressUnpairedNode","suppressEmptyNode","endsWith","attr","item","attr_to_str_raw","nestedContent","attrVal","suppressBooleanAttributes","textValue","entity","a","oneListGroup","Builder","isAttribute","attrPrefixLen","processTextOrObjNode","indentate","tagEndChar","newLine","object","level","extractAttributes","rawContent","buildRawContent","buildAttributesForStopNode","buildObjectNode","j2x","buildTextValNode","repeat","build","jObj","buildFromOrderedJs","arrayNodeName","isCurrentStopNode","Date","buildAttrPairStr","closeTag","arrLen","listTagVal","listTagAttr","Ks","L","attrGroup","attrKey","nestedAttrs","cleanKey","tagEndExp","piClosingChar","safeVal","XMLValidator"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/lib/fxparser.min.js b/node_modules/fast-xml-parser/lib/fxparser.min.js new file mode 100644 index 0000000..762d7de --- /dev/null +++ b/node_modules/fast-xml-parser/lib/fxparser.min.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.XMLParser=e():t.XMLParser=e()}(this,()=>(()=>{"use strict";var t={d:(e,r)=>{for(var n in r)t.o(r,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:r[n]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{default:()=>Tt});var r=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=new RegExp("^["+r+"]["+r+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function i(t,e){for(var r=[],n=e.exec(t);n;){var i=[];i.startIndex=e.lastIndex-n[0].length;for(var a=n.length,s=0;s0?this.child.push(((r={})[t.tagname]=t.child,r[":@"]=t[":@"],r)):this.child.push(((n={})[t.tagname]=t.child,n)),void 0!==e&&(this.child[this.child.length-1][d]={startIndex:e})},t.getMetaDataSymbol=function(){return d},t}(),g=function(){function t(t){this.suppressValidationErr=!t,this.options=t}var e=t.prototype;return e.readDocType=function(t,e){var r=Object.create(null),n=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");e+=9;for(var i=1,a=!1,s=!1;e"===t[e]){if(s?"-"===t[e-1]&&"-"===t[e-2]&&(s=!1,i--):i--,0===i)break}else"["===t[e]?a=!0:t[e];else{if(a&&v(t,"!ENTITY",e)){e+=7;var o,h=void 0,l=this.readEntityExp(t,e+1,this.suppressValidationErr);if(o=l[0],h=l[1],e=l[2],-1===h.indexOf("&")){if(!1!==this.options.enabled&&null!=this.options.maxEntityCount&&n>=this.options.maxEntityCount)throw new Error("Entity count ("+(n+1)+") exceeds maximum allowed ("+this.options.maxEntityCount+")");r[o]=h,n++}}else if(a&&v(t,"!ELEMENT",e))e+=8,e=this.readElementExp(t,e+1).index;else if(a&&v(t,"!ATTLIST",e))e+=8;else if(a&&v(t,"!NOTATION",e))e+=9,e=this.readNotationExp(t,e+1,this.suppressValidationErr).index;else{if(!v(t,"!--",e))throw new Error("Invalid DOCTYPE");s=!0}i++}if(0!==i)throw new Error("Unclosed DOCTYPE");return{entities:r,i:e}},e.readEntityExp=function(t,e){for(var r=e=m(t,e);ethis.options.maxEntitySize)throw new Error('Entity "'+n+'" size ('+i.length+") exceeds maximum allowed size ("+this.options.maxEntitySize+")");return[n,i,--e]},e.readNotationExp=function(t,e){for(var r=e=m(t,e);et.length)&&(e=t.length);for(var r=0,n=Array(e);r0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const r=e[e.length-1];return void 0!==r.values&&t in r.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class S{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new _(this)}push(t,e=null,r=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const n=this.path.length;this.siblingStacks[n]||(this.siblingStacks[n]=new Map);const i=this.siblingStacks[n],a=r?`${r}:${t}`:t,s=i.get(a)||0;let o=0;for(const t of i.values())o+=t;i.set(a,s+1);const h={tag:t,position:o,counter:s};null!=r&&(h.namespace=r),null!=e&&(h.values=e),this.path.push(h)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const r=t||this.separator;if(r===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(r);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(r)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e=0&&e>=0;){const n=t[r];if("deep-wildcard"===n.type){if(r--,r<0)return!0;const n=t[r];let i=!1;for(let t=e;t>=0;t--)if(this._matchSegment(n,this.path[t],t===this.path.length-1)){e=t-1,r--,i=!0;break}if(!i)return!1}else{if(!this._matchSegment(n,this.path[e],e===this.path.length-1))return!1;e--,r--}}return r<0}_matchSegment(t,e,r){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!r)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!r)return!1;const n=e.counter??0;if("first"===t.position&&0!==n)return!1;if("odd"===t.position&&n%2!=1)return!1;if("even"===t.position&&n%2!=0)return!1;if("nth"===t.position&&n!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}class T{constructor(t,e={},r){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=r,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let r=0,n="";for(;r",lt:"<",quot:'"'},P={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},M=new Set("!?\\\\/[]$%{}^&*()<>|+");function D(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(M.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function O(...t){const e=Object.create(null);for(const r of t)if(r)for(const t of Object.keys(r)){const n=r[t];if("string"==typeof n)e[t]=n;else if(n&&"object"==typeof n&&void 0!==n.val){const r=n.val;"string"==typeof r&&(e[t]=r)}}return e}const j="external",L="base",k="all",V=Object.freeze({allow:0,leave:1,remove:2,throw:3}),F=new Set([9,10,13]);class ${constructor(t={}){var e;this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitTiers=(e=this._limit.applyLimitsTo??j)&&e!==j?e===k?new Set([k]):e===L?new Set([L]):Array.isArray(e)?new Set(e):new Set([j]):new Set([j]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=O(I,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const r=function(t){if(!t)return{xmlVersion:1,onLevel:V.allow,nullLevel:V.remove};const e=1.1===t.xmlVersion?1.1:1,r=V[t.onNCR]??V.allow,n=V[t.nullNCR]??V.remove;return{xmlVersion:e,onLevel:r,nullLevel:Math.max(n,V.remove)}}(t.ncr);this._ncrXmlVersion=r.xmlVersion,this._ncrOnLevel=r.onLevel,this._ncrNullLevel=r.nullLevel}setExternalEntities(t){if(t)for(const e of Object.keys(t))D(e);this._externalMap=O(t)}addExternalEntity(t,e){D(t),"string"==typeof e&&-1===e.indexOf("&")&&(this._externalMap[t]=e)}addInputEntities(t){this._totalExpansions=0,this._expandedLength=0,this._inputMap=O(t)}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=1.1===t?1.1:1}decode(t){if("string"!=typeof t||0===t.length)return t;const e=t,r=[],n=t.length;let i=0,a=0;const s=this._maxTotalExpansions>0,o=this._maxExpandedLength>0,h=s||o;for(;a=n||59!==t.charCodeAt(e)){a++;continue}const l=t.slice(a+1,e);if(0===l.length){a++;continue}let u,p;if(this._removeSet.has(l))u="",void 0===p&&(p=j);else{if(this._leaveSet.has(l)){a++;continue}if(35===l.charCodeAt(0)){const t=this._resolveNCR(l);if(void 0===t){a++;continue}u=t,p=L}else{const t=this._resolveName(l);u=t?.value,p=t?.tier}}if(void 0!==u){if(a>i&&r.push(t.slice(i,a)),r.push(u),i=e+1,a=i,h&&this._tierCounts(p)){if(s&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(o){const t=u.length-(l.length+2);if(t>0&&(this._expandedLength+=t,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else a++}i=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!F.has(t)?V.remove:-1}_applyNCRAction(t,e,r){switch(t){case V.allow:return String.fromCodePoint(r);case V.remove:return"";case V.leave:return;case V.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${r.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(r)}}_resolveNCR(t){const e=t.charCodeAt(1);let r;if(r=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(r)||r<0||r>1114111)return;const n=this._classifyNCR(r);if(!this._numericAllowed&&n0){var r=t.substring(0,e);if("xmlns"!==r)return r}}}var X=function(t){var e;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=q,this.parseTextData=Y,this.resolveNameSpace=B,this.buildAttributesMap=G,this.isItStopNode=Q,this.replaceEntitiesValue=J,this.readStopNodeData=rt,this.saveTextToParentTag=K,this.addChild=Z,this.ignoreAttributesFn="function"==typeof(e=this.options.ignoreAttributes)?e:Array.isArray(e)?function(t){for(var r,n=function(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,e){if(t){if("string"==typeof t)return w(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?w(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(e);!(r=n()).done;){var i=r.value;if("string"==typeof i&&t===i)return!0;if(i instanceof RegExp&&i.test(t))return!0}}:function(){return!1},this.entityExpansionCount=0,this.currentExpandedLength=0;var r=R({},I);this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?r=this.options.htmlEntities:!0===this.options.htmlEntities&&(r=R({},P,A)),this.entityDecoder=new $({namedEntities:r,numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo}})),this.matcher=new S,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new C;var n=this.options.stopNodes;if(n&&n.length>0){for(var i=0;i0)){s||(t=this.replaceEntitiesValue(t,e,r));var h=o.jPath?r.toString():r,l=o.tagValueProcessor(e,t,h,i,a);return null==l?t:typeof l!=typeof t||l!==t?l:o.trimValues||t.trim()===t?nt(t,o.parseTagValue,o.numberParseOptions):t}}function B(t){if(this.options.removeNSPrefix){var e=t.split(":"),r="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=r+e[1])}return t}var z=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function G(t,e,r,n){void 0===n&&(n=!1);var a=this.options;if(!0===n||!0!==a.ignoreAttributes&&"string"==typeof t){for(var s=i(t,z),o=s.length,h={},l=new Array(o),u=!1,p={},d=0;d",o,"Closing Tag is not closed."),u=t.substring(o+2,l).trim();if(i.removeNSPrefix){var p=u.indexOf(":");-1!==p&&(u=u.substr(p+1))}u=it(i.transformTagName,u,"",i).tagName,r&&(n=this.saveTextToParentTag(n,r,this.readonlyMatcher));var d=this.matcher.getCurrentTag();if(u&&i.unpairedTagsSet.has(u))throw new Error("Unpaired tag can not be used as closing tag: ");d&&i.unpairedTagsSet.has(d)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,r=this.tagsNodeStack.pop(),n="",o=l}else if(63===h){var c=et(t,o,!1,"?>");if(!c)throw new Error("Pi Tag is not closed.");n=this.saveTextToParentTag(n,r,this.readonlyMatcher);var m=this.buildAttributesMap(c.tagExp,this.matcher,c.tagName,!0);if(m){var v=m[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(v)||1)}if(i.ignoreDeclaration&&"?xml"===c.tagName||i.ignorePiTags);else{var x=new f(c.tagName);x.add(i.textNodeName,""),c.tagName!==c.tagExp&&c.attrExpPresent&&!0!==i.ignoreAttributes&&(x[":@"]=m),this.addChild(r,x,this.readonlyMatcher,o)}o=c.closeIndex+1}else if(33===h&&45===t.charCodeAt(o+2)&&45===t.charCodeAt(o+3)){var y=H(t,"--\x3e",o+4,"Comment is not closed.");if(i.commentPropName){var E,b=t.substring(o+4,y-2);n=this.saveTextToParentTag(n,r,this.readonlyMatcher),r.add(i.commentPropName,[(E={},E[i.textNodeName]=b,E)])}o=y}else if(33===h&&68===t.charCodeAt(o+2)){var N=a.readDocType(t,o);this.entityDecoder.addInputEntities(N.entities),o=N.i}else if(33===h&&91===t.charCodeAt(o+2)){var w=H(t,"]]>",o,"CDATA is not closed.")-2,_=t.substring(o+9,w);n=this.saveTextToParentTag(n,r,this.readonlyMatcher);var S,T=this.parseTextData(_,r.tagname,this.readonlyMatcher,!0,!1,!0,!0);null==T&&(T=""),i.cdataPropName?r.add(i.cdataPropName,[(S={},S[i.textNodeName]=_,S)]):r.add(i.textNodeName,T),o=w+2}else{var C=et(t,o,i.removeNSPrefix);if(!C){var A=t.substring(Math.max(0,o-50),Math.min(s,o+50));throw new Error("readTagExp returned undefined at position "+o+'. Context: "'+A+'"')}var I=C.tagName,P=C.rawTagName,M=C.tagExp,D=C.attrExpPresent,O=C.closeIndex,j=it(i.transformTagName,I,M,i);if(I=j.tagName,M=j.tagExp,i.strictReservedNames&&(I===i.commentPropName||I===i.cdataPropName||I===i.textNodeName||I===i.attributesGroupName))throw new Error("Invalid tag name: "+I);r&&n&&"!xml"!==r.tagname&&(n=this.saveTextToParentTag(n,r,this.readonlyMatcher,!1));var L=r;L&&i.unpairedTagsSet.has(L.tagname)&&(r=this.tagsNodeStack.pop(),this.matcher.pop());var k=!1;M.length>0&&M.lastIndexOf("/")===M.length-1&&(k=!0,M="/"===I[I.length-1]?I=I.substr(0,I.length-1):M.substr(0,M.length-1),D=I!==M);var V,F=null;V=W(P),I!==e.tagname&&this.matcher.push(I,{},V),I!==M&&D&&(F=this.buildAttributesMap(M,this.matcher,I))&&U(F,i),I!==e.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());var $=o;if(this.isCurrentNodeStopNode){var R="";if(k)o=C.closeIndex;else if(i.unpairedTagsSet.has(I))o=C.closeIndex;else{var X=this.readStopNodeData(t,P,O+1);if(!X)throw new Error("Unexpected end of "+P);o=X.i,R=X.tagContent}var Y=new f(I);F&&(Y[":@"]=F),Y.add(i.textNodeName,R),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(r,Y,this.readonlyMatcher,$)}else{if(k){var B=it(i.transformTagName,I,M,i);I=B.tagName,M=B.tagExp;var z=new f(I);F&&(z[":@"]=F),this.addChild(r,z,this.readonlyMatcher,$),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else{if(i.unpairedTagsSet.has(I)){var G=new f(I);F&&(G[":@"]=F),this.addChild(r,G,this.readonlyMatcher,$),this.matcher.pop(),this.isCurrentNodeStopNode=!1,o=C.closeIndex;continue}var q=new f(I);if(this.tagsNodeStack.length>i.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(r),F&&(q[":@"]=F),this.addChild(r,q,this.readonlyMatcher,$),r=q}n="",o=O}}}else n+=t[o];return e.child};function Z(t,e,r,n){this.options.captureMetaData||(n=void 0);var i=this.options.jPath?r.toString():r,a=this.options.updateTag(e.tagname,i,e[":@"]);!1===a||("string"==typeof a?(e.tagname=a,t.addChild(e,n)):t.addChild(e,n))}function J(t,e,r){var n=this.options.processEntities;if(!n||!n.enabled)return t;if(n.allowedTags){var i=this.options.jPath?r.toString():r;if(!(Array.isArray(n.allowedTags)?n.allowedTags.includes(e):n.allowedTags(e,i)))return t}if(n.tagFilter){var a=this.options.jPath?r.toString():r;if(!n.tagFilter(e,a))return t}return this.entityDecoder.decode(t)}function K(t,e,r,n){return t&&(void 0===n&&(n=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,r,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,n))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function Q(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function H(t,e,r,n){var i=t.indexOf(e,r);if(-1===i)throw new Error(n);return i+e.length-1}function tt(t,e,r,n){var i=t.indexOf(e,r);if(-1===i)throw new Error(n);return i}function et(t,e,r,n){void 0===n&&(n=">");var i=function(t,e,r){void 0===r&&(r=">");for(var n=0,i=[],a=t.length,s=r.charCodeAt(0),o=r.length>1?r.charCodeAt(1):-1,h=e;h",r,e+" is not closed");if(t.substring(r+2,o).trim()===e&&0===--i)return{tagContent:t.substring(n,r),i:o};r=o}else if(63===s)r=H(t,"?>",r+1,"StopNode is not closed.");else if(33===s&&45===t.charCodeAt(r+2)&&45===t.charCodeAt(r+3))r=H(t,"--\x3e",r+3,"StopNode is not closed.");else if(33===s&&91===t.charCodeAt(r+2))r=H(t,"]]>",r,"StopNode is not closed.")-2;else{var h=et(t,r,">");h&&((h&&h.tagName)===e&&"/"!==h.tagExp[h.tagExp.length-1]&&i++,r=h.closeIndex)}}}function nt(t,e,r){if(e&&"string"==typeof t){var n=t.trim();return"true"===n||"false"!==n&&function(t,e={}){if(e=Object.assign({},b,e),!t||"string"!=typeof t)return t;let r=t.trim();if(0===r.length)return t;if(void 0!==e.skipLike&&e.skipLike.test(r))return t;if("0"===r)return 0;if(e.hex&&y.test(r))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(r);if(isFinite(r)){if(r.includes("e")||r.includes("E"))return function(t,e,r){if(!r.eNotation)return t;const n=e.match(N);if(n){let i=n[1]||"";const a=-1===n[3].indexOf("e")?"E":"e",s=n[2],o=i?t[s.length+1]===a:t[s.length]===a;return s.length>1&&o?t:(1!==s.length||!n[3].startsWith(`.${a}`)&&n[3][0]!==a)&&s.length>0?r.leadingZeros&&!o?(e=(n[1]||"")+n[3],Number(e)):t:Number(e)}return t}(t,r,e);{const i=E.exec(r);if(i){const a=i[1]||"",s=i[2];let o=(n=i[3])&&-1!==n.indexOf(".")?("."===(n=n.replace(/0+$/,""))?n="0":"."===n[0]?n="0"+n:"."===n[n.length-1]&&(n=n.substring(0,n.length-1)),n):n;const h=a?"."===t[s.length+1]:"."===t[s.length];if(!e.leadingZeros&&(s.length>1||1===s.length&&!h))return t;{const n=Number(r),i=String(n);if(0===n)return n;if(-1!==i.search(/[eE]/))return e.eNotation?n:t;if(-1!==r.indexOf("."))return"0"===i||i===o||i===`${a}${o}`?n:t;let h=s?o:r;return s?h===i||a+h===i?n:t:h===i||h===a+i?n:t}}return t}}var n;return function(t,e,r){const n=e===1/0;switch(r.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return n?"Infinity":"-Infinity";default:return t}}(t,Number(r),e)}(t,r)}return void 0!==t?t:""}function it(t,e,r,n){if(t){var i=t(e);r===e&&(r=i),e=i}return{tagName:e=at(e,n),tagExp:r}}function at(t,e){if(o.includes(t))throw new Error('[SECURITY] Invalid name: "'+t+'" is a reserved JavaScript keyword that could cause prototype pollution');return s.includes(t)?e.onDangerousProperty(t):t}var st=f.getMetaDataSymbol();function ot(t,e){if(!t||"object"!=typeof t)return{};if(!e)return t;var r={};for(var n in t)n.startsWith(e)?r[n.substring(e.length)]=t[n]:r[n]=t[n];return r}function ht(t,e,r,n){return lt(t,e,r,n)}function lt(t,e,r,n){for(var i,a={},s=0;s0&&(a[e.textNodeName]=i):void 0!==i&&(a[e.textNodeName]=i),a}function ut(t){for(var e=Object.keys(t),r=0;r5&&"xml"===n)return bt("InvalidXml","XML declaration allowed only at the start of the document.",_t(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}}return e}function mt(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){var r=1;for(e+=8;e"===t[e]&&0===--r)break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}function vt(t,e){for(var r="",n="",i=!1;e"===t[e]&&""===n){i=!0;break}r+=t[e]}return""===n&&{value:r,index:e,tagClosed:i}}var xt=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function yt(t,e){for(var r=i(t,xt),n={},a=0;a"!==t[a]&&" "!==t[a]&&"\t"!==t[a]&&"\n"!==t[a]&&"\r"!==t[a];a++)h+=t[a];if("/"===(h=h.trim())[h.length-1]&&(h=h.substring(0,h.length-1),a--),!wt(h))return bt("InvalidTag",0===h.trim().length?"Invalid space after '<'.":"Tag '"+h+"' is an invalid name.",_t(t,a));var l=vt(t,a);if(!1===l)return bt("InvalidAttr","Attributes for '"+h+"' have open quote.",_t(t,a));var u=l.value;if(a=l.index,"/"===u[u.length-1]){var p=a-u.length,d=yt(u=u.substring(0,u.length-1),e);if(!0!==d)return bt(d.err.code,d.err.msg,_t(t,p+d.err.line));n=!0}else if(o){if(!l.tagClosed)return bt("InvalidTag","Closing tag '"+h+"' doesn't have proper closing.",_t(t,a));if(u.trim().length>0)return bt("InvalidTag","Closing tag '"+h+"' can't have attributes or invalid starting.",_t(t,s));if(0===r.length)return bt("InvalidTag","Closing tag '"+h+"' has not been opened.",_t(t,s));var c=r.pop();if(h!==c.tagName){var f=_t(t,c.tagStartPos);return bt("InvalidTag","Expected closing tag '"+c.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+h+"'.",_t(t,s))}0==r.length&&(i=!0)}else{var g=yt(u,e);if(!0!==g)return bt(g.err.code,g.err.msg,_t(t,a-u.length+g.err.line));if(!0===i)return bt("InvalidXml","Multiple possible root nodes found.",_t(t,a));-1!==e.unpairedTags.indexOf(h)||r.push({tagName:h,tagStartPos:s}),n=!0}for(a++;a0)||bt("InvalidXml","Invalid '"+JSON.stringify(r.map(function(t){return t.tagName}),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):bt("InvalidXml","Start tag expected.",1)}(t,e);if(!0!==r)throw Error(r.err.msg+":"+r.err.line+":"+r.err.col)}var n=new X(this.options);n.entityDecoder.setExternalEntities(this.externalEntities);var i=n.parseXml(t);return this.options.preserveOrder||void 0===i?i:ht(i,this.options,n.matcher,n.readonlyMatcher)},e.addEntity=function(t,e){if(-1!==e.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==t.indexOf("&")||-1!==t.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e},t.getMetaDataSymbol=function(){return f.getMetaDataSymbol()},t}();return e})()); +//# sourceMappingURL=fxparser.min.js.map \ No newline at end of file diff --git a/node_modules/fast-xml-parser/lib/fxparser.min.js.map b/node_modules/fast-xml-parser/lib/fxparser.min.js.map new file mode 100644 index 0000000..60fcd3a --- /dev/null +++ b/node_modules/fast-xml-parser/lib/fxparser.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"./lib/fxparser.min.js","mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAmB,UAAID,IAEvBD,EAAgB,UAAIC,GACrB,CATD,CASGK,KAAM,I,mBCRT,IAAIC,EAAsB,CCA1BA,EAAwB,CAACL,EAASM,KACjC,IAAI,IAAIC,KAAOD,EACXD,EAAoBG,EAAEF,EAAYC,KAASF,EAAoBG,EAAER,EAASO,IAC5EE,OAAOC,eAAeV,EAASO,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3EF,EAAwB,CAACQ,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFT,EAAyBL,IACH,oBAAXkB,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeV,EAASkB,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,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/webpack/universalModuleDefinition","webpack://XMLParser/webpack/bootstrap","webpack://XMLParser/webpack/runtime/define property getters","webpack://XMLParser/webpack/runtime/hasOwnProperty shorthand","webpack://XMLParser/webpack/runtime/make namespace object","webpack://XMLParser/./src/util.js","webpack://XMLParser/./src/xmlparser/OptionsBuilder.js","webpack://XMLParser/./src/xmlparser/xmlNode.js","webpack://XMLParser/./src/xmlparser/DocTypeReader.js","webpack://XMLParser/./node_modules/strnum/strnum.js","webpack://XMLParser/./node_modules/path-expression-matcher/src/Matcher.js","webpack://XMLParser/./node_modules/path-expression-matcher/src/Expression.js","webpack://XMLParser/./node_modules/path-expression-matcher/src/ExpressionSet.js","webpack://XMLParser/./node_modules/@nodable/entities/src/entities.js","webpack://XMLParser/./node_modules/@nodable/entities/src/EntityDecoder.js","webpack://XMLParser/./src/xmlparser/OrderedObjParser.js","webpack://XMLParser/./src/ignoreAttributes.js","webpack://XMLParser/./src/xmlparser/node2json.js","webpack://XMLParser/./src/validator.js","webpack://XMLParser/./src/xmlparser/XMLParser.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"XMLParser\"] = factory();\n\telse\n\t\troot[\"XMLParser\"] = factory();\n})(this, () => {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","'use strict';\n\nconst nameStartChar = ':A-Za-z_\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD';\nconst nameChar = nameStartChar + '\\\\-.\\\\d\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040';\nexport const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*';\nconst regexName = new RegExp('^' + nameRegexp + '$');\n\nexport function getAllMatches(string, regex) {\n const matches = [];\n let match = regex.exec(string);\n while (match) {\n const allmatches = [];\n allmatches.startIndex = regex.lastIndex - match[0].length;\n const len = match.length;\n for (let index = 0; index < len; index++) {\n allmatches.push(match[index]);\n }\n matches.push(allmatches);\n match = regex.exec(string);\n }\n return matches;\n}\n\nexport const isName = function (string) {\n const match = regexName.exec(string);\n return !(match === null || typeof match === 'undefined');\n}\n\nexport function isExist(v) {\n return typeof v !== 'undefined';\n}\n\nexport function isEmptyObject(obj) {\n return Object.keys(obj).length === 0;\n}\n\nexport function getValue(v) {\n if (exports.isExist(v)) {\n return v;\n } else {\n return '';\n }\n}\n\n/**\n * Dangerous property names that could lead to prototype pollution or security issues\n */\nexport const DANGEROUS_PROPERTY_NAMES = [\n // '__proto__',\n // 'constructor',\n // 'prototype',\n 'hasOwnProperty',\n 'toString',\n 'valueOf',\n '__defineGetter__',\n '__defineSetter__',\n '__lookupGetter__',\n '__lookupSetter__'\n];\n\nexport const criticalProperties = [\"__proto__\", \"constructor\", \"prototype\"];","import { DANGEROUS_PROPERTY_NAMES, criticalProperties } from \"../util.js\";\nimport { COMMON_HTML, CURRENCY } from '@nodable/entities';\n\nconst defaultOnDangerousProperty = (name) => {\n if (DANGEROUS_PROPERTY_NAMES.includes(name)) {\n return \"__\" + name;\n }\n return name;\n};\n\n\nexport const defaultOptions = {\n preserveOrder: false,\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n removeNSPrefix: false, // remove NS from tag name or attribute name if true\n allowBooleanAttributes: false, //a tag can have attributes without any value\n //ignoreRootElement : false,\n parseTagValue: true,\n parseAttributeValue: false,\n trimValues: true, //Trim string values of tag and attributes\n cdataPropName: false,\n numberParseOptions: {\n hex: true,\n leadingZeros: true,\n eNotation: true\n },\n tagValueProcessor: function (tagName, val) {\n return val;\n },\n attributeValueProcessor: function (attrName, val) {\n return val;\n },\n stopNodes: [], //nested tags will not be parsed even for errors\n alwaysCreateTextNode: false,\n isArray: () => false,\n commentPropName: false,\n unpairedTags: [],\n processEntities: true,\n htmlEntities: false,\n entityDecoder: null,\n ignoreDeclaration: false,\n ignorePiTags: false,\n transformTagName: false,\n transformAttributeName: false,\n updateTag: function (tagName, jPath, attrs) {\n return tagName\n },\n // skipEmptyListItem: false\n captureMetaData: false,\n maxNestedTags: 100,\n strictReservedNames: true,\n jPath: true, // if true, pass jPath string to callbacks; if false, pass matcher instance\n onDangerousProperty: defaultOnDangerousProperty\n};\n\n\n/**\n * Validates that a property name is safe to use\n * @param {string} propertyName - The property name to validate\n * @param {string} optionName - The option field name (for error message)\n * @throws {Error} If property name is dangerous\n */\nfunction validatePropertyName(propertyName, optionName) {\n if (typeof propertyName !== 'string') {\n return; // Only validate string property names\n }\n\n const normalized = propertyName.toLowerCase();\n if (DANGEROUS_PROPERTY_NAMES.some(dangerous => normalized === dangerous.toLowerCase())) {\n throw new Error(\n `[SECURITY] Invalid ${optionName}: \"${propertyName}\" is a reserved JavaScript keyword that could cause prototype pollution`\n );\n }\n\n if (criticalProperties.some(dangerous => normalized === dangerous.toLowerCase())) {\n throw new Error(\n `[SECURITY] Invalid ${optionName}: \"${propertyName}\" is a reserved JavaScript keyword that could cause prototype pollution`\n );\n }\n}\n\n/**\n * Normalizes processEntities option for backward compatibility\n * @param {boolean|object} value \n * @returns {object} Always returns normalized object\n */\nfunction normalizeProcessEntities(value, htmlEntities) {\n // Boolean backward compatibility\n if (typeof value === 'boolean') {\n return {\n enabled: value, // true or false\n maxEntitySize: 10000,\n maxExpansionDepth: 10000,\n maxTotalExpansions: Infinity,\n maxExpandedLength: 100000,\n maxEntityCount: 1000,\n allowedTags: null,\n tagFilter: null,\n appliesTo: \"all\",\n };\n }\n\n // Object config - merge with defaults\n if (typeof value === 'object' && value !== null) {\n return {\n enabled: value.enabled !== false,\n maxEntitySize: Math.max(1, value.maxEntitySize ?? 10000),\n maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 10000),\n maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity),\n maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 100000),\n maxEntityCount: Math.max(1, value.maxEntityCount ?? 1000),\n allowedTags: value.allowedTags ?? null,\n tagFilter: value.tagFilter ?? null,\n appliesTo: value.appliesTo ?? \"all\",\n };\n }\n\n // Default to enabled with limits\n return normalizeProcessEntities(true);\n}\n\nexport const buildOptions = function (options) {\n const built = Object.assign({}, defaultOptions, options);\n\n // Validate property names to prevent prototype pollution\n const propertyNameOptions = [\n { value: built.attributeNamePrefix, name: 'attributeNamePrefix' },\n { value: built.attributesGroupName, name: 'attributesGroupName' },\n { value: built.textNodeName, name: 'textNodeName' },\n { value: built.cdataPropName, name: 'cdataPropName' },\n { value: built.commentPropName, name: 'commentPropName' }\n ];\n\n for (const { value, name } of propertyNameOptions) {\n if (value) {\n validatePropertyName(value, name);\n }\n }\n\n if (built.onDangerousProperty === null) {\n built.onDangerousProperty = defaultOnDangerousProperty;\n }\n\n // Always normalize processEntities for backward compatibility and validation\n built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities);\n built.unpairedTagsSet = new Set(built.unpairedTags);\n // Convert old-style stopNodes for backward compatibility\n if (built.stopNodes && Array.isArray(built.stopNodes)) {\n built.stopNodes = built.stopNodes.map(node => {\n if (typeof node === 'string' && node.startsWith('*.')) {\n // Old syntax: *.tagname meant \"tagname anywhere\"\n // Convert to new syntax: ..tagname\n return '..' + node.substring(2);\n }\n return node;\n });\n }\n //console.debug(built.processEntities)\n return built;\n};","'use strict';\n\nlet METADATA_SYMBOL;\n\nif (typeof Symbol !== \"function\") {\n METADATA_SYMBOL = \"@@xmlMetadata\";\n} else {\n METADATA_SYMBOL = Symbol(\"XML Node Metadata\");\n}\n\nexport default class XmlNode {\n constructor(tagname) {\n this.tagname = tagname;\n this.child = []; //nested tags, text, cdata, comments in order\n this[\":@\"] = Object.create(null); //attributes map\n }\n add(key, val) {\n // this.child.push( {name : key, val: val, isCdata: isCdata });\n if (key === \"__proto__\") key = \"#__proto__\";\n this.child.push({ [key]: val });\n }\n addChild(node, startIndex) {\n if (node.tagname === \"__proto__\") node.tagname = \"#__proto__\";\n if (node[\":@\"] && Object.keys(node[\":@\"]).length > 0) {\n this.child.push({ [node.tagname]: node.child, [\":@\"]: node[\":@\"] });\n } else {\n this.child.push({ [node.tagname]: node.child });\n }\n // if requested, add the startIndex\n if (startIndex !== undefined) {\n // Note: for now we just overwrite the metadata. If we had more complex metadata,\n // we might need to do an object append here: metadata = { ...metadata, startIndex }\n this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex };\n }\n }\n /** symbol used for metadata */\n static getMetaDataSymbol() {\n return METADATA_SYMBOL;\n }\n}\n","import { isName } from '../util.js';\n\nexport default class DocTypeReader {\n constructor(options) {\n this.suppressValidationErr = !options;\n this.options = options;\n }\n\n readDocType(xmlData, i) {\n const entities = Object.create(null);\n let entityCount = 0;\n\n if (xmlData[i + 3] === 'O' &&\n xmlData[i + 4] === 'C' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'Y' &&\n xmlData[i + 7] === 'P' &&\n xmlData[i + 8] === 'E') {\n i = i + 9;\n let angleBracketsCount = 1;\n let hasBody = false, comment = false;\n let exp = \"\";\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === '<' && !comment) { //Determine the tag type\n if (hasBody && hasSeq(xmlData, \"!ENTITY\", i)) {\n i += 7;\n let entityName, val;\n [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr);\n if (val.indexOf(\"&\") === -1) { //Parameter entities are not supported\n if (this.options.enabled !== false &&\n this.options.maxEntityCount != null &&\n entityCount >= this.options.maxEntityCount) {\n throw new Error(\n `Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`\n );\n }\n //const escaped = entityName.replace(/[.\\-+*:]/g, '\\\\.');\n //const escaped = entityName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n entities[entityName] = val;\n entityCount++;\n }\n }\n else if (hasBody && hasSeq(xmlData, \"!ELEMENT\", i)) {\n i += 8;//Not supported\n const { index } = this.readElementExp(xmlData, i + 1);\n i = index;\n } else if (hasBody && hasSeq(xmlData, \"!ATTLIST\", i)) {\n i += 8;//Not supported\n // const {index} = this.readAttlistExp(xmlData,i+1);\n // i = index;\n } else if (hasBody && hasSeq(xmlData, \"!NOTATION\", i)) {\n i += 9;//Not supported\n const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr);\n i = index;\n } else if (hasSeq(xmlData, \"!--\", i)) comment = true;\n else throw new Error(`Invalid DOCTYPE`);\n\n angleBracketsCount++;\n exp = \"\";\n } else if (xmlData[i] === '>') { //Read tag content\n if (comment) {\n if (xmlData[i - 1] === \"-\" && xmlData[i - 2] === \"-\") {\n comment = false;\n angleBracketsCount--;\n }\n } else {\n angleBracketsCount--;\n }\n if (angleBracketsCount === 0) {\n break;\n }\n } else if (xmlData[i] === '[') {\n hasBody = true;\n } else {\n exp += xmlData[i];\n }\n }\n if (angleBracketsCount !== 0) {\n throw new Error(`Unclosed DOCTYPE`);\n }\n } else {\n throw new Error(`Invalid Tag instead of DOCTYPE`);\n }\n return { entities, i };\n }\n readEntityExp(xmlData, i) {\n //External entities are not supported\n // \n\n //Parameter entities are not supported\n // \n\n //Internal entities are supported\n // \n\n // Skip leading whitespace after this.options.maxEntitySize) {\n throw new Error(\n `Entity \"${entityName}\" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`\n );\n }\n\n i--;\n return [entityName, entityValue, i];\n }\n\n readNotationExp(xmlData, i) {\n // Skip leading whitespace after \n // \n // \n // \n // \n\n // Skip leading whitespace after {\n while (index < data.length && /\\s/.test(data[index])) {\n index++;\n }\n return index;\n};\n\n\n\nfunction hasSeq(data, seq, i) {\n for (let j = 0; j < seq.length; j++) {\n if (seq[j] !== data[i + j + 1]) return false;\n }\n return true;\n}\n\nfunction validateEntityName(name) {\n if (isName(name))\n return name;\n else\n throw new Error(`Invalid entity name ${name}`);\n}","const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;\nconst numRegex = /^([\\-\\+])?(0*)([0-9]*(\\.[0-9]*)?)$/;\n// const octRegex = /^0x[a-z0-9]+/;\n// const binRegex = /0x[a-z0-9]+/;\n\n\nconst consider = {\n hex: true,\n // oct: false,\n leadingZeros: true,\n decimalPoint: \"\\.\",\n eNotation: true,\n //skipLike: /regex/,\n infinity: \"original\", // \"null\", \"infinity\" (Infinity type), \"string\" (\"Infinity\" (the string literal))\n};\n\nexport default function toNumber(str, options = {}) {\n options = Object.assign({}, consider, options);\n if (!str || typeof str !== \"string\") return str;\n\n let trimmedStr = str.trim();\n\n if (trimmedStr.length === 0) return str;\n else if (options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;\n else if (trimmedStr === \"0\") return 0;\n else if (options.hex && hexRegex.test(trimmedStr)) {\n return parse_int(trimmedStr, 16);\n // }else if (options.oct && octRegex.test(str)) {\n // return Number.parseInt(val, 8);\n } else if (!isFinite(trimmedStr)) { //Infinity\n return handleInfinity(str, Number(trimmedStr), options);\n } else if (trimmedStr.includes('e') || trimmedStr.includes('E')) { //eNotation\n return resolveEnotation(str, trimmedStr, options);\n // }else if (options.parseBin && binRegex.test(str)) {\n // return Number.parseInt(val, 2);\n } else {\n //separate negative sign, leading zeros, and rest number\n const match = numRegex.exec(trimmedStr);\n // +00.123 => [ , '+', '00', '.123', ..\n if (match) {\n const sign = match[1] || \"\";\n const leadingZeros = match[2];\n let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros\n const decimalAdjacentToLeadingZeros = sign ? // 0., -00., 000.\n str[leadingZeros.length + 1] === \".\"\n : str[leadingZeros.length] === \".\";\n\n //trim ending zeros for floating number\n if (!options.leadingZeros //leading zeros are not allowed\n && (leadingZeros.length > 1\n || (leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros))) {\n // 00, 00.3, +03.24, 03, 03.24\n return str;\n }\n else {//no leading zeros or leading zeros are allowed\n const num = Number(trimmedStr);\n const parsedStr = String(num);\n\n if (num === 0) return num;\n if (parsedStr.search(/[eE]/) !== -1) { //given number is long and parsed to eNotation\n if (options.eNotation) return num;\n else return str;\n } else if (trimmedStr.indexOf(\".\") !== -1) { //floating number\n if (parsedStr === \"0\") return num; //0.0\n else if (parsedStr === numTrimmedByZeros) return num; //0.456. 0.79000\n else if (parsedStr === `${sign}${numTrimmedByZeros}`) return num;\n else return str;\n }\n\n let n = leadingZeros ? numTrimmedByZeros : trimmedStr;\n if (leadingZeros) {\n // -009 => -9\n return (n === parsedStr) || (sign + n === parsedStr) ? num : str\n } else {\n // +9\n return (n === parsedStr) || (n === sign + parsedStr) ? num : str\n }\n }\n } else { //non-numeric string\n return str;\n }\n }\n}\n\nconst eNotationRegx = /^([-+])?(0*)(\\d*(\\.\\d*)?[eE][-\\+]?\\d+)$/;\nfunction resolveEnotation(str, trimmedStr, options) {\n if (!options.eNotation) return str;\n const notation = trimmedStr.match(eNotationRegx);\n if (notation) {\n let sign = notation[1] || \"\";\n const eChar = notation[3].indexOf(\"e\") === -1 ? \"E\" : \"e\";\n const leadingZeros = notation[2];\n const eAdjacentToLeadingZeros = sign ? // 0E.\n str[leadingZeros.length + 1] === eChar\n : str[leadingZeros.length] === eChar;\n\n if (leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str;\n else if (leadingZeros.length === 1\n && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)) {\n return Number(trimmedStr);\n } else if (leadingZeros.length > 0) {\n // Has leading zeros — only accept if leadingZeros option allows it\n if (options.leadingZeros && !eAdjacentToLeadingZeros) {\n trimmedStr = (notation[1] || \"\") + notation[3];\n return Number(trimmedStr);\n } else return str;\n } else {\n // No leading zeros — always valid e-notation, parse it\n return Number(trimmedStr);\n }\n } else {\n return str;\n }\n}\n\n/**\n * \n * @param {string} numStr without leading zeros\n * @returns \n */\nfunction trimZeros(numStr) {\n if (numStr && numStr.indexOf(\".\") !== -1) {//float\n numStr = numStr.replace(/0+$/, \"\"); //remove ending zeros\n if (numStr === \".\") numStr = \"0\";\n else if (numStr[0] === \".\") numStr = \"0\" + numStr;\n else if (numStr[numStr.length - 1] === \".\") numStr = numStr.substring(0, numStr.length - 1);\n return numStr;\n }\n return numStr;\n}\n\nfunction parse_int(numStr, base) {\n //polyfill\n if (parseInt) return parseInt(numStr, base);\n else if (Number.parseInt) return Number.parseInt(numStr, base);\n else if (window && window.parseInt) return window.parseInt(numStr, base);\n else throw new Error(\"parseInt, Number.parseInt, window.parseInt are not supported\")\n}\n\n/**\n * Handle infinite values based on user option\n * @param {string} str - original input string\n * @param {number} num - parsed number (Infinity or -Infinity)\n * @param {object} options - user options\n * @returns {string|number|null} based on infinity option\n */\nfunction handleInfinity(str, num, options) {\n const isPositive = num === Infinity;\n\n switch (options.infinity.toLowerCase()) {\n case \"null\":\n return null;\n case \"infinity\":\n return num; // Return Infinity or -Infinity\n case \"string\":\n return isPositive ? \"Infinity\" : \"-Infinity\";\n case \"original\":\n default:\n return str; // Return original string like \"1e1000\"\n }\n}","import ExpressionSet from \"./ExpressionSet.js\";\n\n/**\n * MatcherView - A lightweight read-only view over a Matcher's internal state.\n *\n * Created once by Matcher and reused across all callbacks. Holds a direct\n * reference to the parent Matcher so it always reflects current parser state\n * with zero copying or freezing overhead.\n *\n * Users receive this via {@link Matcher#readOnly} or directly from parser\n * callbacks. It exposes all query and matching methods but has no mutation\n * methods — misuse is caught at the TypeScript level rather than at runtime.\n *\n * @example\n * const matcher = new Matcher();\n * const view = matcher.readOnly();\n *\n * matcher.push(\"root\", {});\n * view.getCurrentTag(); // \"root\"\n * view.getDepth(); // 1\n */\nexport class MatcherView {\n /**\n * @param {Matcher} matcher - The parent Matcher instance to read from.\n */\n constructor(matcher) {\n this._matcher = matcher;\n }\n\n /**\n * Get the path separator used by the parent matcher.\n * @returns {string}\n */\n get separator() {\n return this._matcher.separator;\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return undefined;\n return path[path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return false;\n const current = path[path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this._matcher.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n return this._matcher.toString(separator, includeNamespace);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this._matcher.path.map(n => n.tag);\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n return this._matcher.matches(expression);\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this._matcher);\n }\n}\n\n/**\n * Matcher - Tracks current path in XML/JSON tree and matches against Expressions.\n *\n * The matcher maintains a stack of nodes representing the current path from root to\n * current tag. It only stores attribute values for the current (top) node to minimize\n * memory usage. Sibling tracking is used to auto-calculate position and counter.\n *\n * Use {@link Matcher#readOnly} to obtain a {@link MatcherView} safe to pass to\n * user callbacks — it always reflects current state with no Proxy overhead.\n *\n * @example\n * const matcher = new Matcher();\n * matcher.push(\"root\", {});\n * matcher.push(\"users\", {});\n * matcher.push(\"user\", { id: \"123\", type: \"admin\" });\n *\n * const expr = new Expression(\"root.users.user\");\n * matcher.matches(expr); // true\n */\nexport default class Matcher {\n /**\n * Create a new Matcher.\n * @param {Object} [options={}]\n * @param {string} [options.separator='.'] - Default path separator\n */\n constructor(options = {}) {\n this.separator = options.separator || '.';\n this.path = [];\n this.siblingStacks = [];\n // Each path node: { tag, values, position, counter, namespace? }\n // values only present for current (last) node\n // Each siblingStacks entry: Map tracking occurrences at each level\n this._pathStringCache = null;\n this._view = new MatcherView(this);\n }\n\n /**\n * Push a new tag onto the path.\n * @param {string} tagName\n * @param {Object|null} [attrValues=null]\n * @param {string|null} [namespace=null]\n */\n push(tagName, attrValues = null, namespace = null) {\n this._pathStringCache = null;\n\n // Remove values from previous current node (now becoming ancestor)\n if (this.path.length > 0) {\n this.path[this.path.length - 1].values = undefined;\n }\n\n // Get or create sibling tracking for current level\n const currentLevel = this.path.length;\n if (!this.siblingStacks[currentLevel]) {\n this.siblingStacks[currentLevel] = new Map();\n }\n\n const siblings = this.siblingStacks[currentLevel];\n\n // Create a unique key for sibling tracking that includes namespace\n const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;\n\n // Calculate counter (how many times this tag appeared at this level)\n const counter = siblings.get(siblingKey) || 0;\n\n // Calculate position (total children at this level so far)\n let position = 0;\n for (const count of siblings.values()) {\n position += count;\n }\n\n // Update sibling count for this tag\n siblings.set(siblingKey, counter + 1);\n\n // Create new node\n const node = {\n tag: tagName,\n position: position,\n counter: counter\n };\n\n if (namespace !== null && namespace !== undefined) {\n node.namespace = namespace;\n }\n\n if (attrValues !== null && attrValues !== undefined) {\n node.values = attrValues;\n }\n\n this.path.push(node);\n }\n\n /**\n * Pop the last tag from the path.\n * @returns {Object|undefined} The popped node\n */\n pop() {\n if (this.path.length === 0) return undefined;\n this._pathStringCache = null;\n\n const node = this.path.pop();\n\n if (this.siblingStacks.length > this.path.length + 1) {\n this.siblingStacks.length = this.path.length + 1;\n }\n\n return node;\n }\n\n /**\n * Update current node's attribute values.\n * Useful when attributes are parsed after push.\n * @param {Object} attrValues\n */\n updateCurrent(attrValues) {\n if (this.path.length > 0) {\n const current = this.path[this.path.length - 1];\n if (attrValues !== null && attrValues !== undefined) {\n current.values = attrValues;\n }\n }\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n return this.path.length > 0 ? this.path[this.path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n return this.path.length > 0 ? this.path[this.path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n if (this.path.length === 0) return undefined;\n return this.path[this.path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n if (this.path.length === 0) return false;\n const current = this.path[this.path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n const sep = separator || this.separator;\n const isDefault = (sep === this.separator && includeNamespace === true);\n\n if (isDefault) {\n if (this._pathStringCache !== null) {\n return this._pathStringCache;\n }\n const result = this.path.map(n =>\n (n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n this._pathStringCache = result;\n return result;\n }\n\n return this.path.map(n =>\n (includeNamespace && n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this.path.map(n => n.tag);\n }\n\n /**\n * Reset the path to empty.\n */\n reset() {\n this._pathStringCache = null;\n this.path = [];\n this.siblingStacks = [];\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n const segments = expression.segments;\n\n if (segments.length === 0) {\n return false;\n }\n\n if (expression.hasDeepWildcard()) {\n return this._matchWithDeepWildcard(segments);\n }\n\n return this._matchSimple(segments);\n }\n\n /**\n * @private\n */\n _matchSimple(segments) {\n if (this.path.length !== segments.length) {\n return false;\n }\n\n for (let i = 0; i < segments.length; i++) {\n if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * @private\n */\n _matchWithDeepWildcard(segments) {\n let pathIdx = this.path.length - 1;\n let segIdx = segments.length - 1;\n\n while (segIdx >= 0 && pathIdx >= 0) {\n const segment = segments[segIdx];\n\n if (segment.type === 'deep-wildcard') {\n segIdx--;\n\n if (segIdx < 0) {\n return true;\n }\n\n const nextSeg = segments[segIdx];\n let found = false;\n\n for (let i = pathIdx; i >= 0; i--) {\n if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) {\n pathIdx = i - 1;\n segIdx--;\n found = true;\n break;\n }\n }\n\n if (!found) {\n return false;\n }\n } else {\n if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) {\n return false;\n }\n pathIdx--;\n segIdx--;\n }\n }\n\n return segIdx < 0;\n }\n\n /**\n * @private\n */\n _matchSegment(segment, node, isCurrentNode) {\n if (segment.tag !== '*' && segment.tag !== node.tag) {\n return false;\n }\n\n if (segment.namespace !== undefined) {\n if (segment.namespace !== '*' && segment.namespace !== node.namespace) {\n return false;\n }\n }\n\n if (segment.attrName !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n if (!node.values || !(segment.attrName in node.values)) {\n return false;\n }\n\n if (segment.attrValue !== undefined) {\n if (String(node.values[segment.attrName]) !== String(segment.attrValue)) {\n return false;\n }\n }\n }\n\n if (segment.position !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n const counter = node.counter ?? 0;\n\n if (segment.position === 'first' && counter !== 0) {\n return false;\n } else if (segment.position === 'odd' && counter % 2 !== 1) {\n return false;\n } else if (segment.position === 'even' && counter % 2 !== 0) {\n return false;\n } else if (segment.position === 'nth' && counter !== segment.positionValue) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this);\n }\n\n /**\n * Create a snapshot of current state.\n * @returns {Object}\n */\n snapshot() {\n return {\n path: this.path.map(node => ({ ...node })),\n siblingStacks: this.siblingStacks.map(map => new Map(map))\n };\n }\n\n /**\n * Restore state from snapshot.\n * @param {Object} snapshot\n */\n restore(snapshot) {\n this._pathStringCache = null;\n this.path = snapshot.path.map(node => ({ ...node }));\n this.siblingStacks = snapshot.siblingStacks.map(map => new Map(map));\n }\n\n /**\n * Return the read-only {@link MatcherView} for this matcher.\n *\n * The same instance is returned on every call — no allocation occurs.\n * It always reflects the current parser state and is safe to pass to\n * user callbacks without risk of accidental mutation.\n *\n * @returns {MatcherView}\n *\n * @example\n * const view = matcher.readOnly();\n * // pass view to callbacks — it stays in sync automatically\n * view.matches(expr); // ✓\n * view.getCurrentTag(); // ✓\n * // view.push(...) // ✗ method does not exist — caught by TypeScript\n */\n readOnly() {\n return this._view;\n }\n}","/**\n * Expression - Parses and stores a tag pattern expression\n * \n * Patterns are parsed once and stored in an optimized structure for fast matching.\n * \n * @example\n * const expr = new Expression(\"root.users.user\");\n * const expr2 = new Expression(\"..user[id]:first\");\n * const expr3 = new Expression(\"root/users/user\", { separator: '/' });\n */\nexport default class Expression {\n /**\n * Create a new Expression\n * @param {string} pattern - Pattern string (e.g., \"root.users.user\", \"..user[id]\")\n * @param {Object} options - Configuration options\n * @param {string} options.separator - Path separator (default: '.')\n */\n constructor(pattern, options = {}, data) {\n this.pattern = pattern;\n this.separator = options.separator || '.';\n this.segments = this._parse(pattern);\n this.data = data;\n // Cache expensive checks for performance (O(1) instead of O(n))\n this._hasDeepWildcard = this.segments.some(seg => seg.type === 'deep-wildcard');\n this._hasAttributeCondition = this.segments.some(seg => seg.attrName !== undefined);\n this._hasPositionSelector = this.segments.some(seg => seg.position !== undefined);\n }\n\n /**\n * Parse pattern string into segments\n * @private\n * @param {string} pattern - Pattern to parse\n * @returns {Array} Array of segment objects\n */\n _parse(pattern) {\n const segments = [];\n\n // Split by separator but handle \"..\" specially\n let i = 0;\n let currentPart = '';\n\n while (i < pattern.length) {\n if (pattern[i] === this.separator) {\n // Check if next char is also separator (deep wildcard)\n if (i + 1 < pattern.length && pattern[i + 1] === this.separator) {\n // Flush current part if any\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n currentPart = '';\n }\n // Add deep wildcard\n segments.push({ type: 'deep-wildcard' });\n i += 2; // Skip both separators\n } else {\n // Regular separator\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n currentPart = '';\n i++;\n }\n } else {\n currentPart += pattern[i];\n i++;\n }\n }\n\n // Flush remaining part\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n\n return segments;\n }\n\n /**\n * Parse a single segment\n * @private\n * @param {string} part - Segment string (e.g., \"user\", \"ns::user\", \"user[id]\", \"ns::user:first\")\n * @returns {Object} Segment object\n */\n _parseSegment(part) {\n const segment = { type: 'tag' };\n\n // NEW NAMESPACE SYNTAX (v2.0):\n // ============================\n // Namespace uses DOUBLE colon (::)\n // Position uses SINGLE colon (:)\n // \n // Examples:\n // \"user\" → tag\n // \"user:first\" → tag + position\n // \"user[id]\" → tag + attribute\n // \"user[id]:first\" → tag + attribute + position\n // \"ns::user\" → namespace + tag\n // \"ns::user:first\" → namespace + tag + position\n // \"ns::user[id]\" → namespace + tag + attribute\n // \"ns::user[id]:first\" → namespace + tag + attribute + position\n // \"ns::first\" → namespace + tag named \"first\" (NO ambiguity!)\n //\n // This eliminates all ambiguity:\n // :: = namespace separator\n // : = position selector\n // [] = attributes\n\n // Step 1: Extract brackets [attr] or [attr=value]\n let bracketContent = null;\n let withoutBrackets = part;\n\n const bracketMatch = part.match(/^([^\\[]+)(\\[[^\\]]*\\])(.*)$/);\n if (bracketMatch) {\n withoutBrackets = bracketMatch[1] + bracketMatch[3];\n if (bracketMatch[2]) {\n const content = bracketMatch[2].slice(1, -1);\n if (content) {\n bracketContent = content;\n }\n }\n }\n\n // Step 2: Check for namespace (double colon ::)\n let namespace = undefined;\n let tagAndPosition = withoutBrackets;\n\n if (withoutBrackets.includes('::')) {\n const nsIndex = withoutBrackets.indexOf('::');\n namespace = withoutBrackets.substring(0, nsIndex).trim();\n tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim(); // Skip ::\n\n if (!namespace) {\n throw new Error(`Invalid namespace in pattern: ${part}`);\n }\n }\n\n // Step 3: Parse tag and position (single colon :)\n let tag = undefined;\n let positionMatch = null;\n\n if (tagAndPosition.includes(':')) {\n const colonIndex = tagAndPosition.lastIndexOf(':'); // Use last colon for position\n const tagPart = tagAndPosition.substring(0, colonIndex).trim();\n const posPart = tagAndPosition.substring(colonIndex + 1).trim();\n\n // Verify position is a valid keyword\n const isPositionKeyword = ['first', 'last', 'odd', 'even'].includes(posPart) ||\n /^nth\\(\\d+\\)$/.test(posPart);\n\n if (isPositionKeyword) {\n tag = tagPart;\n positionMatch = posPart;\n } else {\n // Not a valid position keyword, treat whole thing as tag\n tag = tagAndPosition;\n }\n } else {\n tag = tagAndPosition;\n }\n\n if (!tag) {\n throw new Error(`Invalid segment pattern: ${part}`);\n }\n\n segment.tag = tag;\n if (namespace) {\n segment.namespace = namespace;\n }\n\n // Step 4: Parse attributes\n if (bracketContent) {\n if (bracketContent.includes('=')) {\n const eqIndex = bracketContent.indexOf('=');\n segment.attrName = bracketContent.substring(0, eqIndex).trim();\n segment.attrValue = bracketContent.substring(eqIndex + 1).trim();\n } else {\n segment.attrName = bracketContent.trim();\n }\n }\n\n // Step 5: Parse position selector\n if (positionMatch) {\n const nthMatch = positionMatch.match(/^nth\\((\\d+)\\)$/);\n if (nthMatch) {\n segment.position = 'nth';\n segment.positionValue = parseInt(nthMatch[1], 10);\n } else {\n segment.position = positionMatch;\n }\n }\n\n return segment;\n }\n\n /**\n * Get the number of segments\n * @returns {number}\n */\n get length() {\n return this.segments.length;\n }\n\n /**\n * Check if expression contains deep wildcard\n * @returns {boolean}\n */\n hasDeepWildcard() {\n return this._hasDeepWildcard;\n }\n\n /**\n * Check if expression has attribute conditions\n * @returns {boolean}\n */\n hasAttributeCondition() {\n return this._hasAttributeCondition;\n }\n\n /**\n * Check if expression has position selectors\n * @returns {boolean}\n */\n hasPositionSelector() {\n return this._hasPositionSelector;\n }\n\n /**\n * Get string representation\n * @returns {string}\n */\n toString() {\n return this.pattern;\n }\n}","/**\n * ExpressionSet - An indexed collection of Expressions for efficient bulk matching\n *\n * Instead of iterating all expressions on every tag, ExpressionSet pre-indexes\n * them at insertion time by depth and terminal tag name. At match time, only\n * the relevant bucket is evaluated — typically reducing checks from O(E) to O(1)\n * lookup plus O(small bucket) matches.\n *\n * Three buckets are maintained:\n * - `_byDepthAndTag` — exact depth + exact tag name (tightest, used first)\n * - `_wildcardByDepth` — exact depth + wildcard tag `*` (depth-matched only)\n * - `_deepWildcards` — expressions containing `..` (cannot be depth-indexed)\n *\n * @example\n * import { Expression, ExpressionSet } from 'fast-xml-tagger';\n *\n * // Build once at config time\n * const stopNodes = new ExpressionSet();\n * stopNodes.add(new Expression('root.users.user'));\n * stopNodes.add(new Expression('root.config.setting'));\n * stopNodes.add(new Expression('..script'));\n *\n * // Query on every tag — hot path\n * if (stopNodes.matchesAny(matcher)) { ... }\n */\nexport default class ExpressionSet {\n constructor() {\n /** @type {Map} depth:tag → expressions */\n this._byDepthAndTag = new Map();\n\n /** @type {Map} depth → wildcard-tag expressions */\n this._wildcardByDepth = new Map();\n\n /** @type {import('./Expression.js').default[]} expressions containing deep wildcard (..) */\n this._deepWildcards = [];\n\n /** @type {Set} pattern strings already added — used for deduplication */\n this._patterns = new Set();\n\n /** @type {boolean} whether the set is sealed against further additions */\n this._sealed = false;\n }\n\n /**\n * Add an Expression to the set.\n * Duplicate patterns (same pattern string) are silently ignored.\n *\n * @param {import('./Expression.js').default} expression - A pre-constructed Expression instance\n * @returns {this} for chaining\n * @throws {TypeError} if called after seal()\n *\n * @example\n * set.add(new Expression('root.users.user'));\n * set.add(new Expression('..script'));\n */\n add(expression) {\n if (this._sealed) {\n throw new TypeError(\n 'ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.'\n );\n }\n\n // Deduplicate by pattern string\n if (this._patterns.has(expression.pattern)) return this;\n this._patterns.add(expression.pattern);\n\n if (expression.hasDeepWildcard()) {\n this._deepWildcards.push(expression);\n return this;\n }\n\n const depth = expression.length;\n const lastSeg = expression.segments[expression.segments.length - 1];\n const tag = lastSeg?.tag;\n\n if (!tag || tag === '*') {\n // Can index by depth but not by tag\n if (!this._wildcardByDepth.has(depth)) this._wildcardByDepth.set(depth, []);\n this._wildcardByDepth.get(depth).push(expression);\n } else {\n // Tightest bucket: depth + tag\n const key = `${depth}:${tag}`;\n if (!this._byDepthAndTag.has(key)) this._byDepthAndTag.set(key, []);\n this._byDepthAndTag.get(key).push(expression);\n }\n\n return this;\n }\n\n /**\n * Add multiple expressions at once.\n *\n * @param {import('./Expression.js').default[]} expressions - Array of Expression instances\n * @returns {this} for chaining\n *\n * @example\n * set.addAll([\n * new Expression('root.users.user'),\n * new Expression('root.config.setting'),\n * ]);\n */\n addAll(expressions) {\n for (const expr of expressions) this.add(expr);\n return this;\n }\n\n /**\n * Check whether a pattern string is already present in the set.\n *\n * @param {import('./Expression.js').default} expression\n * @returns {boolean}\n */\n has(expression) {\n return this._patterns.has(expression.pattern);\n }\n\n /**\n * Number of expressions in the set.\n * @type {number}\n */\n get size() {\n return this._patterns.size;\n }\n\n /**\n * Seal the set against further modifications.\n * Useful to prevent accidental mutations after config is built.\n * Calling add() or addAll() on a sealed set throws a TypeError.\n *\n * @returns {this}\n */\n seal() {\n this._sealed = true;\n return this;\n }\n\n /**\n * Whether the set has been sealed.\n * @type {boolean}\n */\n get isSealed() {\n return this._sealed;\n }\n\n /**\n * Test whether the matcher's current path matches any expression in the set.\n *\n * Evaluation order (cheapest → most expensive):\n * 1. Exact depth + tag bucket — O(1) lookup, typically 0–2 expressions\n * 2. Depth-only wildcard bucket — O(1) lookup, rare\n * 3. Deep-wildcard list — always checked, but usually small\n *\n * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)\n * @returns {boolean} true if any expression matches the current path\n *\n * @example\n * if (stopNodes.matchesAny(matcher)) {\n * // handle stop node\n * }\n */\n matchesAny(matcher) {\n return this.findMatch(matcher) !== null;\n }\n /**\n * Find and return the first Expression that matches the matcher's current path.\n *\n * Uses the same evaluation order as matchesAny (cheapest → most expensive):\n * 1. Exact depth + tag bucket\n * 2. Depth-only wildcard bucket\n * 3. Deep-wildcard list\n *\n * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)\n * @returns {import('./Expression.js').default | null} the first matching Expression, or null\n *\n * @example\n * const expr = stopNodes.findMatch(matcher);\n * if (expr) {\n * // access expr.config, expr.pattern, etc.\n * }\n */\n findMatch(matcher) {\n const depth = matcher.getDepth();\n const tag = matcher.getCurrentTag();\n\n // 1. Tightest bucket — most expressions live here\n const exactKey = `${depth}:${tag}`;\n const exactBucket = this._byDepthAndTag.get(exactKey);\n if (exactBucket) {\n for (let i = 0; i < exactBucket.length; i++) {\n if (matcher.matches(exactBucket[i])) return exactBucket[i];\n }\n }\n\n // 2. Depth-matched wildcard-tag expressions\n const wildcardBucket = this._wildcardByDepth.get(depth);\n if (wildcardBucket) {\n for (let i = 0; i < wildcardBucket.length; i++) {\n if (matcher.matches(wildcardBucket[i])) return wildcardBucket[i];\n }\n }\n\n // 3. Deep wildcards — cannot be pre-filtered by depth or tag\n for (let i = 0; i < this._deepWildcards.length; i++) {\n if (matcher.matches(this._deepWildcards[i])) return this._deepWildcards[i];\n }\n\n return null;\n }\n}\n","// ---------------------------------------------------------------------------\n// Complete HTML5 named entity reference\n// Organized by logical categories for easy maintenance and selective importing\n// ---------------------------------------------------------------------------\n\n/**\n * Basic Latin & Special Characters\n * @type {Record}\n */\nexport const BASIC_LATIN = {\n amp: '&',\n AMP: '&',\n lt: '<',\n LT: '<',\n gt: '>',\n GT: '>',\n quot: '\"',\n QUOT: '\"',\n apos: \"'\",\n lsquo: '‘',\n rsquo: '’',\n ldquo: '“',\n rdquo: '”',\n lsquor: '‚',\n rsquor: '’',\n ldquor: '„',\n bdquo: '„',\n comma: ',',\n period: '.',\n colon: ':',\n semi: ';',\n excl: '!',\n quest: '?',\n num: '#',\n dollar: '$',\n percent: '%',\n amp: '&',\n ast: '*',\n commat: '@',\n lowbar: '_',\n verbar: '|',\n vert: '|',\n sol: '/',\n bsol: '\\\\',\n lbrace: '{',\n rbrace: '}',\n lbrack: '[',\n rbrack: ']',\n lpar: '(',\n rpar: ')',\n nbsp: '\\u00a0',\n iexcl: '¡',\n cent: '¢',\n pound: '£',\n curren: '¤',\n yen: '¥',\n brvbar: '¦',\n sect: '§',\n uml: '¨',\n copy: '©',\n COPY: '©',\n ordf: 'ª',\n laquo: '«',\n not: '¬',\n shy: '\\u00ad',\n reg: '®',\n REG: '®',\n macr: '¯',\n deg: '°',\n plusmn: '±',\n sup2: '²',\n sup3: '³',\n acute: '´',\n micro: 'µ',\n para: '¶',\n middot: '·',\n cedil: '¸',\n sup1: '¹',\n ordm: 'º',\n raquo: '»',\n frac14: '¼',\n frac12: '½',\n half: '½',\n frac34: '¾',\n iquest: '¿',\n times: '×',\n div: '÷',\n divide: '÷',\n};\n\n/**\n * Latin Extended & Accented Letters (A-Z)\n * @type {Record}\n */\nexport const LATIN_ACCENTS = {\n Agrave: 'À',\n agrave: 'à',\n Aacute: 'Á',\n aacute: 'á',\n Acirc: 'Â',\n acirc: 'â',\n Atilde: 'Ã',\n atilde: 'ã',\n Auml: 'Ä',\n auml: 'ä',\n Aring: 'Å',\n aring: 'å',\n AElig: 'Æ',\n aelig: 'æ',\n Ccedil: 'Ç',\n ccedil: 'ç',\n Egrave: 'È',\n egrave: 'è',\n Eacute: 'É',\n eacute: 'é',\n Ecirc: 'Ê',\n ecirc: 'ê',\n Euml: 'Ë',\n euml: 'ë',\n Igrave: 'Ì',\n igrave: 'ì',\n Iacute: 'Í',\n iacute: 'í',\n Icirc: 'Î',\n icirc: 'î',\n Iuml: 'Ï',\n iuml: 'ï',\n ETH: 'Ð',\n eth: 'ð',\n Ntilde: 'Ñ',\n ntilde: 'ñ',\n Ograve: 'Ò',\n ograve: 'ò',\n Oacute: 'Ó',\n oacute: 'ó',\n Ocirc: 'Ô',\n ocirc: 'ô',\n Otilde: 'Õ',\n otilde: 'õ',\n Ouml: 'Ö',\n ouml: 'ö',\n Oslash: 'Ø',\n oslash: 'ø',\n Ugrave: 'Ù',\n ugrave: 'ù',\n Uacute: 'Ú',\n uacute: 'ú',\n Ucirc: 'Û',\n ucirc: 'û',\n Uuml: 'Ü',\n uuml: 'ü',\n Yacute: 'Ý',\n yacute: 'ý',\n THORN: 'Þ',\n thorn: 'þ',\n szlig: 'ß',\n yuml: 'ÿ',\n Yuml: 'Ÿ',\n};\n\n/**\n * Latin Extended (Letters with diacritics)\n * @type {Record}\n */\nexport const LATIN_EXTENDED = {\n Amacr: 'Ā',\n amacr: 'ā',\n Abreve: 'Ă',\n abreve: 'ă',\n Aogon: 'Ą',\n aogon: 'ą',\n Cacute: 'Ć',\n cacute: 'ć',\n Ccirc: 'Ĉ',\n ccirc: 'ĉ',\n Cdot: 'Ċ',\n cdot: 'ċ',\n Ccaron: 'Č',\n ccaron: 'č',\n Dcaron: 'Ď',\n dcaron: 'ď',\n Dstrok: 'Đ',\n dstrok: 'đ',\n Emacr: 'Ē',\n emacr: 'ē',\n Ecaron: 'Ě',\n ecaron: 'ě',\n Edot: 'Ė',\n edot: 'ė',\n Eogon: 'Ę',\n eogon: 'ę',\n Gcirc: 'Ĝ',\n gcirc: 'ĝ',\n Gbreve: 'Ğ',\n gbreve: 'ğ',\n Gdot: 'Ġ',\n gdot: 'ġ',\n Gcedil: 'Ģ',\n Hcirc: 'Ĥ',\n hcirc: 'ĥ',\n Hstrok: 'Ħ',\n hstrok: 'ħ',\n Itilde: 'Ĩ',\n itilde: 'ĩ',\n Imacr: 'Ī',\n imacr: 'ī',\n Iogon: 'Į',\n iogon: 'į',\n Idot: 'İ',\n IJlig: 'IJ',\n ijlig: 'ij',\n Jcirc: 'Ĵ',\n jcirc: 'ĵ',\n Kcedil: 'Ķ',\n kcedil: 'ķ',\n kgreen: 'ĸ',\n Lacute: 'Ĺ',\n lacute: 'ĺ',\n Lcedil: 'Ļ',\n lcedil: 'ļ',\n Lcaron: 'Ľ',\n lcaron: 'ľ',\n Lmidot: 'Ŀ',\n lmidot: 'ŀ',\n Lstrok: 'Ł',\n lstrok: 'ł',\n Nacute: 'Ń',\n nacute: 'ń',\n Ncaron: 'Ň',\n ncaron: 'ň',\n Ncedil: 'Ņ',\n ncedil: 'ņ',\n ENG: 'Ŋ',\n eng: 'ŋ',\n Omacr: 'Ō',\n omacr: 'ō',\n Odblac: 'Ő',\n odblac: 'ő',\n OElig: 'Œ',\n oelig: 'œ',\n Racute: 'Ŕ',\n racute: 'ŕ',\n Rcaron: 'Ř',\n rcaron: 'ř',\n Rcedil: 'Ŗ',\n rcedil: 'ŗ',\n Sacute: 'Ś',\n sacute: 'ś',\n Scirc: 'Ŝ',\n scirc: 'ŝ',\n Scedil: 'Ş',\n scedil: 'ş',\n Scaron: 'Š',\n scaron: 'š',\n Tcedil: 'Ţ',\n tcedil: 'ţ',\n Tcaron: 'Ť',\n tcaron: 'ť',\n Tstrok: 'Ŧ',\n tstrok: 'ŧ',\n Utilde: 'Ũ',\n utilde: 'ũ',\n Umacr: 'Ū',\n umacr: 'ū',\n Ubreve: 'Ŭ',\n ubreve: 'ŭ',\n Uring: 'Ů',\n uring: 'ů',\n Udblac: 'Ű',\n udblac: 'ű',\n Uogon: 'Ų',\n uogon: 'ų',\n Wcirc: 'Ŵ',\n wcirc: 'ŵ',\n Ycirc: 'Ŷ',\n ycirc: 'ŷ',\n Zacute: 'Ź',\n zacute: 'ź',\n Zdot: 'Ż',\n zdot: 'ż',\n Zcaron: 'Ž',\n zcaron: 'ž',\n};\n\n/**\n * Greek Letters\n * @type {Record}\n */\nexport const GREEK = {\n Alpha: 'Α',\n alpha: 'α',\n Beta: 'Β',\n beta: 'β',\n Gamma: 'Γ',\n gamma: 'γ',\n Delta: 'Δ',\n delta: 'δ',\n Epsilon: 'Ε',\n epsilon: 'ε',\n epsiv: 'ϵ',\n varepsilon: 'ϵ',\n Zeta: 'Ζ',\n zeta: 'ζ',\n Eta: 'Η',\n eta: 'η',\n Theta: 'Θ',\n theta: 'θ',\n thetasym: 'ϑ',\n vartheta: 'ϑ',\n Iota: 'Ι',\n iota: 'ι',\n Kappa: 'Κ',\n kappa: 'κ',\n kappav: 'ϰ',\n varkappa: 'ϰ',\n Lambda: 'Λ',\n lambda: 'λ',\n Mu: 'Μ',\n mu: 'μ',\n Nu: 'Ν',\n nu: 'ν',\n Xi: 'Ξ',\n xi: 'ξ',\n Omicron: 'Ο',\n omicron: 'ο',\n Pi: 'Π',\n pi: 'π',\n piv: 'ϖ',\n varpi: 'ϖ',\n Rho: 'Ρ',\n rho: 'ρ',\n rhov: 'ϱ',\n varrho: 'ϱ',\n Sigma: 'Σ',\n sigma: 'σ',\n sigmaf: 'ς',\n sigmav: 'ς',\n varsigma: 'ς',\n Tau: 'Τ',\n tau: 'τ',\n Upsilon: 'Υ',\n upsilon: 'υ',\n upsi: 'υ',\n Upsi: 'ϒ',\n upsih: 'ϒ',\n Phi: 'Φ',\n phi: 'φ',\n phiv: 'ϕ',\n varphi: 'ϕ',\n Chi: 'Χ',\n chi: 'χ',\n Psi: 'Ψ',\n psi: 'ψ',\n Omega: 'Ω',\n omega: 'ω',\n ohm: 'Ω',\n Gammad: 'Ϝ',\n gammad: 'ϝ',\n digamma: 'ϝ',\n};\n\n/**\n * Cyrillic Letters\n * @type {Record}\n */\nexport const CYRILLIC = {\n Afr: '𝔄',\n afr: '𝔞',\n Acy: 'А',\n acy: 'а',\n Bcy: 'Б',\n bcy: 'б',\n Vcy: 'В',\n vcy: 'в',\n Gcy: 'Г',\n gcy: 'г',\n Dcy: 'Д',\n dcy: 'д',\n IEcy: 'Е',\n iecy: 'е',\n IOcy: 'Ё',\n iocy: 'ё',\n ZHcy: 'Ж',\n zhcy: 'ж',\n Zcy: 'З',\n zcy: 'з',\n Icy: 'И',\n icy: 'и',\n Jcy: 'Й',\n jcy: 'й',\n Kcy: 'К',\n kcy: 'к',\n Lcy: 'Л',\n lcy: 'л',\n Mcy: 'М',\n mcy: 'м',\n Ncy: 'Н',\n ncy: 'н',\n Ocy: 'О',\n ocy: 'о',\n Pcy: 'П',\n pcy: 'п',\n Rcy: 'Р',\n rcy: 'р',\n Scy: 'С',\n scy: 'с',\n Tcy: 'Т',\n tcy: 'т',\n Ucy: 'У',\n ucy: 'у',\n Fcy: 'Ф',\n fcy: 'ф',\n KHcy: 'Х',\n khcy: 'х',\n TScy: 'Ц',\n tscy: 'ц',\n CHcy: 'Ч',\n chcy: 'ч',\n SHcy: 'Ш',\n shcy: 'ш',\n SHCHcy: 'Щ',\n shchcy: 'щ',\n HARDcy: 'Ъ',\n hardcy: 'ъ',\n Ycy: 'Ы',\n ycy: 'ы',\n SOFTcy: 'Ь',\n softcy: 'ь',\n Ecy: 'Э',\n ecy: 'э',\n YUcy: 'Ю',\n yucy: 'ю',\n YAcy: 'Я',\n yacy: 'я',\n DJcy: 'Ђ',\n djcy: 'ђ',\n GJcy: 'Ѓ',\n gjcy: 'ѓ',\n Jukcy: 'Є',\n jukcy: 'є',\n DScy: 'Ѕ',\n dscy: 'ѕ',\n Iukcy: 'І',\n iukcy: 'і',\n YIcy: 'Ї',\n yicy: 'ї',\n Jsercy: 'Ј',\n jsercy: 'ј',\n LJcy: 'Љ',\n ljcy: 'љ',\n NJcy: 'Њ',\n njcy: 'њ',\n TSHcy: 'Ћ',\n tshcy: 'ћ',\n KJcy: 'Ќ',\n kjcy: 'ќ',\n Ubrcy: 'Ў',\n ubrcy: 'ў',\n DZcy: 'Џ',\n dzcy: 'џ',\n};\n\n/**\n * Mathematical Operators & Relations\n * @type {Record}\n */\nexport const MATH = {\n plus: '+',\n minus: '−',\n mnplus: '∓',\n mp: '∓',\n pm: '±',\n times: '×',\n div: '÷',\n divide: '÷',\n sdot: '⋅',\n star: '☆',\n starf: '★',\n bigstar: '★',\n lowast: '∗',\n ast: '*',\n midast: '*',\n compfn: '∘',\n smallcircle: '∘',\n bullet: '•',\n bull: '•',\n nbsp: '\\u00a0',\n hellip: '…',\n mldr: '…',\n prime: '′',\n Prime: '″',\n tprime: '‴',\n bprime: '‵',\n backprime: '‵',\n minus: '−',\n minusd: '∸',\n dotminus: '∸',\n plusdo: '∔',\n dotplus: '∔',\n plusmn: '±',\n minusplus: '∓',\n mnplus: '∓',\n mp: '∓',\n setminus: '∖',\n smallsetminus: '∖',\n Backslash: '∖',\n setmn: '∖',\n ssetmn: '∖',\n lowbar: '_',\n verbar: '|',\n vert: '|',\n VerticalLine: '|',\n colon: ':',\n Colon: '∷',\n Proportion: '∷',\n ratio: '∶',\n equals: '=',\n ne: '≠',\n nequiv: '≢',\n equiv: '≡',\n Congruent: '≡',\n sim: '∼',\n thicksim: '∼',\n thksim: '∼',\n sime: '≃',\n simeq: '≃',\n TildeEqual: '≃',\n asymp: '≈',\n approx: '≈',\n thickapprox: '≈',\n thkap: '≈',\n TildeTilde: '≈',\n ncong: '≇',\n cong: '≅',\n TildeFullEqual: '≅',\n asympeq: '≍',\n CupCap: '≍',\n bump: '≎',\n Bumpeq: '≎',\n HumpDownHump: '≎',\n bumpe: '≏',\n bumpeq: '≏',\n HumpEqual: '≏',\n dotminus: '∸',\n minusd: '∸',\n plusdo: '∔',\n dotplus: '∔',\n le: '≤',\n LessEqual: '≤',\n ge: '≥',\n GreaterEqual: '≥',\n lesseqgtr: '⋚',\n lesseqqgtr: '⪋',\n greater: '>',\n less: '<',\n};\n\n/**\n * Mathematical Operators (Advanced)\n * @type {Record}\n */\nexport const MATH_ADVANCED = {\n alefsym: 'ℵ',\n aleph: 'ℵ',\n beth: 'ℶ',\n gimel: 'ℷ',\n daleth: 'ℸ',\n forall: '∀',\n ForAll: '∀',\n part: '∂',\n PartialD: '∂',\n exist: '∃',\n Exists: '∃',\n nexist: '∄',\n nexists: '∄',\n empty: '∅',\n emptyset: '∅',\n emptyv: '∅',\n varnothing: '∅',\n nabla: '∇',\n Del: '∇',\n isin: '∈',\n isinv: '∈',\n in: '∈',\n Element: '∈',\n notin: '∉',\n notinva: '∉',\n ni: '∋',\n niv: '∋',\n SuchThat: '∋',\n ReverseElement: '∋',\n notni: '∌',\n notniva: '∌',\n prod: '∏',\n Product: '∏',\n coprod: '∐',\n Coproduct: '∐',\n sum: '∑',\n Sum: '∑',\n minus: '−',\n mp: '∓',\n plusdo: '∔',\n dotplus: '∔',\n setminus: '∖',\n lowast: '∗',\n radic: '√',\n Sqrt: '√',\n prop: '∝',\n propto: '∝',\n Proportional: '∝',\n varpropto: '∝',\n infin: '∞',\n infintie: '⧝',\n ang: '∠',\n angle: '∠',\n angmsd: '∡',\n measuredangle: '∡',\n angsph: '∢',\n mid: '∣',\n VerticalBar: '∣',\n nmid: '∤',\n nsmid: '∤',\n npar: '∦',\n parallel: '∥',\n spar: '∥',\n nparallel: '∦',\n nspar: '∦',\n and: '∧',\n wedge: '∧',\n or: '∨',\n vee: '∨',\n cap: '∩',\n cup: '∪',\n int: '∫',\n Integral: '∫',\n conint: '∮',\n ContourIntegral: '∮',\n Conint: '∯',\n DoubleContourIntegral: '∯',\n Cconint: '∰',\n there4: '∴',\n therefore: '∴',\n Therefore: '∴',\n becaus: '∵',\n because: '∵',\n Because: '∵',\n ratio: '∶',\n Proportion: '∷',\n minusd: '∸',\n dotminus: '∸',\n mDDot: '∺',\n homtht: '∻',\n sim: '∼',\n bsimg: '∽',\n backsim: '∽',\n ac: '∾',\n mstpos: '∾',\n acd: '∿',\n VerticalTilde: '≀',\n wr: '≀',\n wreath: '≀',\n nsime: '≄',\n nsimeq: '≄',\n nsimeq: '≄',\n ncong: '≇',\n simne: '≆',\n ncongdot: '⩭̸',\n ngsim: '≵',\n nsim: '≁',\n napprox: '≉',\n nap: '≉',\n ngeq: '≱',\n nge: '≱',\n nleq: '≰',\n nle: '≰',\n ngtr: '≯',\n ngt: '≯',\n nless: '≮',\n nlt: '≮',\n nprec: '⊀',\n npr: '⊀',\n nsucc: '⊁',\n nsc: '⊁',\n};\n\n/**\n * Arrows\n * @type {Record}\n */\nexport const ARROWS = {\n larr: '←',\n leftarrow: '←',\n LeftArrow: '←',\n uarr: '↑',\n uparrow: '↑',\n UpArrow: '↑',\n rarr: '→',\n rightarrow: '→',\n RightArrow: '→',\n darr: '↓',\n downarrow: '↓',\n DownArrow: '↓',\n harr: '↔',\n leftrightarrow: '↔',\n LeftRightArrow: '↔',\n varr: '↕',\n updownarrow: '↕',\n UpDownArrow: '↕',\n nwarr: '↖',\n nwarrow: '↖',\n UpperLeftArrow: '↖',\n nearr: '↗',\n nearrow: '↗',\n UpperRightArrow: '↗',\n searr: '↘',\n searrow: '↘',\n LowerRightArrow: '↘',\n swarr: '↙',\n swarrow: '↙',\n LowerLeftArrow: '↙',\n lArr: '⇐',\n Leftarrow: '⇐',\n uArr: '⇑',\n Uparrow: '⇑',\n rArr: '⇒',\n Rightarrow: '⇒',\n dArr: '⇓',\n Downarrow: '⇓',\n hArr: '⇔',\n Leftrightarrow: '⇔',\n iff: '⇔',\n vArr: '⇕',\n Updownarrow: '⇕',\n lAarr: '⇚',\n Lleftarrow: '⇚',\n rAarr: '⇛',\n Rrightarrow: '⇛',\n lrarr: '⇆',\n leftrightarrows: '⇆',\n rlarr: '⇄',\n rightleftarrows: '⇄',\n lrhar: '⇋',\n leftrightharpoons: '⇋',\n ReverseEquilibrium: '⇋',\n rlhar: '⇌',\n rightleftharpoons: '⇌',\n Equilibrium: '⇌',\n udarr: '⇅',\n UpArrowDownArrow: '⇅',\n duarr: '⇵',\n DownArrowUpArrow: '⇵',\n llarr: '⇇',\n leftleftarrows: '⇇',\n rrarr: '⇉',\n rightrightarrows: '⇉',\n ddarr: '⇊',\n downdownarrows: '⇊',\n har: '↽',\n lhard: '↽',\n leftharpoondown: '↽',\n lharu: '↼',\n leftharpoonup: '↼',\n rhard: '⇁',\n rightharpoondown: '⇁',\n rharu: '⇀',\n rightharpoonup: '⇀',\n lsh: '↰',\n Lsh: '↰',\n rsh: '↱',\n Rsh: '↱',\n ldsh: '↲',\n rdsh: '↳',\n hookleftarrow: '↩',\n hookrightarrow: '↪',\n mapstoleft: '↤',\n mapstoup: '↥',\n map: '↦',\n mapsto: '↦',\n mapstodown: '↧',\n crarr: '↵',\n nwarrow: '↖',\n nearrow: '↗',\n searrow: '↘',\n swarrow: '↙',\n nleftarrow: '↚',\n nleftrightarrow: '↮',\n nrightarrow: '↛',\n nrarr: '↛',\n larrtl: '↢',\n rarrtl: '↣',\n leftarrowtail: '↢',\n rightarrowtail: '↣',\n twoheadleftarrow: '↞',\n twoheadrightarrow: '↠',\n Larr: '↞',\n Rarr: '↠',\n larrhk: '↩',\n rarrhk: '↪',\n larrlp: '↫',\n looparrowleft: '↫',\n rarrlp: '↬',\n looparrowright: '↬',\n harrw: '↭',\n leftrightsquigarrow: '↭',\n nrarrw: '↝̸',\n rarrw: '↝',\n rightsquigarrow: '↝',\n larrbfs: '⤟',\n rarrbfs: '⤠',\n nvHarr: '⤄',\n nvlArr: '⤂',\n nvrArr: '⤃',\n larrfs: '⤝',\n rarrfs: '⤞',\n Map: '⤅',\n larrsim: '⥳',\n rarrsim: '⥴',\n harrcir: '⥈',\n Uarrocir: '⥉',\n lurdshar: '⥊',\n ldrdhar: '⥧',\n ldrushar: '⥋',\n rdldhar: '⥩',\n lrhard: '⥭',\n rlhar: '⇌',\n uharr: '↾',\n uharl: '↿',\n dharr: '⇂',\n dharl: '⇃',\n Uarr: '↟',\n Darr: '↡',\n zigrarr: '⇝',\n nwArr: '⇖',\n neArr: '⇗',\n seArr: '⇘',\n swArr: '⇙',\n nharr: '↮',\n nhArr: '⇎',\n nlarr: '↚',\n nlArr: '⇍',\n nrarr: '↛',\n nrArr: '⇏',\n larrb: '⇤',\n LeftArrowBar: '⇤',\n rarrb: '⇥',\n RightArrowBar: '⇥',\n};\n\n/**\n * Geometric Shapes\n * @type {Record}\n */\nexport const SHAPES = {\n square: '□',\n Square: '□',\n squ: '□',\n squf: '▪',\n squarf: '▪',\n blacksquar: '▪',\n blacksquare: '▪',\n FilledVerySmallSquare: '▪',\n blk34: '▓',\n blk12: '▒',\n blk14: '░',\n block: '█',\n srect: '▭',\n rect: '▭',\n sdot: '⋅',\n sdotb: '⊡',\n dotsquare: '⊡',\n triangle: '▵',\n tri: '▵',\n trine: '▵',\n utri: '▵',\n triangledown: '▿',\n dtri: '▿',\n tridown: '▿',\n triangleleft: '◃',\n ltri: '◃',\n triangleright: '▹',\n rtri: '▹',\n blacktriangle: '▴',\n utrif: '▴',\n blacktriangledown: '▾',\n dtrif: '▾',\n blacktriangleleft: '◂',\n ltrif: '◂',\n blacktriangleright: '▸',\n rtrif: '▸',\n loz: '◊',\n lozenge: '◊',\n blacklozenge: '⧫',\n lozf: '⧫',\n bigcirc: '◯',\n xcirc: '◯',\n circ: 'ˆ',\n Circle: '○',\n cir: '○',\n o: '○',\n bullet: '•',\n bull: '•',\n hellip: '…',\n mldr: '…',\n nldr: '‥',\n boxh: '─',\n HorizontalLine: '─',\n boxv: '│',\n boxdr: '┌',\n boxdl: '┐',\n boxur: '└',\n boxul: '┘',\n boxvr: '├',\n boxvl: '┤',\n boxhd: '┬',\n boxhu: '┴',\n boxvh: '┼',\n boxH: '═',\n boxV: '║',\n boxdR: '╒',\n boxDr: '╓',\n boxDR: '╔',\n boxDl: '╕',\n boxdL: '╖',\n boxDL: '╗',\n boxuR: '╘',\n boxUr: '╙',\n boxUR: '╚',\n boxUl: '╜',\n boxuL: '╛',\n boxUL: '╝',\n boxvR: '╞',\n boxVr: '╟',\n boxVR: '╠',\n boxVl: '╢',\n boxvL: '╡',\n boxVL: '╣',\n boxHd: '╤',\n boxhD: '╥',\n boxHD: '╦',\n boxHu: '╧',\n boxhU: '╨',\n boxHU: '╩',\n boxvH: '╪',\n boxVh: '╫',\n boxVH: '╬',\n};\n\n/**\n * Punctuation & Diacritics\n * @type {Record}\n */\nexport const PUNCTUATION = {\n excl: '!',\n iexcl: '¡',\n brvbar: '¦',\n sect: '§',\n uml: '¨',\n copy: '©',\n ordf: 'ª',\n laquo: '«',\n not: '¬',\n shy: '\\u00ad',\n reg: '®',\n macr: '¯',\n deg: '°',\n plusmn: '±',\n sup2: '²',\n sup3: '³',\n acute: '´',\n micro: 'µ',\n para: '¶',\n middot: '·',\n cedil: '¸',\n sup1: '¹',\n ordm: 'º',\n raquo: '»',\n frac14: '¼',\n frac12: '½',\n frac34: '¾',\n iquest: '¿',\n nbsp: '\\u00a0',\n comma: ',',\n period: '.',\n colon: ':',\n semi: ';',\n vert: '|',\n Verbar: '‖',\n verbar: '|',\n dblac: '˝',\n circ: 'ˆ',\n caron: 'ˇ',\n breve: '˘',\n dot: '˙',\n ring: '˚',\n ogon: '˛',\n tilde: '˜',\n DiacriticalGrave: '`',\n DiacriticalAcute: '´',\n DiacriticalTilde: '˜',\n DiacriticalDot: '˙',\n DiacriticalDoubleAcute: '˝',\n grave: '`',\n acute: '´',\n};\n\n/**\n * Currency Symbols\n * @type {Record}\n */\nexport const CURRENCY = {\n cent: '¢',\n pound: '£',\n curren: '¤',\n yen: '¥',\n euro: '€',\n dollar: '$',\n euro: '€',\n fnof: 'ƒ',\n inr: '₹',\n af: '؋',\n birr: 'ብር',\n peso: '₱',\n rub: '₽',\n won: '₩',\n yuan: '¥',\n cedil: '¸',\n};\n\n/**\n * Fractions\n * @type {Record}\n */\nexport const FRACTIONS = {\n frac12: '½',\n half: '½',\n frac13: '⅓',\n frac14: '¼',\n frac15: '⅕',\n frac16: '⅙',\n frac18: '⅛',\n frac23: '⅔',\n frac25: '⅖',\n frac34: '¾',\n frac35: '⅗',\n frac38: '⅜',\n frac45: '⅘',\n frac56: '⅚',\n frac58: '⅝',\n frac78: '⅞',\n frasl: '⁄',\n};\n\n/**\n * Miscellaneous Symbols\n * @type {Record}\n */\nexport const MISC_SYMBOLS = {\n trade: '™',\n TRADE: '™',\n telrec: '⌕',\n target: '⌖',\n ulcorn: '⌜',\n ulcorner: '⌜',\n urcorn: '⌝',\n urcorner: '⌝',\n dlcorn: '⌞',\n llcorner: '⌞',\n drcorn: '⌟',\n lrcorner: '⌟',\n intercal: '⊺',\n intcal: '⊺',\n oplus: '⊕',\n CirclePlus: '⊕',\n ominus: '⊖',\n CircleMinus: '⊖',\n otimes: '⊗',\n CircleTimes: '⊗',\n osol: '⊘',\n odot: '⊙',\n CircleDot: '⊙',\n oast: '⊛',\n circledast: '⊛',\n odash: '⊝',\n circleddash: '⊝',\n ocirc: '⊚',\n circledcirc: '⊚',\n boxplus: '⊞',\n plusb: '⊞',\n boxminus: '⊟',\n minusb: '⊟',\n boxtimes: '⊠',\n timesb: '⊠',\n boxdot: '⊡',\n sdotb: '⊡',\n veebar: '⊻',\n vee: '∨',\n barvee: '⊽',\n and: '∧',\n wedge: '∧',\n Cap: '⋒',\n Cup: '⋓',\n Fork: '⋔',\n pitchfork: '⋔',\n epar: '⋕',\n ltlarr: '⥶',\n nvap: '≍⃒',\n nvsim: '∼⃒',\n nvge: '≥⃒',\n nvle: '≤⃒',\n nvlt: '<⃒',\n nvgt: '>⃒',\n nvltrie: '⊴⃒',\n nvrtrie: '⊵⃒',\n Vdash: '⊩',\n dashv: '⊣',\n vDash: '⊨',\n Vdash: '⊩',\n Vvdash: '⊪',\n nvdash: '⊬',\n nvDash: '⊭',\n nVdash: '⊮',\n nVDash: '⊯',\n};\n\n/**\n * All entities combined (if you need everything)\n * @type {Record}\n */\nexport const ALL_ENTITIES = {\n ...BASIC_LATIN,\n ...LATIN_ACCENTS,\n ...LATIN_EXTENDED,\n ...GREEK,\n ...CYRILLIC,\n ...MATH,\n ...MATH_ADVANCED,\n ...ARROWS,\n ...SHAPES,\n ...PUNCTUATION,\n ...CURRENCY,\n ...FRACTIONS,\n ...MISC_SYMBOLS,\n};\n\nexport const XML = {\n amp: \"&\",\n apos: \"'\",\n gt: \">\",\n lt: \"<\",\n quot: \"\\\"\"\n}\nexport const COMMON_HTML = {\n nbsp: '\\u00a0',\n copy: '\\u00a9',\n reg: '\\u00ae',\n trade: '\\u2122',\n mdash: '\\u2014',\n ndash: '\\u2013',\n hellip: '\\u2026',\n laquo: '\\u00ab',\n raquo: '\\u00bb',\n lsquo: '\\u2018',\n rsquo: '\\u2019',\n ldquo: '\\u201c',\n rdquo: '\\u201d',\n bull: '\\u2022',\n para: '\\u00b6',\n sect: '\\u00a7',\n deg: '\\u00b0',\n frac12: '\\u00bd',\n frac14: '\\u00bc',\n frac34: '\\u00be',\n}\n// ---------------------------------------------------------------------------\n// Note: NUMERIC_ENTITIES (&#NNN; / &#xHH;) are handled by the scanner directly\n// via String.fromCodePoint() without any map lookup.\n// ---------------------------------------------------------------------------","// ---------------------------------------------------------------------------\n// Built-in named entity map (name → replacement string)\n// No regex, no {regex,val} objects — just flat key/value pairs.\n// ---------------------------------------------------------------------------\n\nimport { XML as DEFAULT_XML_ENTITIES } from \"./entities.js\"\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst SPECIAL_CHARS = new Set('!?\\\\\\\\/[]$%{}^&*()<>|+');\n\n/**\n * Validate that an entity name contains no dangerous characters.\n * @param {string} name\n * @returns {string} the name, unchanged\n * @throws {Error} on invalid characters\n */\nfunction validateEntityName(name) {\n if (name[0] === '#') {\n throw new Error(`[EntityReplacer] Invalid character '#' in entity name: \"${name}\"`);\n }\n for (const ch of name) {\n if (SPECIAL_CHARS.has(ch)) {\n throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: \"${name}\"`);\n }\n }\n return name;\n}\n\n/**\n * Merge one or more entity maps into a flat name→string map.\n * Accepts either:\n * - plain string values: { amp: '&' }\n * - legacy {regex,val} / {regx,val}: { lt: { regex: /.../, val: '<' } }\n *\n * Values containing '&' are skipped (recursive expansion risk).\n *\n * @param {...object} maps\n * @returns {Record}\n */\nfunction mergeEntityMaps(...maps) {\n const out = Object.create(null);\n for (const map of maps) {\n if (!map) continue;\n for (const key of Object.keys(map)) {\n const raw = map[key];\n if (typeof raw === 'string') {\n out[key] = raw;\n } else if (raw && typeof raw === 'object' && raw.val !== undefined) {\n // Legacy {regex,val} or {regx,val} — extract the string val only\n const val = raw.val;\n if (typeof val === 'string') {\n out[key] = val;\n }\n // function vals are not supported in the scanner — skip\n }\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// applyLimitsTo helpers\n// ---------------------------------------------------------------------------\n\nconst LIMIT_TIER_EXTERNAL = 'external'; // input/runtime + persistent external maps\nconst LIMIT_TIER_BASE = 'base'; // DEFAULT_XML_ENTITIES + namedEntities (system) maps\nconst LIMIT_TIER_ALL = 'all'; // every entity regardless of tier\n\n/**\n * Resolve `applyLimitsTo` option into a normalised Set of tier strings.\n * Accepted values: 'external' | 'base' | 'all' | string[]\n * Default: 'external' (only untrusted injected entities are counted).\n * @param {string|string[]|undefined} raw\n * @returns {Set}\n */\nfunction parseLimitTiers(raw) {\n if (!raw || raw === LIMIT_TIER_EXTERNAL) return new Set([LIMIT_TIER_EXTERNAL]);\n if (raw === LIMIT_TIER_ALL) return new Set([LIMIT_TIER_ALL]);\n if (raw === LIMIT_TIER_BASE) return new Set([LIMIT_TIER_BASE]);\n if (Array.isArray(raw)) return new Set(raw);\n return new Set([LIMIT_TIER_EXTERNAL]); // safe default for unrecognised values\n}\n\n// ---------------------------------------------------------------------------\n// NCR (Numeric Character Reference) classification\n// ---------------------------------------------------------------------------\n\n// Severity order — higher number = stricter action.\n// Used to enforce minimum action levels for specific codepoint ranges.\nconst NCR_LEVEL = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 });\n\n// XML 1.0 §2.2: allowed chars are #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]\n// Restricted C0: U+0001–U+001F excluding U+0009, U+000A, U+000D\nconst XML10_ALLOWED_C0 = new Set([0x09, 0x0A, 0x0D]);\n\n/**\n * Parse the `ncr` constructor option into flat, hot-path-friendly fields.\n * @param {object|undefined} ncr\n * @returns {{ xmlVersion: number, onLevel: number, nullLevel: number }}\n */\nfunction parseNCRConfig(ncr) {\n if (!ncr) {\n return { xmlVersion: 1.0, onLevel: NCR_LEVEL.allow, nullLevel: NCR_LEVEL.remove };\n }\n const xmlVersion = ncr.xmlVersion === 1.1 ? 1.1 : 1.0;\n const onLevel = NCR_LEVEL[ncr.onNCR] ?? NCR_LEVEL.allow;\n const nullLevel = NCR_LEVEL[ncr.nullNCR] ?? NCR_LEVEL.remove;\n // 'allow' is not meaningful for null — clamp to at least 'remove'\n const clampedNull = Math.max(nullLevel, NCR_LEVEL.remove);\n return { xmlVersion, onLevel, nullLevel: clampedNull };\n}\n\n// ---------------------------------------------------------------------------\n// EntityReplacer\n// ---------------------------------------------------------------------------\n\n/**\n * Single-pass, zero-regex entity replacer for XML/HTML content.\n *\n * Algorithm: scan the string once for '&', read to ';', resolve via map\n * or direct codepoint conversion, build output chunks, join once at the end.\n *\n * Entity lookup priority (highest → lowest):\n * 1. input / runtime (DOCTYPE entities for current document)\n * 2. persistent external (survive across documents)\n * 3. base named map (DEFAULT_XML_ENTITIES + user-supplied namedEntities)\n *\n * Both input and external resolve as the 'external' tier for limit purposes.\n * Base map entities resolve as the 'base' tier.\n *\n * Numeric / hex references (&#NNN; / &#xHH;) are resolved directly via\n * String.fromCodePoint() — no map needed. They count as 'base' tier.\n *\n * @example\n * const replacer = new EntityReplacer({ namedEntities: COMMON_HTML });\n * replacer.setExternalEntities({ brand: 'Acme' });\n *\n * const instance = replacer.reset();\n * instance.addInputEntities({ version: '1.0' });\n * instance.encode('&brand; v&version; <'); // 'Acme v1.0 <'\n */\nexport default class EntityDecoder {\n /**\n * @param {object} [options]\n * @param {object|null} [options.namedEntities] — extra named entities merged into base map\n * @param {object} [options.limit] — security limits\n * @param {number} [options.limit.maxTotalExpansions=0] — 0 = unlimited\n * @param {number} [options.limit.maxExpandedLength=0] — 0 = unlimited\n * @param {'external'|'base'|'all'|string[]} [options.limit.applyLimitsTo='external']\n * Which entity tiers count against the security limits:\n * - 'external' (default) — only input/runtime + persistent external entities\n * - 'base' — only DEFAULT_XML_ENTITIES + namedEntities\n * - 'all' — every entity regardless of tier\n * - string[] — explicit combination, e.g. ['external', 'base']\n * @param {((resolved: string, original: string) => string)|null} [options.postCheck=null]\n * @param {string[]} [options.remove=[]] — entity names (e.g. ['nbsp', '#13']) to delete (replace with empty string)\n * @param {string[]} [options.leave=[]] — entity names to keep as literal (unchanged in output)\n * @param {object} [options.ncr] — Numeric Character Reference controls\n * @param {1.0|1.1} [options.ncr.xmlVersion=1.0]\n * XML version governing which codepoint ranges are restricted:\n * - 1.0 — C0 controls U+0001–U+001F (except U+0009/000A/000D) are prohibited\n * - 1.1 — C0 controls are allowed when written as NCRs; C1 (U+007F–U+009F) decoded as-is\n * @param {'allow'|'leave'|'remove'|'throw'} [options.ncr.onNCR='allow']\n * Base action for numeric references. Severity order: allow < leave < remove < throw.\n * For codepoint ranges that carry a minimum level (surrogates → remove, XML 1.0 C0 → remove),\n * the effective action is max(onNCR, rangeMinimum).\n * @param {'remove'|'throw'} [options.ncr.nullNCR='remove']\n * Action for U+0000 (null). 'allow' and 'leave' are clamped to 'remove' since null is never safe.\n */\n constructor(options = {}) {\n this._limit = options.limit || {};\n this._maxTotalExpansions = this._limit.maxTotalExpansions || 0;\n this._maxExpandedLength = this._limit.maxExpandedLength || 0;\n this._postCheck = typeof options.postCheck === 'function' ? options.postCheck : r => r;\n this._limitTiers = parseLimitTiers(this._limit.applyLimitsTo ?? LIMIT_TIER_EXTERNAL);\n this._numericAllowed = options.numericAllowed ?? true;\n // Base map: DEFAULT_XML_ENTITIES + user-supplied extras. Immutable after construction.\n this._baseMap = mergeEntityMaps(DEFAULT_XML_ENTITIES, options.namedEntities || null);\n\n // Persistent external entities — survive across documents.\n // Stored as a separate map so reset() never touches them.\n /** @type {Record} */\n this._externalMap = Object.create(null);\n\n // Input / runtime entities — current document only, wiped on reset().\n /** @type {Record} */\n this._inputMap = Object.create(null);\n\n // Per-document counters\n this._totalExpansions = 0;\n this._expandedLength = 0;\n\n // --- New: remove / leave sets ---\n /** @type {Set} */\n this._removeSet = new Set(options.remove && Array.isArray(options.remove) ? options.remove : []);\n /** @type {Set} */\n this._leaveSet = new Set(options.leave && Array.isArray(options.leave) ? options.leave : []);\n\n // --- NCR config (parsed into flat fields for hot-path speed) ---\n const ncrCfg = parseNCRConfig(options.ncr);\n this._ncrXmlVersion = ncrCfg.xmlVersion;\n this._ncrOnLevel = ncrCfg.onLevel;\n this._ncrNullLevel = ncrCfg.nullLevel;\n }\n\n // -------------------------------------------------------------------------\n // Persistent external entity registration\n // -------------------------------------------------------------------------\n\n /**\n * Replace the full set of persistent external entities.\n * All keys are validated — throws on invalid characters.\n * @param {Record} map\n */\n setExternalEntities(map) {\n if (map) {\n for (const key of Object.keys(map)) {\n validateEntityName(key);\n }\n }\n this._externalMap = mergeEntityMaps(map);\n }\n\n /**\n * Add a single persistent external entity.\n * @param {string} key\n * @param {string} value\n */\n addExternalEntity(key, value) {\n validateEntityName(key);\n if (typeof value === 'string' && value.indexOf('&') === -1) {\n this._externalMap[key] = value;\n }\n }\n\n // -------------------------------------------------------------------------\n // Input / runtime entity registration (per document)\n // -------------------------------------------------------------------------\n\n /**\n * Inject DOCTYPE entities for the current document.\n * Also resets per-document expansion counters.\n * @param {Record} map\n */\n addInputEntities(map) {\n this._totalExpansions = 0;\n this._expandedLength = 0;\n this._inputMap = mergeEntityMaps(map);\n }\n\n // -------------------------------------------------------------------------\n // Per-document reset\n // -------------------------------------------------------------------------\n\n /**\n * Wipe input/runtime entities and reset counters.\n * Call this before processing each new document.\n * @returns {this}\n */\n reset() {\n this._inputMap = Object.create(null);\n this._totalExpansions = 0;\n this._expandedLength = 0;\n return this;\n }\n\n // -------------------------------------------------------------------------\n // XML version (can be set after construction, e.g. once parser reads )\n // -------------------------------------------------------------------------\n\n /**\n * Update the XML version used for NCR classification.\n * Call this as soon as the document's `` declaration is parsed.\n * @param {1.0|1.1|number} version\n */\n setXmlVersion(version) {\n this._ncrXmlVersion = version === 1.1 ? 1.1 : 1.0;\n }\n\n // -------------------------------------------------------------------------\n // Primary API\n // -------------------------------------------------------------------------\n\n /**\n * Replace all entity references in `str` in a single pass.\n *\n * @param {string} str\n * @returns {string}\n */\n decode(str) {\n if (typeof str !== 'string' || str.length === 0) return str;\n //TODO: check if needed\n //if (str.indexOf('&') === -1) return str; // fast path — no entities at all\n\n const original = str;\n const chunks = [];\n const len = str.length;\n let last = 0; // start of next unprocessed literal chunk\n let i = 0;\n\n const limitExpansions = this._maxTotalExpansions > 0;\n const limitLength = this._maxExpandedLength > 0;\n const checkLimits = limitExpansions || limitLength;\n\n while (i < len) {\n // Scan forward to next '&'\n if (str.charCodeAt(i) !== 38 /* '&' */) { i++; continue; }\n\n // --- Found '&' at position i ---\n\n // Scan forward to ';'\n let j = i + 1;\n while (j < len && str.charCodeAt(j) !== 59 /* ';' */ && (j - i) <= 32) j++;\n\n if (j >= len || str.charCodeAt(j) !== 59) {\n // No closing ';' within window — treat '&' as literal\n i++;\n continue;\n }\n\n // Raw token between '&' and ';' (exclusive)\n const token = str.slice(i + 1, j);\n if (token.length === 0) { i++; continue; }\n\n let replacement;\n let tier; // which limit tier this entity belongs to\n\n if (this._removeSet.has(token)) {\n // Remove entity: replace with empty string\n replacement = '';\n // If entity was unknown (replacement undefined), we still need a tier for limits.\n // Treat as external tier because it's user-directed removal of an unknown reference.\n if (tier === undefined) {\n tier = LIMIT_TIER_EXTERNAL;\n }\n } else if (this._leaveSet.has(token)) {\n // Do not replace — keep original &token; as literal\n i++;\n continue;\n } else if (token.charCodeAt(0) === 35 /* '#' */) {\n // ---- Numeric / NCR reference ----\n // NCR classification always runs first — prohibited codepoints must be\n // caught regardless of numericAllowed.\n const ncrResult = this._resolveNCR(token);\n if (ncrResult === undefined) {\n // 'leave' action — keep original &token; as-is\n i++;\n continue;\n }\n replacement = ncrResult; // '' for remove, char string for allow\n tier = LIMIT_TIER_BASE;\n } else {\n // ---- Named reference ----\n const resolved = this._resolveName(token);\n replacement = resolved?.value;\n tier = resolved?.tier;\n }\n\n if (replacement === undefined) {\n // Unknown entity — leave as-is, advance past '&' only\n i++;\n continue;\n }\n\n // Flush literal chunk before this entity\n if (i > last) chunks.push(str.slice(last, i));\n chunks.push(replacement);\n last = j + 1; // skip past ';'\n i = last;\n\n // Apply expansion limits only if this tier is being tracked\n if (checkLimits && this._tierCounts(tier)) {\n if (limitExpansions) {\n this._totalExpansions++;\n if (this._totalExpansions > this._maxTotalExpansions) {\n throw new Error(\n `[EntityReplacer] Entity expansion count limit exceeded: ` +\n `${this._totalExpansions} > ${this._maxTotalExpansions}`\n );\n }\n }\n if (limitLength) {\n // delta: replacement.length minus the raw &token; length (token.length + 2 for '&' and ';')\n const delta = replacement.length - (token.length + 2);\n if (delta > 0) {\n this._expandedLength += delta;\n if (this._expandedLength > this._maxExpandedLength) {\n throw new Error(\n `[EntityReplacer] Expanded content length limit exceeded: ` +\n `${this._expandedLength} > ${this._maxExpandedLength}`\n );\n }\n }\n }\n }\n }\n\n // Flush trailing literal\n if (last < len) chunks.push(str.slice(last));\n\n // If nothing was replaced, chunks is empty — return original\n const result = chunks.length === 0 ? str : chunks.join('');\n\n return this._postCheck(result, original);\n }\n\n // -------------------------------------------------------------------------\n // Private: limit tier check\n // -------------------------------------------------------------------------\n\n /**\n * Returns true if a resolved entity of the given tier should count\n * against the expansion/length limits.\n * @param {string} tier — LIMIT_TIER_EXTERNAL | LIMIT_TIER_BASE\n * @returns {boolean}\n */\n _tierCounts(tier) {\n if (this._limitTiers.has(LIMIT_TIER_ALL)) return true;\n return this._limitTiers.has(tier);\n }\n\n // -------------------------------------------------------------------------\n // Private: entity resolution\n // -------------------------------------------------------------------------\n\n /**\n * Resolve a named entity token (without & and ;).\n * Priority: inputMap > externalMap > baseMap\n * Returns the resolved value tagged with its limit tier.\n *\n * @param {string} name\n * @returns {{ value: string, tier: string }|undefined}\n */\n _resolveName(name) {\n // input and external both count as 'external' tier for limit purposes —\n // they are injected at runtime and are the untrusted surface.\n if (name in this._inputMap) return { value: this._inputMap[name], tier: LIMIT_TIER_EXTERNAL };\n if (name in this._externalMap) return { value: this._externalMap[name], tier: LIMIT_TIER_EXTERNAL };\n if (name in this._baseMap) return { value: this._baseMap[name], tier: LIMIT_TIER_BASE };\n return undefined;\n }\n\n /**\n * Classify a codepoint and return the minimum action level that must be applied.\n * Returns -1 when no minimum is imposed (normal allow path).\n *\n * Ranges checked (in priority order):\n * 1. U+0000 — null, governed by nullNCR (always ≥ remove)\n * 2. U+D800–U+DFFF — surrogates, always prohibited (min: remove)\n * 3. U+0001–U+001F \\ {0x09,0x0A,0x0D} — XML 1.0 restricted C0 (min: remove)\n * (skipped in XML 1.1 — C0 controls are allowed when written as NCRs)\n *\n * @param {number} cp — codepoint\n * @returns {number} — minimum NCR_LEVEL value, or -1 for no restriction\n */\n _classifyNCR(cp) {\n // 1. Null\n if (cp === 0) return this._ncrNullLevel;\n\n // 2. Surrogates — always prohibited, minimum 'remove'\n if (cp >= 0xD800 && cp <= 0xDFFF) return NCR_LEVEL.remove;\n\n // 3. XML 1.0 restricted C0 controls\n if (this._ncrXmlVersion === 1.0) {\n if (cp >= 0x01 && cp <= 0x1F && !XML10_ALLOWED_C0.has(cp)) return NCR_LEVEL.remove;\n }\n\n return -1; // no restriction\n }\n\n /**\n * Execute a resolved NCR action.\n *\n * @param {number} action — NCR_LEVEL value\n * @param {string} token — raw token (e.g. '#38') for error messages\n * @param {number} cp — codepoint, used only for error messages\n * @returns {string|undefined}\n * - decoded character string → 'allow'\n * - '' → 'remove'\n * - undefined → 'leave' (caller must skip past '&' only)\n * - throws Error → 'throw'\n */\n _applyNCRAction(action, token, cp) {\n switch (action) {\n case NCR_LEVEL.allow: return String.fromCodePoint(cp);\n case NCR_LEVEL.remove: return '';\n case NCR_LEVEL.leave: return undefined; // signal: keep literal\n case NCR_LEVEL.throw:\n throw new Error(\n `[EntityDecoder] Prohibited numeric character reference ` +\n `&${token}; (U+${cp.toString(16).toUpperCase().padStart(4, '0')})`\n );\n default: return String.fromCodePoint(cp);\n }\n }\n\n /**\n * Full NCR resolution pipeline for a numeric token.\n *\n * Steps:\n * 1. Parse the codepoint (decimal or hex).\n * 2. Validate the raw codepoint range (NaN, <0, >0x10FFFF).\n * 3. If numericAllowed is false and no minimum restriction applies → leave as-is.\n * 4. Classify the codepoint to find the minimum required action level.\n * 5. Resolve effective action = max(onNCR, minimum).\n * 6. Apply and return.\n *\n * @param {string} token — e.g. '#38', '#x26', '#X26'\n * @returns {string|undefined}\n * - string (incl. '') — replacement ('' = remove)\n * - undefined — leave original &token; as-is\n */\n _resolveNCR(token) {\n // Step 1: parse codepoint\n const second = token.charCodeAt(1);\n let cp;\n if (second === 120 /* x */ || second === 88 /* X */) {\n cp = parseInt(token.slice(2), 16);\n } else {\n cp = parseInt(token.slice(1), 10);\n }\n\n // Step 2: out-of-range → leave as-is unconditionally\n if (Number.isNaN(cp) || cp < 0 || cp > 0x10FFFF) return undefined;\n\n // Step 3: classify to get minimum action level\n const minimum = this._classifyNCR(cp);\n\n // Step 4: if numericAllowed is false and no hard minimum → leave\n if (!this._numericAllowed && minimum < NCR_LEVEL.remove) return undefined;\n\n // Step 5: effective action = max(configured onNCR, range minimum)\n const effective = minimum === -1\n ? this._ncrOnLevel\n : Math.max(this._ncrOnLevel, minimum);\n\n // Step 6: apply\n return this._applyNCRAction(effective, token, cp);\n }\n}","'use strict';\n///@ts-check\n\nimport { getAllMatches, isExist, DANGEROUS_PROPERTY_NAMES, criticalProperties } from '../util.js';\nimport xmlNode from './xmlNode.js';\nimport DocTypeReader from './DocTypeReader.js';\nimport toNumber from \"strnum\";\nimport getIgnoreAttributesFn from \"../ignoreAttributes.js\";\nimport { Expression, Matcher } from 'path-expression-matcher';\nimport { ExpressionSet } from 'path-expression-matcher';\nimport { EntityDecoder, XML, CURRENCY, COMMON_HTML } from '@nodable/entities';\n\n// const regx =\n// '<((!\\\\[CDATA\\\\[([\\\\s\\\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\\\/)(NAME)\\\\s*>))([^<]*)'\n// .replace(/NAME/g, util.nameRegexp);\n\n//const tagsRegx = new RegExp(\"<(\\\\/?[\\\\w:\\\\-\\._]+)([^>]*)>(\\\\s*\"+cdataRegx+\")*([^<]+)?\",\"g\");\n//const tagsRegx = new RegExp(\"<(\\\\/?)((\\\\w*:)?([\\\\w:\\\\-\\._]+))([^>]*)>([^<]*)(\"+cdataRegx+\"([^<]*))*([^<]+)?\",\"g\");\n\n// Helper functions for attribute and namespace handling\n\n/**\n * Extract raw attributes (without prefix) from prefixed attribute map\n * @param {object} prefixedAttrs - Attributes with prefix from buildAttributesMap\n * @param {object} options - Parser options containing attributeNamePrefix\n * @returns {object} Raw attributes for matcher\n */\nfunction extractRawAttributes(prefixedAttrs, options) {\n if (!prefixedAttrs) return {};\n\n // Handle attributesGroupName option\n const attrs = options.attributesGroupName\n ? prefixedAttrs[options.attributesGroupName]\n : prefixedAttrs;\n\n if (!attrs) return {};\n\n const rawAttrs = {};\n for (const key in attrs) {\n // Remove the attribute prefix to get raw name\n if (key.startsWith(options.attributeNamePrefix)) {\n const rawName = key.substring(options.attributeNamePrefix.length);\n rawAttrs[rawName] = attrs[key];\n } else {\n // Attribute without prefix (shouldn't normally happen, but be safe)\n rawAttrs[key] = attrs[key];\n }\n }\n return rawAttrs;\n}\n\n/**\n * Extract namespace from raw tag name\n * @param {string} rawTagName - Tag name possibly with namespace (e.g., \"soap:Envelope\")\n * @returns {string|undefined} Namespace or undefined\n */\nfunction extractNamespace(rawTagName) {\n if (!rawTagName || typeof rawTagName !== 'string') return undefined;\n\n const colonIndex = rawTagName.indexOf(':');\n if (colonIndex !== -1 && colonIndex > 0) {\n const ns = rawTagName.substring(0, colonIndex);\n // Don't treat xmlns as a namespace\n if (ns !== 'xmlns') {\n return ns;\n }\n }\n return undefined;\n}\n\nexport default class OrderedObjParser {\n constructor(options) {\n this.options = options;\n this.currentNode = null;\n this.tagsNodeStack = [];\n this.parseXml = parseXml;\n this.parseTextData = parseTextData;\n this.resolveNameSpace = resolveNameSpace;\n this.buildAttributesMap = buildAttributesMap;\n this.isItStopNode = isItStopNode;\n this.replaceEntitiesValue = replaceEntitiesValue;\n this.readStopNodeData = readStopNodeData;\n this.saveTextToParentTag = saveTextToParentTag;\n this.addChild = addChild;\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.entityExpansionCount = 0;\n this.currentExpandedLength = 0;\n let namedEntities = { ...XML };\n if (this.options.entityDecoder) {\n this.entityDecoder = this.options.entityDecoder\n } else {\n if (typeof this.options.htmlEntities === \"object\") namedEntities = this.options.htmlEntities;\n else if (this.options.htmlEntities === true) namedEntities = { ...COMMON_HTML, ...CURRENCY };\n this.entityDecoder = new EntityDecoder({\n namedEntities: namedEntities,\n numericAllowed: this.options.htmlEntities,\n limit: {\n maxTotalExpansions: this.options.processEntities.maxTotalExpansions,\n maxExpandedLength: this.options.processEntities.maxExpandedLength,\n applyLimitsTo: this.options.processEntities.appliesTo,\n }\n //postCheck: resolved => resolved\n });\n }\n\n // Initialize path matcher for path-expression-matcher\n this.matcher = new Matcher();\n\n // Live read-only proxy of matcher — PEM creates and caches this internally.\n // All user callbacks receive this instead of the mutable matcher.\n this.readonlyMatcher = this.matcher.readOnly();\n\n // Flag to track if current node is a stop node (optimization)\n this.isCurrentNodeStopNode = false;\n\n // Pre-compile stopNodes expressions\n this.stopNodeExpressionsSet = new ExpressionSet();\n const stopNodesOpts = this.options.stopNodes;\n if (stopNodesOpts && stopNodesOpts.length > 0) {\n for (let i = 0; i < stopNodesOpts.length; i++) {\n const stopNodeExp = stopNodesOpts[i];\n if (typeof stopNodeExp === 'string') {\n // Convert string to Expression object\n this.stopNodeExpressionsSet.add(new Expression(stopNodeExp));\n } else if (stopNodeExp instanceof Expression) {\n // Already an Expression object\n this.stopNodeExpressionsSet.add(stopNodeExp);\n }\n }\n this.stopNodeExpressionsSet.seal();\n }\n }\n\n}\n\n\n/**\n * @param {string} val\n * @param {string} tagName\n * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath\n * @param {boolean} dontTrim\n * @param {boolean} hasAttributes\n * @param {boolean} isLeafNode\n * @param {boolean} escapeEntities\n */\nfunction parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {\n const options = this.options;\n if (val !== undefined) {\n if (options.trimValues && !dontTrim) {\n val = val.trim();\n }\n if (val.length > 0) {\n if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath);\n\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = options.jPath ? jPath.toString() : jPath;\n const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);\n if (newval === null || newval === undefined) {\n //don't parse\n return val;\n } else if (typeof newval !== typeof val || newval !== val) {\n //overwrite\n return newval;\n } else if (options.trimValues) {\n return parseValue(val, options.parseTagValue, options.numberParseOptions);\n } else {\n const trimmedVal = val.trim();\n if (trimmedVal === val) {\n return parseValue(val, options.parseTagValue, options.numberParseOptions);\n } else {\n return val;\n }\n }\n }\n }\n}\n\nfunction resolveNameSpace(tagname) {\n if (this.options.removeNSPrefix) {\n const tags = tagname.split(':');\n const prefix = tagname.charAt(0) === '/' ? '/' : '';\n if (tags[0] === 'xmlns') {\n return '';\n }\n if (tags.length === 2) {\n tagname = prefix + tags[1];\n }\n }\n return tagname;\n}\n\n//TODO: change regex to capture NS\n//const attrsRegx = new RegExp(\"([\\\\w\\\\-\\\\.\\\\:]+)\\\\s*=\\\\s*(['\\\"])((.|\\n)*?)\\\\2\",\"gm\");\nconst attrsRegx = new RegExp('([^\\\\s=]+)\\\\s*(=\\\\s*([\\'\"])([\\\\s\\\\S]*?)\\\\3)?', 'gm');\n\nfunction buildAttributesMap(attrStr, jPath, tagName, force = false) {\n const options = this.options;\n if (force === true || (options.ignoreAttributes !== true && typeof attrStr === 'string')) {\n // attrStr = attrStr.replace(/\\r?\\n/g, ' ');\n //attrStr = attrStr || attrStr.trim();\n\n const matches = getAllMatches(attrStr, attrsRegx);\n const len = matches.length; //don't make it inline\n const attrs = {};\n\n // Pre-process values once: trim + entity replacement\n // Reused in both matcher update and second pass\n const processedVals = new Array(len);\n let hasRawAttrs = false;\n const rawAttrsForMatcher = {};\n\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n const oldVal = matches[i][4];\n\n if (attrName.length && oldVal !== undefined) {\n let val = oldVal;\n if (options.trimValues) val = val.trim();\n val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher);\n processedVals[i] = val;\n\n rawAttrsForMatcher[attrName] = val;\n hasRawAttrs = true;\n }\n }\n\n // Update matcher ONCE before second pass, if applicable\n if (hasRawAttrs && typeof jPath === 'object' && jPath.updateCurrent) {\n jPath.updateCurrent(rawAttrsForMatcher);\n }\n\n // Hoist toString() once — path doesn't change during attribute processing\n const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;\n\n // Second pass: apply processors, build final attrs\n let hasAttrs = false;\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n\n if (this.ignoreAttributesFn(attrName, jPathStr)) continue;\n\n let aName = options.attributeNamePrefix + attrName;\n\n if (attrName.length) {\n if (options.transformAttributeName) {\n aName = options.transformAttributeName(aName);\n }\n aName = sanitizeName(aName, options);\n\n if (matches[i][4] !== undefined) {\n // Reuse already-processed value — no double entity replacement\n const oldVal = processedVals[i];\n\n const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);\n if (newVal === null || newVal === undefined) {\n attrs[aName] = oldVal;\n } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {\n attrs[aName] = newVal;\n } else {\n attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions);\n }\n hasAttrs = true;\n } else if (options.allowBooleanAttributes) {\n attrs[aName] = true;\n hasAttrs = true;\n }\n }\n }\n\n if (!hasAttrs) return;\n\n if (options.attributesGroupName) {\n const attrCollection = {};\n attrCollection[options.attributesGroupName] = attrs;\n return attrCollection;\n }\n return attrs;\n }\n}\nconst parseXml = function (xmlData) {\n xmlData = xmlData.replace(/\\r\\n?/g, \"\\n\"); //TODO: remove this line\n const xmlObj = new xmlNode('!xml');\n let currentNode = xmlObj;\n let textData = \"\";\n\n // Reset matcher for new document\n this.matcher.reset();\n this.entityDecoder.reset();\n\n // Reset entity expansion counters for this document\n this.entityExpansionCount = 0;\n this.currentExpandedLength = 0;\n const options = this.options;\n const docTypeReader = new DocTypeReader(options.processEntities);\n const xmlLen = xmlData.length;\n for (let i = 0; i < xmlLen; i++) {//for each char in XML data\n const ch = xmlData[i];\n if (ch === '<') {\n // const nextIndex = i+1;\n // const _2ndChar = xmlData[nextIndex];\n const c1 = xmlData.charCodeAt(i + 1);\n if (c1 === 47) {//Closing Tag '/'\n const closeIndex = findClosingIndex(xmlData, \">\", i, \"Closing Tag is not closed.\")\n let tagName = xmlData.substring(i + 2, closeIndex).trim();\n\n if (options.removeNSPrefix) {\n const colonIndex = tagName.indexOf(\":\");\n if (colonIndex !== -1) {\n tagName = tagName.substr(colonIndex + 1);\n }\n }\n\n tagName = transformTagName(options.transformTagName, tagName, \"\", options).tagName;\n\n if (currentNode) {\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n }\n\n //check if last tag of nested tag was unpaired tag\n const lastTagName = this.matcher.getCurrentTag();\n if (tagName && options.unpairedTagsSet.has(tagName)) {\n throw new Error(`Unpaired tag can not be used as closing tag: `);\n }\n if (lastTagName && options.unpairedTagsSet.has(lastTagName)) {\n // Pop the unpaired tag\n this.matcher.pop();\n this.tagsNodeStack.pop();\n }\n // Pop the closing tag\n this.matcher.pop();\n this.isCurrentNodeStopNode = false; // Reset flag when closing tag\n\n currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope\n textData = \"\";\n i = closeIndex;\n } else if (c1 === 63) { //'?'\n\n let tagData = readTagExp(xmlData, i, false, \"?>\");\n if (!tagData) throw new Error(\"Pi Tag is not closed.\");\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true);\n if (attsMap) {\n const ver = attsMap[this.options.attributeNamePrefix + \"version\"];\n this.entityDecoder.setXmlVersion(Number(ver) || 1.0);\n }\n if ((options.ignoreDeclaration && tagData.tagName === \"?xml\") || options.ignorePiTags) {\n //do nothing\n } else {\n\n const childNode = new xmlNode(tagData.tagName);\n childNode.add(options.textNodeName, \"\");\n\n if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) {\n childNode[\":@\"] = attsMap\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, i);\n }\n\n\n i = tagData.closeIndex + 1;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 45\n && xmlData.charCodeAt(i + 3) === 45) { //'!--'\n const endIndex = findClosingIndex(xmlData, \"-->\", i + 4, \"Comment is not closed.\")\n if (options.commentPropName) {\n const comment = xmlData.substring(i + 4, endIndex - 2);\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n\n currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]);\n }\n i = endIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 68) { //'!D'\n const result = docTypeReader.readDocType(xmlData, i);\n this.entityDecoder.addInputEntities(result.entities);\n i = result.i;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 91) { // '!['\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"CDATA is not closed.\") - 2;\n const tagExp = xmlData.substring(i + 9, closeIndex);\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n\n let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true);\n if (val == undefined) val = \"\";\n\n //cdata should be set even if it is 0 length string\n if (options.cdataPropName) {\n currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]);\n } else {\n currentNode.add(options.textNodeName, val);\n }\n\n i = closeIndex + 2;\n } else {//Opening tag\n let result = readTagExp(xmlData, i, options.removeNSPrefix);\n\n // Safety check: readTagExp can return undefined\n if (!result) {\n // Log context for debugging\n const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50));\n throw new Error(`readTagExp returned undefined at position ${i}. Context: \"${context}\"`);\n }\n\n let tagName = result.tagName;\n const rawTagName = result.rawTagName;\n let tagExp = result.tagExp;\n let attrExpPresent = result.attrExpPresent;\n let closeIndex = result.closeIndex;\n\n ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));\n\n if (options.strictReservedNames &&\n (tagName === options.commentPropName\n || tagName === options.cdataPropName\n || tagName === options.textNodeName\n || tagName === options.attributesGroupName\n )) {\n throw new Error(`Invalid tag name: ${tagName}`);\n }\n\n //save text as child node\n if (currentNode && textData) {\n if (currentNode.tagname !== '!xml') {\n //when nested tag is found\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false);\n }\n }\n\n //check if last tag was unpaired tag\n const lastTag = currentNode;\n if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) {\n currentNode = this.tagsNodeStack.pop();\n this.matcher.pop();\n }\n\n // Clean up self-closing syntax BEFORE processing attributes\n // This is where tagExp gets the trailing / removed\n let isSelfClosing = false;\n if (tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1) {\n isSelfClosing = true;\n if (tagName[tagName.length - 1] === \"/\") {\n tagName = tagName.substr(0, tagName.length - 1);\n tagExp = tagName;\n } else {\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n\n // Re-check attrExpPresent after cleaning\n attrExpPresent = (tagName !== tagExp);\n }\n\n // Now process attributes with CLEAN tagExp (no trailing /)\n let prefixedAttrs = null;\n let rawAttrs = {};\n let namespace = undefined;\n\n // Extract namespace from rawTagName\n namespace = extractNamespace(rawTagName);\n\n // Push tag to matcher FIRST (with empty attrs for now) so callbacks see correct path\n if (tagName !== xmlObj.tagname) {\n this.matcher.push(tagName, {}, namespace);\n }\n\n // Now build attributes - callbacks will see correct matcher state\n if (tagName !== tagExp && attrExpPresent) {\n // Build attributes (returns prefixed attributes for the tree)\n // Note: buildAttributesMap now internally updates the matcher with raw attributes\n prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName);\n\n if (prefixedAttrs) {\n // Extract raw attributes (without prefix) for our use\n //TODO: seems a performance overhead\n rawAttrs = extractRawAttributes(prefixedAttrs, options);\n }\n }\n\n // Now check if this is a stop node (after attributes are set)\n if (tagName !== xmlObj.tagname) {\n this.isCurrentNodeStopNode = this.isItStopNode();\n }\n\n const startIndex = i;\n if (this.isCurrentNodeStopNode) {\n let tagContent = \"\";\n\n // For self-closing tags, content is empty\n if (isSelfClosing) {\n i = result.closeIndex;\n }\n //unpaired tag\n else if (options.unpairedTagsSet.has(tagName)) {\n i = result.closeIndex;\n }\n //normal tag\n else {\n //read until closing tag is found\n const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);\n if (!result) throw new Error(`Unexpected end of ${rawTagName}`);\n i = result.i;\n tagContent = result.tagContent;\n }\n\n const childNode = new xmlNode(tagName);\n\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n\n // For stop nodes, store raw content as-is without any processing\n childNode.add(options.textNodeName, tagContent);\n\n this.matcher.pop(); // Pop the stop node tag\n this.isCurrentNodeStopNode = false; // Reset flag\n\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n } else {\n //selfClosing tag\n if (isSelfClosing) {\n ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));\n\n const childNode = new xmlNode(tagName);\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n this.matcher.pop(); // Pop self-closing tag\n this.isCurrentNodeStopNode = false; // Reset flag\n }\n else if (options.unpairedTagsSet.has(tagName)) {//unpaired tag\n const childNode = new xmlNode(tagName);\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n this.matcher.pop(); // Pop unpaired tag\n this.isCurrentNodeStopNode = false; // Reset flag\n i = result.closeIndex;\n // Continue to next iteration without changing currentNode\n continue;\n }\n //opening tag\n else {\n const childNode = new xmlNode(tagName);\n if (this.tagsNodeStack.length > options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n this.tagsNodeStack.push(currentNode);\n\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n currentNode = childNode;\n }\n textData = \"\";\n i = closeIndex;\n }\n }\n } else {\n textData += xmlData[i];\n }\n }\n return xmlObj.child;\n}\n\nfunction addChild(currentNode, childNode, matcher, startIndex) {\n // unset startIndex if not requested\n if (!this.options.captureMetaData) startIndex = undefined;\n\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher;\n const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[\":@\"])\n if (result === false) {\n //do nothing\n } else if (typeof result === \"string\") {\n childNode.tagname = result\n currentNode.addChild(childNode, startIndex);\n } else {\n currentNode.addChild(childNode, startIndex);\n }\n}\n\n/**\n * @param {object} val - Entity object with regex and val properties\n * @param {string} tagName - Tag name\n * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath\n */\nfunction replaceEntitiesValue(val, tagName, jPath) {\n const entityConfig = this.options.processEntities;\n\n if (!entityConfig || !entityConfig.enabled) {\n return val;\n }\n\n // Check if tag is allowed to contain entities\n if (entityConfig.allowedTags) {\n const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;\n const allowed = Array.isArray(entityConfig.allowedTags)\n ? entityConfig.allowedTags.includes(tagName)\n : entityConfig.allowedTags(tagName, jPathOrMatcher);\n\n if (!allowed) {\n return val;\n }\n }\n\n // Apply custom tag filter if provided\n if (entityConfig.tagFilter) {\n const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;\n if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) {\n return val; // Skip based on custom filter\n }\n }\n\n return this.entityDecoder.decode(val);\n}\n\n\nfunction saveTextToParentTag(textData, parentNode, matcher, isLeafNode) {\n if (textData) { //store previously collected data as textNode\n if (isLeafNode === undefined) isLeafNode = parentNode.child.length === 0\n\n textData = this.parseTextData(textData,\n parentNode.tagname,\n matcher,\n false,\n parentNode[\":@\"] ? Object.keys(parentNode[\":@\"]).length !== 0 : false,\n isLeafNode);\n\n if (textData !== undefined && textData !== \"\")\n parentNode.add(this.options.textNodeName, textData);\n textData = \"\";\n }\n return textData;\n}\n\n/**\n * @param {Array} stopNodeExpressions - Array of compiled Expression objects\n * @param {Matcher} matcher - Current path matcher\n */\nfunction isItStopNode() {\n if (this.stopNodeExpressionsSet.size === 0) return false;\n\n return this.matcher.matchesAny(this.stopNodeExpressionsSet);\n}\n\n/**\n * Returns the tag Expression and where it is ending handling single-double quotes situation\n * @param {string} xmlData \n * @param {number} i starting index\n * @returns \n */\nfunction tagExpWithClosingIndex(xmlData, i, closingChar = \">\") {\n let attrBoundary = 0;\n const chars = [];\n const len = xmlData.length;\n const closeCode0 = closingChar.charCodeAt(0);\n const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1;\n\n for (let index = i; index < len; index++) {\n const code = xmlData.charCodeAt(index);\n\n if (attrBoundary) {\n if (code === attrBoundary) attrBoundary = 0;\n } else if (code === 34 || code === 39) { // \" or '\n attrBoundary = code;\n } else if (code === closeCode0) {\n if (closeCode1 !== -1) {\n if (xmlData.charCodeAt(index + 1) === closeCode1) {\n return { data: String.fromCharCode(...chars), index };\n }\n } else {\n return { data: String.fromCharCode(...chars), index };\n }\n } else if (code === 9) { // \\t\n chars.push(32); // space\n continue;\n }\n\n chars.push(code);\n }\n}\n\nfunction findClosingIndex(xmlData, str, i, errMsg) {\n const closingIndex = xmlData.indexOf(str, i);\n if (closingIndex === -1) {\n throw new Error(errMsg)\n } else {\n return closingIndex + str.length - 1;\n }\n}\n\nfunction findClosingChar(xmlData, char, i, errMsg) {\n const closingIndex = xmlData.indexOf(char, i);\n if (closingIndex === -1) throw new Error(errMsg);\n return closingIndex; // no offset needed\n}\n\nfunction readTagExp(xmlData, i, removeNSPrefix, closingChar = \">\") {\n const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);\n if (!result) return;\n let tagExp = result.data;\n const closeIndex = result.index;\n const separatorIndex = tagExp.search(/\\s/);\n let tagName = tagExp;\n let attrExpPresent = true;\n if (separatorIndex !== -1) {//separate tag name and attributes expression\n tagName = tagExp.substring(0, separatorIndex);\n tagExp = tagExp.substring(separatorIndex + 1).trimStart();\n }\n\n const rawTagName = tagName;\n if (removeNSPrefix) {\n const colonIndex = tagName.indexOf(\":\");\n if (colonIndex !== -1) {\n tagName = tagName.substr(colonIndex + 1);\n attrExpPresent = tagName !== result.data.substr(colonIndex + 1);\n }\n }\n\n return {\n tagName: tagName,\n tagExp: tagExp,\n closeIndex: closeIndex,\n attrExpPresent: attrExpPresent,\n rawTagName: rawTagName,\n }\n}\n/**\n * find paired tag for a stop node\n * @param {string} xmlData \n * @param {string} tagName \n * @param {number} i \n */\nfunction readStopNodeData(xmlData, tagName, i) {\n const startIndex = i;\n // Starting at 1 since we already have an open tag\n let openTagCount = 1;\n\n const xmllen = xmlData.length;\n for (; i < xmllen; i++) {\n if (xmlData[i] === \"<\") {\n const c1 = xmlData.charCodeAt(i + 1);\n if (c1 === 47) {//close tag '/'\n const closeIndex = findClosingChar(xmlData, \">\", i, `${tagName} is not closed`);\n let closeTagName = xmlData.substring(i + 2, closeIndex).trim();\n if (closeTagName === tagName) {\n openTagCount--;\n if (openTagCount === 0) {\n return {\n tagContent: xmlData.substring(startIndex, i),\n i: closeIndex\n }\n }\n }\n i = closeIndex;\n } else if (c1 === 63) { //?\n const closeIndex = findClosingIndex(xmlData, \"?>\", i + 1, \"StopNode is not closed.\")\n i = closeIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 45\n && xmlData.charCodeAt(i + 3) === 45) { // '!--'\n const closeIndex = findClosingIndex(xmlData, \"-->\", i + 3, \"StopNode is not closed.\")\n i = closeIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 91) { // '!['\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"StopNode is not closed.\") - 2;\n i = closeIndex;\n } else {\n const tagData = readTagExp(xmlData, i, '>')\n\n if (tagData) {\n const openTagName = tagData && tagData.tagName;\n if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== \"/\") {\n openTagCount++;\n }\n i = tagData.closeIndex;\n }\n }\n }\n }//end for loop\n}\n\nfunction parseValue(val, shouldParse, options) {\n if (shouldParse && typeof val === 'string') {\n //console.log(options)\n const newval = val.trim();\n if (newval === 'true') return true;\n else if (newval === 'false') return false;\n else return toNumber(val, options);\n } else {\n if (isExist(val)) {\n return val;\n } else {\n return '';\n }\n }\n}\n\nfunction fromCodePoint(str, base, prefix) {\n const codePoint = Number.parseInt(str, base);\n\n if (codePoint >= 0 && codePoint <= 0x10FFFF) {\n return String.fromCodePoint(codePoint);\n } else {\n return prefix + str + \";\";\n }\n}\n\nfunction transformTagName(fn, tagName, tagExp, options) {\n if (fn) {\n const newTagName = fn(tagName);\n if (tagExp === tagName) {\n tagExp = newTagName\n }\n tagName = newTagName;\n }\n tagName = sanitizeName(tagName, options);\n return { tagName, tagExp };\n}\n\n\n\nfunction sanitizeName(name, options) {\n if (criticalProperties.includes(name)) {\n throw new Error(`[SECURITY] Invalid name: \"${name}\" is a reserved JavaScript keyword that could cause prototype pollution`);\n } else if (DANGEROUS_PROPERTY_NAMES.includes(name)) {\n return options.onDangerousProperty(name);\n }\n return name;\n}","export default function getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}","'use strict';\n\nimport XmlNode from './xmlNode.js';\nimport { Matcher } from 'path-expression-matcher';\n\nconst METADATA_SYMBOL = XmlNode.getMetaDataSymbol();\n\n/**\n * Helper function to strip attribute prefix from attribute map\n * @param {object} attrs - Attributes with prefix (e.g., {\"@_class\": \"code\"})\n * @param {string} prefix - Attribute prefix to remove (e.g., \"@_\")\n * @returns {object} Attributes without prefix (e.g., {\"class\": \"code\"})\n */\nfunction stripAttributePrefix(attrs, prefix) {\n if (!attrs || typeof attrs !== 'object') return {};\n if (!prefix) return attrs;\n\n const rawAttrs = {};\n for (const key in attrs) {\n if (key.startsWith(prefix)) {\n const rawName = key.substring(prefix.length);\n rawAttrs[rawName] = attrs[key];\n } else {\n // Attribute without prefix (shouldn't normally happen, but be safe)\n rawAttrs[key] = attrs[key];\n }\n }\n return rawAttrs;\n}\n\n/**\n * \n * @param {array} node \n * @param {any} options \n * @param {Matcher} matcher - Path matcher instance\n * @returns \n */\nexport default function prettify(node, options, matcher, readonlyMatcher) {\n return compress(node, options, matcher, readonlyMatcher);\n}\n\n/**\n * @param {array} arr \n * @param {object} options \n * @param {Matcher} matcher - Path matcher instance\n * @returns object\n */\nfunction compress(arr, options, matcher, readonlyMatcher) {\n let text;\n const compressedObj = {}; //This is intended to be a plain object\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const property = propName(tagObj);\n\n // Push current property to matcher WITH RAW ATTRIBUTES (no prefix)\n if (property !== undefined && property !== options.textNodeName) {\n const rawAttrs = stripAttributePrefix(\n tagObj[\":@\"] || {},\n options.attributeNamePrefix\n );\n matcher.push(property, rawAttrs);\n }\n\n if (property === options.textNodeName) {\n if (text === undefined) text = tagObj[property];\n else text += \"\" + tagObj[property];\n } else if (property === undefined) {\n continue;\n } else if (tagObj[property]) {\n\n let val = compress(tagObj[property], options, matcher, readonlyMatcher);\n const isLeaf = isLeafTag(val, options);\n\n if (tagObj[\":@\"]) {\n assignAttributes(val, tagObj[\":@\"], readonlyMatcher, options);\n } else if (Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode) {\n val = val[options.textNodeName];\n } else if (Object.keys(val).length === 0) {\n if (options.alwaysCreateTextNode) val[options.textNodeName] = \"\";\n else val = \"\";\n }\n\n if (tagObj[METADATA_SYMBOL] !== undefined && typeof val === \"object\" && val !== null) {\n val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL]; // copy over metadata\n }\n\n\n if (compressedObj[property] !== undefined && Object.prototype.hasOwnProperty.call(compressedObj, property)) {\n if (!Array.isArray(compressedObj[property])) {\n compressedObj[property] = [compressedObj[property]];\n }\n compressedObj[property].push(val);\n } else {\n //TODO: if a node is not an array, then check if it should be an array\n //also determine if it is a leaf node\n\n // Pass jPath string or readonlyMatcher based on options.jPath setting\n const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;\n if (options.isArray(property, jPathOrMatcher, isLeaf)) {\n compressedObj[property] = [val];\n } else {\n compressedObj[property] = val;\n }\n }\n\n // Pop property from matcher after processing\n if (property !== undefined && property !== options.textNodeName) {\n matcher.pop();\n }\n }\n\n }\n // if(text && text.length > 0) compressedObj[options.textNodeName] = text;\n if (typeof text === \"string\") {\n if (text.length > 0) compressedObj[options.textNodeName] = text;\n } else if (text !== undefined) compressedObj[options.textNodeName] = text;\n\n\n return compressedObj;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (key !== \":@\") return key;\n }\n}\n\nfunction assignAttributes(obj, attrMap, readonlyMatcher, options) {\n if (attrMap) {\n const keys = Object.keys(attrMap);\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n const atrrName = keys[i]; // This is the PREFIXED name (e.g., \"@_class\")\n\n // Strip prefix for matcher path (for isArray callback)\n const rawAttrName = atrrName.startsWith(options.attributeNamePrefix)\n ? atrrName.substring(options.attributeNamePrefix.length)\n : atrrName;\n\n // For attributes, we need to create a temporary path\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = options.jPath\n ? readonlyMatcher.toString() + \".\" + rawAttrName\n : readonlyMatcher;\n\n if (options.isArray(atrrName, jPathOrMatcher, true, true)) {\n obj[atrrName] = [attrMap[atrrName]];\n } else {\n obj[atrrName] = attrMap[atrrName];\n }\n }\n }\n}\n\nfunction isLeafTag(obj, options) {\n const { textNodeName } = options;\n const propCount = Object.keys(obj).length;\n\n if (propCount === 0) {\n return true;\n }\n\n if (\n propCount === 1 &&\n (obj[textNodeName] || typeof obj[textNodeName] === \"boolean\" || obj[textNodeName] === 0)\n ) {\n return true;\n }\n\n return false;\n}","'use strict';\n\nimport { getAllMatches, isName } from './util.js';\n\nconst defaultOptions = {\n allowBooleanAttributes: false, //A tag can have attributes without any value\n unpairedTags: []\n};\n\n//const tagsPattern = new RegExp(\"<\\\\/?([\\\\w:\\\\-_\\.]+)\\\\s*\\/?>\",\"g\");\nexport function validate(xmlData, options) {\n options = Object.assign({}, defaultOptions, options);\n\n //xmlData = xmlData.replace(/(\\r\\n|\\n|\\r)/gm,\"\");//make it single line\n //xmlData = xmlData.replace(/(^\\s*<\\?xml.*?\\?>)/g,\"\");//Remove XML starting tag\n //xmlData = xmlData.replace(/()/g,\"\");//Remove DOCTYPE\n const tags = [];\n let tagFound = false;\n\n //indicates that the root tag has been closed (aka. depth 0 has been reached)\n let reachedRoot = false;\n\n if (xmlData[0] === '\\ufeff') {\n // check for byte order mark (BOM)\n xmlData = xmlData.substr(1);\n }\n\n for (let i = 0; i < xmlData.length; i++) {\n\n if (xmlData[i] === '<' && xmlData[i + 1] === '?') {\n i += 2;\n i = readPI(xmlData, i);\n if (i.err) return i;\n } else if (xmlData[i] === '<') {\n //starting of tag\n //read until you reach to '>' avoiding any '>' in attribute value\n let tagStartPos = i;\n i++;\n\n if (xmlData[i] === '!') {\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else {\n let closingTag = false;\n if (xmlData[i] === '/') {\n //closing tag\n closingTag = true;\n i++;\n }\n //read tagname\n let tagName = '';\n for (; i < xmlData.length &&\n xmlData[i] !== '>' &&\n xmlData[i] !== ' ' &&\n xmlData[i] !== '\\t' &&\n xmlData[i] !== '\\n' &&\n xmlData[i] !== '\\r'; i++\n ) {\n tagName += xmlData[i];\n }\n tagName = tagName.trim();\n //console.log(tagName);\n\n if (tagName[tagName.length - 1] === '/') {\n //self closing tag without attributes\n tagName = tagName.substring(0, tagName.length - 1);\n //continue;\n i--;\n }\n if (!validateTagName(tagName)) {\n let msg;\n if (tagName.trim().length === 0) {\n msg = \"Invalid space after '<'.\";\n } else {\n msg = \"Tag '\" + tagName + \"' is an invalid name.\";\n }\n return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));\n }\n\n const result = readAttributeStr(xmlData, i);\n if (result === false) {\n return getErrorObject('InvalidAttr', \"Attributes for '\" + tagName + \"' have open quote.\", getLineNumberForPosition(xmlData, i));\n }\n let attrStr = result.value;\n i = result.index;\n\n if (attrStr[attrStr.length - 1] === '/') {\n //self closing tag\n const attrStrStart = i - attrStr.length;\n attrStr = attrStr.substring(0, attrStr.length - 1);\n const isValid = validateAttributeString(attrStr, options);\n if (isValid === true) {\n tagFound = true;\n //continue; //text may presents after self closing tag\n } else {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));\n }\n } else if (closingTag) {\n if (!result.tagClosed) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' doesn't have proper closing.\", getLineNumberForPosition(xmlData, i));\n } else if (attrStr.trim().length > 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' can't have attributes or invalid starting.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else if (tags.length === 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' has not been opened.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else {\n const otg = tags.pop();\n if (tagName !== otg.tagName) {\n let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);\n return getErrorObject('InvalidTag',\n \"Expected closing tag '\" + otg.tagName + \"' (opened in line \" + openPos.line + \", col \" + openPos.col + \") instead of closing tag '\" + tagName + \"'.\",\n getLineNumberForPosition(xmlData, tagStartPos));\n }\n\n //when there are no more tags, we reached the root level.\n if (tags.length == 0) {\n reachedRoot = true;\n }\n }\n } else {\n const isValid = validateAttributeString(attrStr, options);\n if (isValid !== true) {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));\n }\n\n //if the root level has been reached before ...\n if (reachedRoot === true) {\n return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));\n } else if (options.unpairedTags.indexOf(tagName) !== -1) {\n //don't push into stack\n } else {\n tags.push({ tagName, tagStartPos });\n }\n tagFound = true;\n }\n\n //skip tag text value\n //It may include comments and CDATA value\n for (i++; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n if (xmlData[i + 1] === '!') {\n //comment or CADATA\n i++;\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else if (xmlData[i + 1] === '?') {\n i = readPI(xmlData, ++i);\n if (i.err) return i;\n } else {\n break;\n }\n } else if (xmlData[i] === '&') {\n const afterAmp = validateAmpersand(xmlData, i);\n if (afterAmp == -1)\n return getErrorObject('InvalidChar', \"char '&' is not expected.\", getLineNumberForPosition(xmlData, i));\n i = afterAmp;\n } else {\n if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {\n return getErrorObject('InvalidXml', \"Extra text at the end\", getLineNumberForPosition(xmlData, i));\n }\n }\n } //end of reading tag text value\n if (xmlData[i] === '<') {\n i--;\n }\n }\n } else {\n if (isWhiteSpace(xmlData[i])) {\n continue;\n }\n return getErrorObject('InvalidChar', \"char '\" + xmlData[i] + \"' is not expected.\", getLineNumberForPosition(xmlData, i));\n }\n }\n\n if (!tagFound) {\n return getErrorObject('InvalidXml', 'Start tag expected.', 1);\n } else if (tags.length == 1) {\n return getErrorObject('InvalidTag', \"Unclosed tag '\" + tags[0].tagName + \"'.\", getLineNumberForPosition(xmlData, tags[0].tagStartPos));\n } else if (tags.length > 0) {\n return getErrorObject('InvalidXml', \"Invalid '\" +\n JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\\r?\\n/g, '') +\n \"' found.\", { line: 1, col: 1 });\n }\n\n return true;\n};\n\nfunction isWhiteSpace(char) {\n return char === ' ' || char === '\\t' || char === '\\n' || char === '\\r';\n}\n/**\n * Read Processing insstructions and skip\n * @param {*} xmlData\n * @param {*} i\n */\nfunction readPI(xmlData, i) {\n const start = i;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] == '?' || xmlData[i] == ' ') {\n //tagname\n const tagname = xmlData.substr(start, i - start);\n if (i > 5 && tagname === 'xml') {\n return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));\n } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {\n //check if valid attribut string\n i++;\n break;\n } else {\n continue;\n }\n }\n }\n return i;\n}\n\nfunction readCommentAndCDATA(xmlData, i) {\n if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {\n //comment\n for (i += 3; i < xmlData.length; i++) {\n if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n } else if (\n xmlData.length > i + 8 &&\n xmlData[i + 1] === 'D' &&\n xmlData[i + 2] === 'O' &&\n xmlData[i + 3] === 'C' &&\n xmlData[i + 4] === 'T' &&\n xmlData[i + 5] === 'Y' &&\n xmlData[i + 6] === 'P' &&\n xmlData[i + 7] === 'E'\n ) {\n let angleBracketsCount = 1;\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n angleBracketsCount++;\n } else if (xmlData[i] === '>') {\n angleBracketsCount--;\n if (angleBracketsCount === 0) {\n break;\n }\n }\n }\n } else if (\n xmlData.length > i + 9 &&\n xmlData[i + 1] === '[' &&\n xmlData[i + 2] === 'C' &&\n xmlData[i + 3] === 'D' &&\n xmlData[i + 4] === 'A' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'A' &&\n xmlData[i + 7] === '['\n ) {\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n }\n\n return i;\n}\n\nconst doubleQuote = '\"';\nconst singleQuote = \"'\";\n\n/**\n * Keep reading xmlData until '<' is found outside the attribute value.\n * @param {string} xmlData\n * @param {number} i\n */\nfunction readAttributeStr(xmlData, i) {\n let attrStr = '';\n let startChar = '';\n let tagClosed = false;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {\n if (startChar === '') {\n startChar = xmlData[i];\n } else if (startChar !== xmlData[i]) {\n //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa\n } else {\n startChar = '';\n }\n } else if (xmlData[i] === '>') {\n if (startChar === '') {\n tagClosed = true;\n break;\n }\n }\n attrStr += xmlData[i];\n }\n if (startChar !== '') {\n return false;\n }\n\n return {\n value: attrStr,\n index: i,\n tagClosed: tagClosed\n };\n}\n\n/**\n * Select all the attributes whether valid or invalid.\n */\nconst validAttrStrRegxp = new RegExp('(\\\\s*)([^\\\\s=]+)(\\\\s*=)?(\\\\s*([\\'\"])(([\\\\s\\\\S])*?)\\\\5)?', 'g');\n\n//attr, =\"sd\", a=\"amit's\", a=\"sd\"b=\"saf\", ab cd=\"\"\n\nfunction validateAttributeString(attrStr, options) {\n //console.log(\"start:\"+attrStr+\":end\");\n\n //if(attrStr.trim().length === 0) return true; //empty string\n\n const matches = getAllMatches(attrStr, validAttrStrRegxp);\n const attrNames = {};\n\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][1].length === 0) {\n //nospace before attribute name: a=\"sd\"b=\"saf\"\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' has no space in starting.\", getPositionFromMatch(matches[i]))\n } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' is without value.\", getPositionFromMatch(matches[i]));\n } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {\n //independent attribute: ab\n return getErrorObject('InvalidAttr', \"boolean attribute '\" + matches[i][2] + \"' is not allowed.\", getPositionFromMatch(matches[i]));\n }\n /* else if(matches[i][6] === undefined){//attribute without value: ab=\n return { err: { code:\"InvalidAttr\",msg:\"attribute \" + matches[i][2] + \" has no value assigned.\"}};\n } */\n const attrName = matches[i][2];\n if (!validateAttrName(attrName)) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is an invalid name.\", getPositionFromMatch(matches[i]));\n }\n if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) {\n //check for duplicate attribute.\n attrNames[attrName] = 1;\n } else {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is repeated.\", getPositionFromMatch(matches[i]));\n }\n }\n\n return true;\n}\n\nfunction validateNumberAmpersand(xmlData, i) {\n let re = /\\d/;\n if (xmlData[i] === 'x') {\n i++;\n re = /[\\da-fA-F]/;\n }\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === ';')\n return i;\n if (!xmlData[i].match(re))\n break;\n }\n return -1;\n}\n\nfunction validateAmpersand(xmlData, i) {\n // https://www.w3.org/TR/xml/#dt-charref\n i++;\n if (xmlData[i] === ';')\n return -1;\n if (xmlData[i] === '#') {\n i++;\n return validateNumberAmpersand(xmlData, i);\n }\n let count = 0;\n for (; i < xmlData.length; i++, count++) {\n if (xmlData[i].match(/\\w/) && count < 20)\n continue;\n if (xmlData[i] === ';')\n break;\n return -1;\n }\n return i;\n}\n\nfunction getErrorObject(code, message, lineNumber) {\n return {\n err: {\n code: code,\n msg: message,\n line: lineNumber.line || lineNumber,\n col: lineNumber.col,\n },\n };\n}\n\nfunction validateAttrName(attrName) {\n return isName(attrName);\n}\n\n// const startsWithXML = /^xml/i;\n\nfunction validateTagName(tagname) {\n return isName(tagname) /* && !tagname.match(startsWithXML) */;\n}\n\n//this function returns the line number for the character at the given index\nfunction getLineNumberForPosition(xmlData, index) {\n const lines = xmlData.substring(0, index).split(/\\r?\\n/);\n return {\n line: lines.length,\n\n // column number is last line's length + 1, because column numbering starts at 1:\n col: lines[lines.length - 1].length + 1\n };\n}\n\n//this function returns the position of the first character of match within attrStr\nfunction getPositionFromMatch(match) {\n return match.startIndex + match[1].length;\n}\n","import { buildOptions } from './OptionsBuilder.js';\nimport OrderedObjParser from './OrderedObjParser.js';\nimport prettify from './node2json.js';\nimport { validate } from \"../validator.js\";\nimport XmlNode from './xmlNode.js';\n\nexport default class XMLParser {\n\n constructor(options) {\n this.externalEntities = {};\n this.options = buildOptions(options);\n\n }\n /**\n * Parse XML dats to JS object \n * @param {string|Uint8Array} xmlData \n * @param {boolean|Object} validationOption \n */\n parse(xmlData, validationOption) {\n if (typeof xmlData !== \"string\" && xmlData.toString) {\n xmlData = xmlData.toString();\n } else if (typeof xmlData !== \"string\") {\n throw new Error(\"XML data is accepted in String or Bytes[] form.\")\n }\n\n if (validationOption) {\n if (validationOption === true) validationOption = {}; //validate with default options\n\n const result = validate(xmlData, validationOption);\n if (result !== true) {\n throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`)\n }\n }\n const orderedObjParser = new OrderedObjParser(this.options);\n orderedObjParser.entityDecoder.setExternalEntities(this.externalEntities);\n const orderedResult = orderedObjParser.parseXml(xmlData);\n if (this.options.preserveOrder || orderedResult === undefined) return orderedResult;\n else return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher);\n }\n\n /**\n * Add Entity which is not by default supported by this library\n * @param {string} key \n * @param {string} value \n */\n addEntity(key, value) {\n if (value.indexOf(\"&\") !== -1) {\n throw new Error(\"Entity value can't have '&'\")\n } else if (key.indexOf(\"&\") !== -1 || key.indexOf(\";\") !== -1) {\n throw new Error(\"An entity must be set without '&' and ';'. Eg. use '#xD' for ' '\")\n } else if (value === \"&\") {\n throw new Error(\"An entity with value '&' is not permitted\");\n } else {\n this.externalEntities[key] = value;\n }\n }\n\n /**\n * Returns a Symbol that can be used to access the metadata\n * property on a node.\n * \n * If Symbol is not available in the environment, an ordinary property is used\n * and the name of the property is here returned.\n * \n * The XMLMetaData property is only present when `captureMetaData`\n * is true in the options.\n */\n static getMetaDataSymbol() {\n return XmlNode.getMetaDataSymbol();\n }\n}"],"names":["root","factory","exports","module","define","amd","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","nameStartChar","regexName","RegExp","getAllMatches","string","regex","matches","match","exec","allmatches","startIndex","lastIndex","length","len","index","push","isName","DANGEROUS_PROPERTY_NAMES","criticalProperties","defaultOnDangerousProperty","name","includes","defaultOptions","preserveOrder","attributeNamePrefix","attributesGroupName","textNodeName","ignoreAttributes","removeNSPrefix","allowBooleanAttributes","parseTagValue","parseAttributeValue","trimValues","cdataPropName","numberParseOptions","hex","leadingZeros","eNotation","tagValueProcessor","tagName","val","attributeValueProcessor","attrName","stopNodes","alwaysCreateTextNode","isArray","commentPropName","unpairedTags","processEntities","htmlEntities","entityDecoder","ignoreDeclaration","ignorePiTags","transformTagName","transformAttributeName","updateTag","jPath","attrs","captureMetaData","maxNestedTags","strictReservedNames","onDangerousProperty","validatePropertyName","propertyName","optionName","normalized","toLowerCase","some","dangerous","Error","normalizeProcessEntities","enabled","maxEntitySize","maxExpansionDepth","maxTotalExpansions","Infinity","maxExpandedLength","maxEntityCount","allowedTags","tagFilter","appliesTo","Math","max","_value$maxEntitySize","_value$maxExpansionDe","_value$maxTotalExpans","_value$maxExpandedLen","_value$maxEntityCount","_value$allowedTags","_value$tagFilter","_value$appliesTo","METADATA_SYMBOL","buildOptions","options","built","assign","_i","_propertyNameOptions","_propertyNameOptions$","unpairedTagsSet","Set","Array","map","node","startsWith","substring","XmlNode","tagname","child","create","_proto","add","_this$child$push","addChild","_this$child$push2","_this$child$push3","keys","undefined","getMetaDataSymbol","DocTypeReader","suppressValidationErr","readDocType","xmlData","i","entities","entityCount","angleBracketsCount","hasBody","comment","hasSeq","entityName","_this$readEntityExp","readEntityExp","indexOf","readElementExp","readNotationExp","skipWhitespace","test","validateEntityName","toUpperCase","entityValue","_this$readIdentifierV","readIdentifierVal","notationName","identifierType","publicIdentifier","systemIdentifier","_this$readIdentifierV2","_this$readIdentifierV3","_this$readIdentifierV4","type","identifierVal","startChar","elementName","contentModel","trim","readAttlistExp","attributeName","attributeType","allowedNotations","notation","join","defaultValue","_this$readIdentifierV5","data","seq","j","hexRegex","numRegex","consider","decimalPoint","infinity","eNotationRegx","MatcherView","constructor","matcher","_matcher","separator","getCurrentTag","path","tag","getCurrentNamespace","namespace","getAttrValue","values","hasAttr","current","getPosition","position","getCounter","counter","getIndex","getDepth","toString","includeNamespace","toArray","n","expression","matchesAny","exprSet","Matcher","siblingStacks","_pathStringCache","_view","attrValues","currentLevel","Map","siblings","siblingKey","count","set","pop","updateCurrent","sep","result","reset","segments","hasDeepWildcard","_matchWithDeepWildcard","_matchSimple","_matchSegment","pathIdx","segIdx","segment","nextSeg","found","isCurrentNode","attrValue","String","positionValue","snapshot","restore","readOnly","Expression","pattern","_parse","_hasDeepWildcard","seg","_hasAttributeCondition","_hasPositionSelector","currentPart","_parseSegment","part","bracketContent","withoutBrackets","bracketMatch","content","slice","tagAndPosition","nsIndex","positionMatch","colonIndex","lastIndexOf","tagPart","posPart","eqIndex","nthMatch","parseInt","hasAttributeCondition","hasPositionSelector","ExpressionSet","_byDepthAndTag","_wildcardByDepth","_deepWildcards","_patterns","_sealed","TypeError","has","depth","lastSeg","addAll","expressions","expr","size","seal","isSealed","findMatch","exactKey","exactBucket","wildcardBucket","CURRENCY","cent","pound","curren","yen","euro","dollar","fnof","inr","af","birr","peso","rub","won","yuan","cedil","XML","amp","apos","gt","lt","quot","COMMON_HTML","nbsp","copy","reg","trade","mdash","ndash","hellip","laquo","raquo","lsquo","rsquo","ldquo","rdquo","bull","para","sect","deg","frac12","frac14","frac34","SPECIAL_CHARS","ch","mergeEntityMaps","maps","out","raw","LIMIT_TIER_EXTERNAL","LIMIT_TIER_BASE","LIMIT_TIER_ALL","NCR_LEVEL","freeze","allow","leave","remove","throw","XML10_ALLOWED_C0","EntityDecoder","_limit","limit","_maxTotalExpansions","_maxExpandedLength","_postCheck","postCheck","r","_limitTiers","applyLimitsTo","_numericAllowed","numericAllowed","_baseMap","DEFAULT_XML_ENTITIES","namedEntities","_externalMap","_inputMap","_totalExpansions","_expandedLength","_removeSet","_leaveSet","ncrCfg","ncr","xmlVersion","onLevel","nullLevel","onNCR","nullNCR","parseNCRConfig","_ncrXmlVersion","_ncrOnLevel","_ncrNullLevel","setExternalEntities","addExternalEntity","addInputEntities","setXmlVersion","version","decode","str","original","chunks","last","limitExpansions","limitLength","checkLimits","charCodeAt","token","replacement","tier","ncrResult","_resolveNCR","resolved","_resolveName","_tierCounts","delta","_classifyNCR","cp","_applyNCRAction","action","fromCodePoint","padStart","second","Number","isNaN","minimum","effective","_extends","bind","e","arguments","t","apply","extractRawAttributes","prefixedAttrs","rawAttrs","extractNamespace","rawTagName","ns","OrderedObjParser","currentNode","tagsNodeStack","parseXml","parseTextData","resolveNameSpace","buildAttributesMap","isItStopNode","replaceEntitiesValue","readStopNodeData","saveTextToParentTag","ignoreAttributesFn","_step","_iterator","_createForOfIteratorHelperLoose","done","entityExpansionCount","currentExpandedLength","readonlyMatcher","isCurrentNodeStopNode","stopNodeExpressionsSet","stopNodesOpts","stopNodeExp","dontTrim","hasAttributes","isLeafNode","escapeEntities","jPathOrMatcher","newval","parseValue","tags","split","prefix","charAt","attrsRegx","attrStr","force","processedVals","hasRawAttrs","rawAttrsForMatcher","oldVal","jPathStr","hasAttrs","aName","sanitizeName","newVal","attrCollection","replace","xmlObj","xmlNode","textData","docTypeReader","xmlLen","c1","closeIndex","findClosingIndex","substr","lastTagName","tagData","readTagExp","attsMap","tagExp","ver","childNode","attrExpPresent","endIndex","_ref","_ref2","context","min","_transformTagName","lastTag","isSelfClosing","tagContent","_transformTagName2","entityConfig","parentNode","errMsg","closingIndex","findClosingChar","char","closingChar","attrBoundary","chars","closeCode0","closeCode1","code","fromCharCode","tagExpWithClosingIndex","separatorIndex","search","trimStart","openTagCount","xmllen","shouldParse","trimmedStr","skipLike","numStr","window","parse_int","isFinite","sign","eChar","eAdjacentToLeadingZeros","resolveEnotation","numTrimmedByZeros","decimalAdjacentToLeadingZeros","num","parsedStr","isPositive","handleInfinity","toNumber","fn","newTagName","stripAttributePrefix","prettify","compress","arr","text","compressedObj","tagObj","property","propName","isLeaf","isLeafTag","assignAttributes","attrMap","atrrName","rawAttrName","propCount","isWhiteSpace","readPI","start","getErrorObject","getLineNumberForPosition","readCommentAndCDATA","readAttributeStr","tagClosed","validAttrStrRegxp","validateAttributeString","attrNames","getPositionFromMatch","validateAttrName","validateAmpersand","re","validateNumberAmpersand","message","lineNumber","err","msg","line","col","validateTagName","lines","XMLParser","externalEntities","parse","validationOption","tagFound","reachedRoot","tagStartPos","closingTag","attrStrStart","isValid","otg","openPos","afterAmp","JSON","stringify","validate","orderedObjParser","orderedResult","addEntity"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/lib/fxvalidator.min.js b/node_modules/fast-xml-parser/lib/fxvalidator.min.js new file mode 100644 index 0000000..5d0215b --- /dev/null +++ b/node_modules/fast-xml-parser/lib/fxvalidator.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.XMLValidator=t():e.XMLValidator=t()}(this,()=>(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{validate:()=>l});var r=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=new RegExp("^["+r+"]["+r+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),i=function(e){return!(null==n.exec(e))},a={allowBooleanAttributes:!1,unpairedTags:[]};function l(e,t){t=Object.assign({},a,t);var r=[],n=!1,i=!1;"\ufeff"===e[0]&&(e=e.substr(1));for(var l=0;l"!==e[l]&&" "!==e[l]&&"\t"!==e[l]&&"\n"!==e[l]&&"\r"!==e[l];l++)v+=e[l];if("/"===(v=v.trim())[v.length-1]&&(v=v.substring(0,v.length-1),l--),!m(v))return p("InvalidTag",0===v.trim().length?"Invalid space after '<'.":"Tag '"+v+"' is an invalid name.",F(e,l));var b=d(e,l);if(!1===b)return p("InvalidAttr","Attributes for '"+v+"' have open quote.",F(e,l));var I=b.value;if(l=b.index,"/"===I[I.length-1]){var x=l-I.length,y=c(I=I.substring(0,I.length-1),t);if(!0!==y)return p(y.err.code,y.err.msg,F(e,x+y.err.line));n=!0}else if(g){if(!b.tagClosed)return p("InvalidTag","Closing tag '"+v+"' doesn't have proper closing.",F(e,l));if(I.trim().length>0)return p("InvalidTag","Closing tag '"+v+"' can't have attributes or invalid starting.",F(e,s));if(0===r.length)return p("InvalidTag","Closing tag '"+v+"' has not been opened.",F(e,s));var A=r.pop();if(v!==A.tagName){var C=F(e,A.tagStartPos);return p("InvalidTag","Expected closing tag '"+A.tagName+"' (opened in line "+C.line+", col "+C.col+") instead of closing tag '"+v+"'.",F(e,s))}0==r.length&&(i=!0)}else{var T=c(I,t);if(!0!==T)return p(T.err.code,T.err.msg,F(e,l-I.length+T.err.line));if(!0===i)return p("InvalidXml","Multiple possible root nodes found.",F(e,l));-1!==t.unpairedTags.indexOf(v)||r.push({tagName:v,tagStartPos:s}),n=!0}for(l++;l0)||p("InvalidXml","Invalid '"+JSON.stringify(r.map(function(e){return e.tagName}),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):p("InvalidXml","Start tag expected.",1)}function o(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function u(e,t){for(var r=t;t5&&"xml"===n)return p("InvalidXml","XML declaration allowed only at the start of the document.",F(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}}return t}function f(e,t){if(e.length>t+5&&"-"===e[t+1]&&"-"===e[t+2]){for(t+=3;t"===e[t+2]){t+=2;break}}else if(e.length>t+8&&"D"===e[t+1]&&"O"===e[t+2]&&"C"===e[t+3]&&"T"===e[t+4]&&"Y"===e[t+5]&&"P"===e[t+6]&&"E"===e[t+7]){var r=1;for(t+=8;t"===e[t]&&0===--r)break}else if(e.length>t+9&&"["===e[t+1]&&"C"===e[t+2]&&"D"===e[t+3]&&"A"===e[t+4]&&"T"===e[t+5]&&"A"===e[t+6]&&"["===e[t+7])for(t+=8;t"===e[t+2]){t+=2;break}return t}var s='"',g="'";function d(e,t){for(var r="",n="",i=!1;t"===e[t]&&""===n){i=!0;break}r+=e[t]}return""===n&&{value:r,index:t,tagClosed:i}}var v=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function c(e,t){for(var r=function(e,t){for(var r=[],n=t.exec(e);n;){var i=[];i.startIndex=t.lastIndex-n[0].length;for(var a=n.length,l=0;l {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","'use strict';\n\nconst nameStartChar = ':A-Za-z_\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD';\nconst nameChar = nameStartChar + '\\\\-.\\\\d\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040';\nexport const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*';\nconst regexName = new RegExp('^' + nameRegexp + '$');\n\nexport function getAllMatches(string, regex) {\n const matches = [];\n let match = regex.exec(string);\n while (match) {\n const allmatches = [];\n allmatches.startIndex = regex.lastIndex - match[0].length;\n const len = match.length;\n for (let index = 0; index < len; index++) {\n allmatches.push(match[index]);\n }\n matches.push(allmatches);\n match = regex.exec(string);\n }\n return matches;\n}\n\nexport const isName = function (string) {\n const match = regexName.exec(string);\n return !(match === null || typeof match === 'undefined');\n}\n\nexport function isExist(v) {\n return typeof v !== 'undefined';\n}\n\nexport function isEmptyObject(obj) {\n return Object.keys(obj).length === 0;\n}\n\nexport function getValue(v) {\n if (exports.isExist(v)) {\n return v;\n } else {\n return '';\n }\n}\n\n/**\n * Dangerous property names that could lead to prototype pollution or security issues\n */\nexport const DANGEROUS_PROPERTY_NAMES = [\n // '__proto__',\n // 'constructor',\n // 'prototype',\n 'hasOwnProperty',\n 'toString',\n 'valueOf',\n '__defineGetter__',\n '__defineSetter__',\n '__lookupGetter__',\n '__lookupSetter__'\n];\n\nexport const criticalProperties = [\"__proto__\", \"constructor\", \"prototype\"];","'use strict';\n\nimport { getAllMatches, isName } from './util.js';\n\nconst defaultOptions = {\n allowBooleanAttributes: false, //A tag can have attributes without any value\n unpairedTags: []\n};\n\n//const tagsPattern = new RegExp(\"<\\\\/?([\\\\w:\\\\-_\\.]+)\\\\s*\\/?>\",\"g\");\nexport function validate(xmlData, options) {\n options = Object.assign({}, defaultOptions, options);\n\n //xmlData = xmlData.replace(/(\\r\\n|\\n|\\r)/gm,\"\");//make it single line\n //xmlData = xmlData.replace(/(^\\s*<\\?xml.*?\\?>)/g,\"\");//Remove XML starting tag\n //xmlData = xmlData.replace(/()/g,\"\");//Remove DOCTYPE\n const tags = [];\n let tagFound = false;\n\n //indicates that the root tag has been closed (aka. depth 0 has been reached)\n let reachedRoot = false;\n\n if (xmlData[0] === '\\ufeff') {\n // check for byte order mark (BOM)\n xmlData = xmlData.substr(1);\n }\n\n for (let i = 0; i < xmlData.length; i++) {\n\n if (xmlData[i] === '<' && xmlData[i + 1] === '?') {\n i += 2;\n i = readPI(xmlData, i);\n if (i.err) return i;\n } else if (xmlData[i] === '<') {\n //starting of tag\n //read until you reach to '>' avoiding any '>' in attribute value\n let tagStartPos = i;\n i++;\n\n if (xmlData[i] === '!') {\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else {\n let closingTag = false;\n if (xmlData[i] === '/') {\n //closing tag\n closingTag = true;\n i++;\n }\n //read tagname\n let tagName = '';\n for (; i < xmlData.length &&\n xmlData[i] !== '>' &&\n xmlData[i] !== ' ' &&\n xmlData[i] !== '\\t' &&\n xmlData[i] !== '\\n' &&\n xmlData[i] !== '\\r'; i++\n ) {\n tagName += xmlData[i];\n }\n tagName = tagName.trim();\n //console.log(tagName);\n\n if (tagName[tagName.length - 1] === '/') {\n //self closing tag without attributes\n tagName = tagName.substring(0, tagName.length - 1);\n //continue;\n i--;\n }\n if (!validateTagName(tagName)) {\n let msg;\n if (tagName.trim().length === 0) {\n msg = \"Invalid space after '<'.\";\n } else {\n msg = \"Tag '\" + tagName + \"' is an invalid name.\";\n }\n return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));\n }\n\n const result = readAttributeStr(xmlData, i);\n if (result === false) {\n return getErrorObject('InvalidAttr', \"Attributes for '\" + tagName + \"' have open quote.\", getLineNumberForPosition(xmlData, i));\n }\n let attrStr = result.value;\n i = result.index;\n\n if (attrStr[attrStr.length - 1] === '/') {\n //self closing tag\n const attrStrStart = i - attrStr.length;\n attrStr = attrStr.substring(0, attrStr.length - 1);\n const isValid = validateAttributeString(attrStr, options);\n if (isValid === true) {\n tagFound = true;\n //continue; //text may presents after self closing tag\n } else {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));\n }\n } else if (closingTag) {\n if (!result.tagClosed) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' doesn't have proper closing.\", getLineNumberForPosition(xmlData, i));\n } else if (attrStr.trim().length > 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' can't have attributes or invalid starting.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else if (tags.length === 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' has not been opened.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else {\n const otg = tags.pop();\n if (tagName !== otg.tagName) {\n let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);\n return getErrorObject('InvalidTag',\n \"Expected closing tag '\" + otg.tagName + \"' (opened in line \" + openPos.line + \", col \" + openPos.col + \") instead of closing tag '\" + tagName + \"'.\",\n getLineNumberForPosition(xmlData, tagStartPos));\n }\n\n //when there are no more tags, we reached the root level.\n if (tags.length == 0) {\n reachedRoot = true;\n }\n }\n } else {\n const isValid = validateAttributeString(attrStr, options);\n if (isValid !== true) {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));\n }\n\n //if the root level has been reached before ...\n if (reachedRoot === true) {\n return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));\n } else if (options.unpairedTags.indexOf(tagName) !== -1) {\n //don't push into stack\n } else {\n tags.push({ tagName, tagStartPos });\n }\n tagFound = true;\n }\n\n //skip tag text value\n //It may include comments and CDATA value\n for (i++; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n if (xmlData[i + 1] === '!') {\n //comment or CADATA\n i++;\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else if (xmlData[i + 1] === '?') {\n i = readPI(xmlData, ++i);\n if (i.err) return i;\n } else {\n break;\n }\n } else if (xmlData[i] === '&') {\n const afterAmp = validateAmpersand(xmlData, i);\n if (afterAmp == -1)\n return getErrorObject('InvalidChar', \"char '&' is not expected.\", getLineNumberForPosition(xmlData, i));\n i = afterAmp;\n } else {\n if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {\n return getErrorObject('InvalidXml', \"Extra text at the end\", getLineNumberForPosition(xmlData, i));\n }\n }\n } //end of reading tag text value\n if (xmlData[i] === '<') {\n i--;\n }\n }\n } else {\n if (isWhiteSpace(xmlData[i])) {\n continue;\n }\n return getErrorObject('InvalidChar', \"char '\" + xmlData[i] + \"' is not expected.\", getLineNumberForPosition(xmlData, i));\n }\n }\n\n if (!tagFound) {\n return getErrorObject('InvalidXml', 'Start tag expected.', 1);\n } else if (tags.length == 1) {\n return getErrorObject('InvalidTag', \"Unclosed tag '\" + tags[0].tagName + \"'.\", getLineNumberForPosition(xmlData, tags[0].tagStartPos));\n } else if (tags.length > 0) {\n return getErrorObject('InvalidXml', \"Invalid '\" +\n JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\\r?\\n/g, '') +\n \"' found.\", { line: 1, col: 1 });\n }\n\n return true;\n};\n\nfunction isWhiteSpace(char) {\n return char === ' ' || char === '\\t' || char === '\\n' || char === '\\r';\n}\n/**\n * Read Processing insstructions and skip\n * @param {*} xmlData\n * @param {*} i\n */\nfunction readPI(xmlData, i) {\n const start = i;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] == '?' || xmlData[i] == ' ') {\n //tagname\n const tagname = xmlData.substr(start, i - start);\n if (i > 5 && tagname === 'xml') {\n return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));\n } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {\n //check if valid attribut string\n i++;\n break;\n } else {\n continue;\n }\n }\n }\n return i;\n}\n\nfunction readCommentAndCDATA(xmlData, i) {\n if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {\n //comment\n for (i += 3; i < xmlData.length; i++) {\n if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n } else if (\n xmlData.length > i + 8 &&\n xmlData[i + 1] === 'D' &&\n xmlData[i + 2] === 'O' &&\n xmlData[i + 3] === 'C' &&\n xmlData[i + 4] === 'T' &&\n xmlData[i + 5] === 'Y' &&\n xmlData[i + 6] === 'P' &&\n xmlData[i + 7] === 'E'\n ) {\n let angleBracketsCount = 1;\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n angleBracketsCount++;\n } else if (xmlData[i] === '>') {\n angleBracketsCount--;\n if (angleBracketsCount === 0) {\n break;\n }\n }\n }\n } else if (\n xmlData.length > i + 9 &&\n xmlData[i + 1] === '[' &&\n xmlData[i + 2] === 'C' &&\n xmlData[i + 3] === 'D' &&\n xmlData[i + 4] === 'A' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'A' &&\n xmlData[i + 7] === '['\n ) {\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n }\n\n return i;\n}\n\nconst doubleQuote = '\"';\nconst singleQuote = \"'\";\n\n/**\n * Keep reading xmlData until '<' is found outside the attribute value.\n * @param {string} xmlData\n * @param {number} i\n */\nfunction readAttributeStr(xmlData, i) {\n let attrStr = '';\n let startChar = '';\n let tagClosed = false;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {\n if (startChar === '') {\n startChar = xmlData[i];\n } else if (startChar !== xmlData[i]) {\n //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa\n } else {\n startChar = '';\n }\n } else if (xmlData[i] === '>') {\n if (startChar === '') {\n tagClosed = true;\n break;\n }\n }\n attrStr += xmlData[i];\n }\n if (startChar !== '') {\n return false;\n }\n\n return {\n value: attrStr,\n index: i,\n tagClosed: tagClosed\n };\n}\n\n/**\n * Select all the attributes whether valid or invalid.\n */\nconst validAttrStrRegxp = new RegExp('(\\\\s*)([^\\\\s=]+)(\\\\s*=)?(\\\\s*([\\'\"])(([\\\\s\\\\S])*?)\\\\5)?', 'g');\n\n//attr, =\"sd\", a=\"amit's\", a=\"sd\"b=\"saf\", ab cd=\"\"\n\nfunction validateAttributeString(attrStr, options) {\n //console.log(\"start:\"+attrStr+\":end\");\n\n //if(attrStr.trim().length === 0) return true; //empty string\n\n const matches = getAllMatches(attrStr, validAttrStrRegxp);\n const attrNames = {};\n\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][1].length === 0) {\n //nospace before attribute name: a=\"sd\"b=\"saf\"\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' has no space in starting.\", getPositionFromMatch(matches[i]))\n } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' is without value.\", getPositionFromMatch(matches[i]));\n } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {\n //independent attribute: ab\n return getErrorObject('InvalidAttr', \"boolean attribute '\" + matches[i][2] + \"' is not allowed.\", getPositionFromMatch(matches[i]));\n }\n /* else if(matches[i][6] === undefined){//attribute without value: ab=\n return { err: { code:\"InvalidAttr\",msg:\"attribute \" + matches[i][2] + \" has no value assigned.\"}};\n } */\n const attrName = matches[i][2];\n if (!validateAttrName(attrName)) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is an invalid name.\", getPositionFromMatch(matches[i]));\n }\n if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) {\n //check for duplicate attribute.\n attrNames[attrName] = 1;\n } else {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is repeated.\", getPositionFromMatch(matches[i]));\n }\n }\n\n return true;\n}\n\nfunction validateNumberAmpersand(xmlData, i) {\n let re = /\\d/;\n if (xmlData[i] === 'x') {\n i++;\n re = /[\\da-fA-F]/;\n }\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === ';')\n return i;\n if (!xmlData[i].match(re))\n break;\n }\n return -1;\n}\n\nfunction validateAmpersand(xmlData, i) {\n // https://www.w3.org/TR/xml/#dt-charref\n i++;\n if (xmlData[i] === ';')\n return -1;\n if (xmlData[i] === '#') {\n i++;\n return validateNumberAmpersand(xmlData, i);\n }\n let count = 0;\n for (; i < xmlData.length; i++, count++) {\n if (xmlData[i].match(/\\w/) && count < 20)\n continue;\n if (xmlData[i] === ';')\n break;\n return -1;\n }\n return i;\n}\n\nfunction getErrorObject(code, message, lineNumber) {\n return {\n err: {\n code: code,\n msg: message,\n line: lineNumber.line || lineNumber,\n col: lineNumber.col,\n },\n };\n}\n\nfunction validateAttrName(attrName) {\n return isName(attrName);\n}\n\n// const startsWithXML = /^xml/i;\n\nfunction validateTagName(tagname) {\n return isName(tagname) /* && !tagname.match(startsWithXML) */;\n}\n\n//this function returns the line number for the character at the given index\nfunction getLineNumberForPosition(xmlData, index) {\n const lines = xmlData.substring(0, index).split(/\\r?\\n/);\n return {\n line: lines.length,\n\n // column number is last line's length + 1, because column numbering starts at 1:\n col: lines[lines.length - 1].length + 1\n };\n}\n\n//this function returns the position of the first character of match within attrStr\nfunction getPositionFromMatch(match) {\n return match.startIndex + match[1].length;\n}\n"],"names":["root","factory","exports","module","define","amd","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","nameStartChar","regexName","RegExp","isName","string","exec","defaultOptions","allowBooleanAttributes","unpairedTags","validate","xmlData","options","assign","tags","tagFound","reachedRoot","substr","i","length","readPI","err","isWhiteSpace","getErrorObject","getLineNumberForPosition","tagStartPos","readCommentAndCDATA","closingTag","tagName","trim","substring","validateTagName","result","readAttributeStr","attrStr","index","attrStrStart","isValid","validateAttributeString","code","msg","line","tagClosed","otg","pop","openPos","col","indexOf","push","afterAmp","validateAmpersand","JSON","stringify","map","t","replace","char","start","tagname","angleBracketsCount","doubleQuote","singleQuote","startChar","validAttrStrRegxp","matches","regex","match","allmatches","startIndex","lastIndex","len","getAllMatches","attrNames","getPositionFromMatch","undefined","attrName","validateAttrName","re","validateNumberAmpersand","count","message","lineNumber","lines","split"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/package.json b/node_modules/fast-xml-parser/package.json new file mode 100644 index 0000000..ded1d5f --- /dev/null +++ b/node_modules/fast-xml-parser/package.json @@ -0,0 +1,95 @@ +{ + "name": "fast-xml-parser", + "version": "5.7.1", + "description": "Validate XML, Parse XML, Build XML without C/C++ based libraries", + "main": "./lib/fxp.cjs", + "type": "module", + "sideEffects": false, + "module": "./src/fxp.js", + "types": "./src/fxp.d.ts", + "exports": { + ".": { + "import": { + "types": "./src/fxp.d.ts", + "default": "./src/fxp.js" + }, + "require": { + "types": "./lib/fxp.d.cts", + "default": "./lib/fxp.cjs" + } + } + }, + "scripts": { + "test": "c8 --reporter=lcov --reporter=text jasmine spec/*spec.js", + "test-types": "tsc --noEmit spec/typings/typings-test.ts", + "unit": "jasmine", + "coverage": "nyc report --reporter html --reporter text -t .nyc_output --report-dir .nyc_output/summary", + "perf": "node ./benchmark/perfTest3.js", + "lint": "eslint src/**/*.js spec/**/*.js benchmark/**/*.js", + "bundle": "webpack --config webpack.cjs.config.js", + "prettier": "prettier --write src/**/*.js", + "checkReadiness": "publish-please --dry-run", + "publish-please": "publish-please", + "prepublishOnly": "publish-please guard" + }, + "bin": { + "fxparser": "src/cli/cli.js" + }, + "files": [ + "lib", + "src", + "CHANGELOG.md" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/NaturalIntelligence/fast-xml-parser.git" + }, + "keywords": [ + "fast", + "xml", + "json", + "parser", + "xml2js", + "x2js", + "xml2json", + "js", + "validator", + "validate", + "transformer", + "assert", + "js2xml", + "json2xml", + "html" + ], + "author": "Amit Gupta (https://solothought.com)", + "license": "MIT", + "devDependencies": { + "@babel/core": "^7.13.10", + "@babel/plugin-transform-runtime": "^7.13.10", + "@babel/preset-env": "^7.13.10", + "@babel/register": "^7.13.8", + "@types/node": "20", + "babel-loader": "^8.2.2", + "c8": "^10.1.3", + "eslint": "^8.3.0", + "he": "^1.2.0", + "jasmine": "^5.6.0", + "prettier": "^3.5.1", + "publish-please": "^5.5.2", + "typescript": "5", + "webpack": "^5.64.4", + "webpack-cli": "^4.9.1" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "dependencies": { + "@nodable/entities": "^2.1.0", + "fast-xml-builder": "^1.1.5", + "path-expression-matcher": "^1.5.0", + "strnum": "^2.2.3" + } +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/cli/cli.js b/node_modules/fast-xml-parser/src/cli/cli.js new file mode 100644 index 0000000..b4773e4 --- /dev/null +++ b/node_modules/fast-xml-parser/src/cli/cli.js @@ -0,0 +1,97 @@ +#!/usr/bin/env node +'use strict'; +/*eslint-disable no-console*/ +import fs from 'fs'; +import { resolve } from 'path'; +import {XMLParser, XMLValidator} from "../fxp.js"; +import ReadToEnd from './read.js'; +import cmdDetail from "./man.js" + +console.warn("\x1b[33m%s\x1b[0m", "⚠️ Warning: The built-in CLI interface is now deprecated."); +console.warn("Please install the dedicated CLI package instead:"); +console.warn(" npm install -g fxp-cli"); + +if (process.argv[2] === '--help' || process.argv[2] === '-h') { + console.log(cmdDetail); +} else if (process.argv[2] === '--version') { + const packageJsonPath = resolve(process.cwd(), 'package.json'); + const version = JSON.parse(fs.readFileSync(packageJsonPath).toString()).version; + console.log(version); +} else { + const options = { + removeNSPrefix: true, + ignoreAttributes: false, + parseTagValue: true, + parseAttributeValue: true, + }; + let fileName = ''; + let outputFileName; + let validate = false; + let validateOnly = false; + for (let i = 2; i < process.argv.length; i++) { + if (process.argv[i] === '-ns') { + options.removeNSPrefix = false; + } else if (process.argv[i] === '-a') { + options.ignoreAttributes = true; + } else if (process.argv[i] === '-c') { + options.parseTagValue = false; + options.parseAttributeValue = false; + } else if (process.argv[i] === '-o') { + outputFileName = process.argv[++i]; + } else if (process.argv[i] === '-v') { + validate = true; + } else if (process.argv[i] === '-V') { + validateOnly = true; + } else { + //filename + fileName = process.argv[i]; + } + } + + const callback = function(xmlData) { + let output = ''; + if (validateOnly) { + output = XMLValidator.validate(xmlData); + process.exitCode = output === true ? 0 : 1; + } else { + const parser = new XMLParser(options); + output = JSON.stringify(parser.parse(xmlData,validate), null, 4); + } + if (outputFileName) { + writeToFile(outputFileName, output); + } else { + console.log(output); + } + }; + + + try { + + if (!fileName) { + ReadToEnd.readToEnd(process.stdin, function(err, data) { + if (err) { + throw err; + } + callback(data.toString()); + }); + } else { + fs.readFile(fileName, function(err, data) { + if (err) { + throw err; + } + callback(data.toString()); + }); + } + } catch (e) { + console.log('Seems an invalid file or stream.' + e); + } +} + +function writeToFile(fileName, data) { + fs.writeFile(fileName, data, function(err) { + if (err) { + throw err; + } + console.log('JSON output has been written to ' + fileName); + }); +} diff --git a/node_modules/fast-xml-parser/src/cli/man.js b/node_modules/fast-xml-parser/src/cli/man.js new file mode 100644 index 0000000..418ea3d --- /dev/null +++ b/node_modules/fast-xml-parser/src/cli/man.js @@ -0,0 +1,17 @@ +import fs from 'fs'; +import { resolve } from 'path'; +const packageJsonPath = resolve(process.cwd(), 'package.json'); +const version = JSON.parse(fs.readFileSync(packageJsonPath).toString()).version; + +export default `Fast XML Parser ${version} +---------------- +$ fxparser [-ns|-a|-c|-v|-V] [-o outputfile.json] +$ cat xmlfile.xml | fxparser [-ns|-a|-c|-v|-V] [-o outputfile.json] + +Options +---------------- +-ns: remove namespace from tag and atrribute name. +-a: don't parse attributes. +-c: parse values to premitive type. +-v: validate before parsing. +-V: validate only.` \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/cli/read.js b/node_modules/fast-xml-parser/src/cli/read.js new file mode 100644 index 0000000..99a2066 --- /dev/null +++ b/node_modules/fast-xml-parser/src/cli/read.js @@ -0,0 +1,43 @@ +'use strict'; + +import { Transform } from 'stream'; + +export default class ReadToEnd extends Transform { + constructor(options = {}) { + super(options); + this._encoding = options.encoding || 'utf8'; + this._buffer = ''; + } + + _transform(chunk, encoding, done) { + this._buffer += chunk.toString(this._encoding); + this.push(chunk); + done(); + } + + _flush(done) { + this.emit('complete', null, this._buffer); + done(); + } + + static readToEnd(stream, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + const dest = new ReadToEnd(options); + + stream.pipe(dest); + + stream.on('error', (err) => { + stream.unpipe(dest); + callback(err); + }); + + dest.on('complete', callback); + dest.resume(); + + return dest; + } +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/fxp.d.ts b/node_modules/fast-xml-parser/src/fxp.d.ts new file mode 100644 index 0000000..e979811 --- /dev/null +++ b/node_modules/fast-xml-parser/src/fxp.d.ts @@ -0,0 +1,738 @@ +/** + * Types copied from path-expression-matcher + * @version + * @updated + * + * Update this file when path-expression-matcher releases a new version. + * Source: https://github.com/NaturalIntelligence/path-expression-matcher + */ + +/** + * Options for creating an Expression + */ +export interface ExpressionOptions { + /** + * Path separator character + * @default '.' + */ + separator?: string; +} + +/** + * Parsed segment from an expression pattern + */ +export interface Segment { + type: 'tag' | 'deep-wildcard'; + tag?: string; + namespace?: string; + attrName?: string; + attrValue?: string; + position?: 'first' | 'last' | 'odd' | 'even' | 'nth'; + positionValue?: number; +} + +/** + * Expression - Parses and stores a tag pattern expression. + * Patterns are parsed once and stored in an optimized structure for fast matching. + * + * @example + * ```typescript + * const expr = new Expression("root.users.user"); + * const expr2 = new Expression("..user[id]:first"); + * const expr3 = new Expression("root/users/user", { separator: '/' }); + * ``` + * + * Pattern Syntax: + * - `root.users.user` — Match exact path + * - `..user` — Match "user" at any depth (deep wildcard) + * - `user[id]` — Match user tag with "id" attribute + * - `user[id=123]` — Match user tag where id="123" + * - `user:first` — Match first occurrence of user tag + * - `ns::user` — Match user tag with namespace "ns" + * - `ns::user[id]:first` — Combine namespace, attribute, and position + */ +export class Expression { + readonly pattern: string; + readonly separator: string; + readonly segments: Segment[]; + + constructor(pattern: string, options?: ExpressionOptions); + + get length(): number; + hasDeepWildcard(): boolean; + hasAttributeCondition(): boolean; + hasPositionSelector(): boolean; + toString(): string; +} + +// --------------------------------------------------------------------------- +// MatcherView +// --------------------------------------------------------------------------- + +/** + * A lightweight, live read-only view of a Matcher instance. + * + * Returned by `Matcher.readOnly()`. The same instance is reused across every + * callback invocation — no allocation overhead per call. Reads directly from + * the parent Matcher's internal state so it always reflects the current parser + * position with no copying or freezing. + * + * Mutation methods (`push`, `pop`, `reset`, `updateCurrent`, `restore`) are + * simply absent — misuse is caught at compile time by TypeScript. + * + * This is the type received by all FXP user callbacks when `jPath: false`. + */ +export class MatcherView { + readonly separator: string; + + /** Check if current path matches an Expression. */ + matches(expression: Expression): boolean; + + /** Get current tag name, or `undefined` if path is empty. */ + getCurrentTag(): string | undefined; + + /** Get current namespace, or `undefined` if not present. */ + getCurrentNamespace(): string | undefined; + + /** Get attribute value of the current node. */ + getAttrValue(attrName: string): any; + + /** Check if the current node has a given attribute. */ + hasAttr(attrName: string): boolean; + + /** Sibling position of the current node (child index in parent). */ + getPosition(): number; + + /** Occurrence counter of the current tag name at this level. */ + getCounter(): number; + + /** Number of nodes in the current path. */ + getDepth(): number; + + /** Current path as a string (e.g. `"root.users.user"`). */ + toString(separator?: string, includeNamespace?: boolean): string; + + /** Current path as an array of tag names. */ + toArray(): string[]; +} + +/** + * @deprecated Use {@link MatcherView} instead. + * Alias kept for backward compatibility. + */ +export type ReadonlyMatcher = MatcherView; + +/** Internal node structure — exposed via snapshot only. */ +export interface PathNode { + tag: string; + namespace?: string; + position: number; + counter: number; + values?: Record; +} + +/** Snapshot of matcher state returned by `snapshot()` and `readOnly().snapshot()`. */ +export interface MatcherSnapshot { + path: PathNode[]; + siblingStacks: Map[]; +} + +/********************************************************************** + * + * END of path-expression-matcher relevant typings + * + **********************************************************************/ + +// jPath: true → string +// jPath: false → MatcherView +type JPathOrMatcher = string | MatcherView; +type JPathOrExpression = string | Expression; + +export type ProcessEntitiesOptions = { + /** + * Whether to enable entity processing + * + * Defaults to `true` + */ + enabled?: boolean; + + /** + * Maximum size in characters for a single entity definition + * + * Defaults to `10000` + */ + maxEntitySize?: number; + + /** + * Maximum depth for nested entity references (reserved for future use) + * + * Defaults to `10` + */ + maxExpansionDepth?: number; + + /** + * Maximum total number of entity expansions allowed + * + * Defaults to `1000` + */ + maxTotalExpansions?: number; + + /** + * Maximum total expanded content length in characters + * + * Defaults to `100000` + */ + maxExpandedLength?: number; + + /** + * Maximum number of entities allowed in the XML + * + * Defaults to `100` + */ + maxEntityCount?: number; + + /** + * Array of tag names where entity replacement is allowed. + * If null, entities are replaced in all tags. + * + * Defaults to `null` + */ + allowedTags?: string[] | null; + + /** + * Custom filter function to determine if entities should be replaced in a tag + * + * @param tagName - The name of the current tag + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @returns `true` to allow entity replacement, `false` to skip + * + * Defaults to `null` + */ + tagFilter?: ((tagName: string, jPathOrMatcher: JPathOrMatcher) => boolean) | null; +}; + +export type EntityDecoderOptions = { + setExternalEntities: (entities: Record) => void; + addInputEntities: (entities: Record) => void; + reset: () => void; + decode: (text: string) => string; + setXmlVersion: (version: string) => void; +} + +export type X2jOptions = { + /** + * Preserve the order of tags in resulting JS object + * + * Defaults to `false` + */ + preserveOrder?: boolean; + + /** + * Give a prefix to the attribute name in the resulting JS object + * + * Defaults to '@_' + */ + attributeNamePrefix?: string; + + /** + * A name to group all attributes of a tag under, or `false` to disable + * + * Defaults to `false` + */ + attributesGroupName?: false | string; + + /** + * The name of the next node in the resulting JS + * + * Defaults to `#text` + */ + textNodeName?: string; + + /** + * Whether to ignore attributes when parsing + * + * When `true` - ignores all the attributes + * + * When `false` - parses all the attributes + * + * When `Array` - filters out attributes that match provided patterns + * + * When `Function` - calls the function for each attribute and filters out those for which the function returned `true` + * + * Defaults to `true` + */ + ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPathOrMatcher: JPathOrMatcher) => boolean); + + /** + * Whether to remove namespace string from tag and attribute names + * + * Defaults to `false` + */ + removeNSPrefix?: boolean; + + /** + * Whether to allow attributes without value + * + * Defaults to `false` + */ + allowBooleanAttributes?: boolean; + + /** + * Whether to parse tag value with `strnum` package + * + * Defaults to `true` + */ + parseTagValue?: boolean; + + /** + * Whether to parse attribute value with `strnum` package + * + * Defaults to `false` + */ + parseAttributeValue?: boolean; + + /** + * Whether to remove surrounding whitespace from tag or attribute value + * + * Defaults to `true` + */ + trimValues?: boolean; + + /** + * Give a property name to set CDATA values to instead of merging to tag's text value + * + * Defaults to `false` + */ + cdataPropName?: false | string; + + /** + * If set, parse comments and set as this property + * + * Defaults to `false` + */ + commentPropName?: false | string; + + /** + * Control how tag value should be parsed. Called only if tag value is not empty + * + * @param tagName - The name of the tag + * @param tagValue - The value of the tag + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @param hasAttributes - Whether the tag has attributes + * @param isLeafNode - Whether the tag is a leaf node + * @returns {undefined|null} `undefined` or `null` to set original value. + * @returns {unknown} + * + * 1. Different value or value with different data type to set new value. + * 2. Same value to set parsed value if `parseTagValue: true`. + * + * Defaults to `(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode) => val` + */ + tagValueProcessor?: (tagName: string, tagValue: string, jPathOrMatcher: JPathOrMatcher, hasAttributes: boolean, isLeafNode: boolean) => unknown; + + /** + * Control how attribute value should be parsed + * + * @param attrName - The name of the attribute + * @param attrValue - The value of the attribute + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @returns {undefined|null} `undefined` or `null` to set original value + * @returns {unknown} + * + * Defaults to `(attrName, val, jPathOrMatcher) => val` + */ + attributeValueProcessor?: (attrName: string, attrValue: string, jPathOrMatcher: JPathOrMatcher) => unknown; + + /** + * Options to pass to `strnum` for parsing numbers + * + * Defaults to `{ hex: true, leadingZeros: true, eNotation: true }` + */ + numberParseOptions?: strnumOptions; + + /** + * Nodes to stop parsing at + * + * Accepts string patterns or Expression objects from path-expression-matcher + * + * String patterns starting with "*." are automatically converted to ".." for backward compatibility + * + * Defaults to `[]` + */ + stopNodes?: JPathOrExpression[]; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; + + /** + * Whether to always create a text node + * + * Defaults to `false` + */ + alwaysCreateTextNode?: boolean; + + /** + * Determine whether a tag should be parsed as an array + * + * @param tagName - The name of the tag + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @param isLeafNode - Whether the tag is a leaf node + * @param isAttribute - Whether this is an attribute + * @returns {boolean} + * + * Defaults to `() => false` + */ + isArray?: (tagName: string, jPathOrMatcher: JPathOrMatcher, isLeafNode: boolean, isAttribute: boolean) => boolean; + + /** + * Whether to process default and DOCTYPE entities + * + * When `true` - enables entity processing with default limits + * + * When `false` - disables all entity processing + * + * When `ProcessEntitiesOptions` - enables entity processing with custom configuration + * + * Defaults to `true` + */ + processEntities?: boolean | ProcessEntitiesOptions; + + /** + * Whether to process HTML entities + * + * Defaults to `false` + * @deprecated Use `entityDecoder` instead + */ + htmlEntities?: boolean; + + /** + * Custom entity decoder + */ + entityDecoder?: EntityDecoderOptions; + /** + * Whether to ignore the declaration tag from output + * + * Defaults to `false` + */ + ignoreDeclaration?: boolean; + + /** + * Whether to ignore Pi tags + * + * Defaults to `false` + */ + ignorePiTags?: boolean; + + /** + * Transform tag names + * + * Defaults to `false` + */ + transformTagName?: ((tagName: string) => string) | false; + + /** + * Transform attribute names + * + * Defaults to `false` + */ + transformAttributeName?: ((attributeName: string) => string) | false; + + /** + * Change the tag name when a different name is returned. Skip the tag from parsed result when false is returned. + * Modify `attrs` object to control attributes for the given tag. + * + * @param tagName - The name of the tag + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @param attrs - The attributes object + * @returns {string} new tag name. + * @returns false to skip the tag + * + * Defaults to `(tagName, jPathOrMatcher, attrs) => tagName` + */ + updateTag?: (tagName: string, jPathOrMatcher: JPathOrMatcher, attrs: { [k: string]: string }) => string | boolean; + + /** + * If true, adds a Symbol to all object nodes, accessible by {@link XMLParser.getMetaDataSymbol} with + * metadata about each the node in the XML file. + */ + captureMetaData?: boolean; + + /** + * Maximum number of nested tags + * + * Defaults to `100` + */ + maxNestedTags?: number; + + /** + * Whether to strictly validate tag names + * + * Defaults to `true` + */ + strictReservedNames?: boolean; + + /** + * Controls whether callbacks receive jPath as string or Matcher instance + * + * When `true` - callbacks receive jPath as string (backward compatible) + * + * When `false` - callbacks receive Matcher instance for advanced pattern matching + * + * Defaults to `true` + */ + jPath?: boolean; + + /** + * Function to sanitize dangerous property names + * + * @param name - The name of the property + * @returns {string} The sanitized name + * + * Defaults to `(name) => __name` + */ + onDangerousProperty?: (name: string) => string; +}; + + + +export type strnumOptions = { + hex: boolean; + leadingZeros: boolean, + skipLike?: RegExp, + eNotation?: boolean +} + +export type validationOptions = { + /** + * Whether to allow attributes without value + * + * Defaults to `false` + */ + allowBooleanAttributes?: boolean; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; +}; + +export type XmlBuilderOptions = { + /** + * Give a prefix to the attribute name in the resulting JS object + * + * Defaults to '@_' + */ + attributeNamePrefix?: string; + + /** + * A name to group all attributes of a tag under, or `false` to disable + * + * Defaults to `false` + */ + attributesGroupName?: false | string; + + /** + * The name of the next node in the resulting JS + * + * Defaults to `#text` + */ + textNodeName?: string; + + /** + * Whether to ignore attributes when building + * + * When `true` - ignores all the attributes + * + * When `false` - builds all the attributes + * + * When `Array` - filters out attributes that match provided patterns + * + * When `Function` - calls the function for each attribute and filters out those for which the function returned `true` + * + * Defaults to `true` + */ + ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean); + + /** + * Give a property name to set CDATA values to instead of merging to tag's text value + * + * Defaults to `false` + */ + cdataPropName?: false | string; + + /** + * If set, parse comments and set as this property + * + * Defaults to `false` + */ + commentPropName?: false | string; + + /** + * Whether to make output pretty instead of single line + * + * Defaults to `false` + */ + format?: boolean; + + + /** + * If `format` is set to `true`, sets the indent string + * + * Defaults to ` ` + */ + indentBy?: string; + + /** + * Give a name to a top-level array + * + * Defaults to `undefined` + */ + arrayNodeName?: string; + + /** + * Create empty tags for tags with no text value + * + * Defaults to `false` + */ + suppressEmptyNode?: boolean; + + /** + * Suppress an unpaired tag + * + * Defaults to `true` + */ + suppressUnpairedNode?: boolean; + + /** + * Don't put a value for boolean attributes + * + * Defaults to `true` + */ + suppressBooleanAttributes?: boolean; + + /** + * Preserve the order of tags in resulting JS object + * + * Defaults to `false` + */ + preserveOrder?: boolean; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; + + /** + * Nodes to stop parsing at + * + * Accepts string patterns or Expression objects from path-expression-matcher + * + * Defaults to `[]` + */ + stopNodes?: JPathOrExpression[]; + + /** + * Control how tag value should be parsed. Called only if tag value is not empty + * + * @returns {undefined|null} `undefined` or `null` to set original value. + * @returns {unknown} + * + * 1. Different value or value with different data type to set new value. + * 2. Same value to set parsed value if `parseTagValue: true`. + * + * Defaults to `(tagName, val, jPath, hasAttributes, isLeafNode) => val` + */ + tagValueProcessor?: (name: string, value: unknown) => unknown; + + /** + * Control how attribute value should be parsed + * + * @param attrName + * @param attrValue + * @param jPath + * @returns {undefined|null} `undefined` or `null` to set original value + * @returns {unknown} + * + * Defaults to `(attrName, val, jPath) => val` + */ + attributeValueProcessor?: (name: string, value: unknown) => unknown; + + /** + * Whether to process default and DOCTYPE entities + * + * Defaults to `true` + */ + processEntities?: boolean; + + + oneListGroup?: boolean; + + /** + * Maximum number of nested tags + * + * Defaults to `100` + */ + maxNestedTags?: number; +}; + +type ESchema = string | object | Array; + +export type ValidationError = { + err: { + code: string; + msg: string, + line: number, + col: number + }; +}; + +export class XMLParser { + constructor(options?: X2jOptions); + parse(xmlData: string | Uint8Array, validationOptions?: validationOptions | boolean): any; + /** + * Add Entity which is not by default supported by this library + * @param entityIdentifier {string} Eg: 'ent' for &ent; + * @param entityValue {string} Eg: '\r' + */ + addEntity(entityIdentifier: string, entityValue: string): void; + + /** + * Returns a Symbol that can be used to access the {@link XMLMetaData} + * property on a node. + * + * If Symbol is not available in the environment, an ordinary property is used + * and the name of the property is here returned. + * + * The XMLMetaData property is only present when {@link X2jOptions.captureMetaData} + * is true in the options. + */ + static getMetaDataSymbol(): Symbol; +} + +export class XMLValidator { + static validate(xmlData: string, options?: validationOptions): true | ValidationError; +} +/** + * @deprecated Use npm package 'fast-xml-builder' instead + */ +export class XMLBuilder { + constructor(options?: XmlBuilderOptions); + build(jObj: any): string; +} + +/** + * This object is available on nodes via the symbol {@link XMLParser.getMetaDataSymbol} + * when {@link X2jOptions.captureMetaData} is true. + */ +export interface XMLMetaData { + /** The index, if available, of the character where the XML node began in the input stream. */ + startIndex?: number; +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/fxp.js b/node_modules/fast-xml-parser/src/fxp.js new file mode 100644 index 0000000..470ed56 --- /dev/null +++ b/node_modules/fast-xml-parser/src/fxp.js @@ -0,0 +1,14 @@ +'use strict'; + +import { validate } from './validator.js'; +import XMLParser from './xmlparser/XMLParser.js'; +import XMLBuilder from './xmlbuilder/json2xml.js'; + +const XMLValidator = { + validate: validate +} +export { + XMLParser, + XMLValidator, + XMLBuilder +}; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/ignoreAttributes.js b/node_modules/fast-xml-parser/src/ignoreAttributes.js new file mode 100644 index 0000000..bdec0a6 --- /dev/null +++ b/node_modules/fast-xml-parser/src/ignoreAttributes.js @@ -0,0 +1,18 @@ +export default function getIgnoreAttributesFn(ignoreAttributes) { + if (typeof ignoreAttributes === 'function') { + return ignoreAttributes + } + if (Array.isArray(ignoreAttributes)) { + return (attrName) => { + for (const pattern of ignoreAttributes) { + if (typeof pattern === 'string' && attrName === pattern) { + return true + } + if (pattern instanceof RegExp && pattern.test(attrName)) { + return true + } + } + } + } + return () => false +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/util.js b/node_modules/fast-xml-parser/src/util.js new file mode 100644 index 0000000..c2c809d --- /dev/null +++ b/node_modules/fast-xml-parser/src/util.js @@ -0,0 +1,61 @@ +'use strict'; + +const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; +const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; +export const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*'; +const regexName = new RegExp('^' + nameRegexp + '$'); + +export function getAllMatches(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); + } + matches.push(allmatches); + match = regex.exec(string); + } + return matches; +} + +export const isName = function (string) { + const match = regexName.exec(string); + return !(match === null || typeof match === 'undefined'); +} + +export function isExist(v) { + return typeof v !== 'undefined'; +} + +export function isEmptyObject(obj) { + return Object.keys(obj).length === 0; +} + +export function getValue(v) { + if (exports.isExist(v)) { + return v; + } else { + return ''; + } +} + +/** + * Dangerous property names that could lead to prototype pollution or security issues + */ +export const DANGEROUS_PROPERTY_NAMES = [ + // '__proto__', + // 'constructor', + // 'prototype', + 'hasOwnProperty', + 'toString', + 'valueOf', + '__defineGetter__', + '__defineSetter__', + '__lookupGetter__', + '__lookupSetter__' +]; + +export const criticalProperties = ["__proto__", "constructor", "prototype"]; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/CharsSymbol.js b/node_modules/fast-xml-parser/src/v6/CharsSymbol.js new file mode 100644 index 0000000..6ac2de4 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/CharsSymbol.js @@ -0,0 +1,16 @@ +export default { + "<" : "<", //tag start + ">" : ">", //tag end + "/" : "/", //close tag + "!" : "!", //comment or docttype + "!--" : "!--", //comment + "-->" : "-->", //comment end + "?" : "?", //pi + "?>" : "?>", //pi end + "?xml" : "?xml", //pi end + "![" : "![", //cdata + "]]>" : "]]>", //cdata end + "[" : "[", + "-" : "-", + "D" : "D", +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/EntitiesParser.js b/node_modules/fast-xml-parser/src/v6/EntitiesParser.js new file mode 100644 index 0000000..576e069 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/EntitiesParser.js @@ -0,0 +1,106 @@ +const ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }; +const htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent": { regex: /&(cent|#162);/g, val: "¢" }, + "pound": { regex: /&(pound|#163);/g, val: "£" }, + "yen": { regex: /&(yen|#165);/g, val: "¥" }, + "euro": { regex: /&(euro|#8364);/g, val: "€" }, + "copyright": { regex: /&(copy|#169);/g, val: "©" }, + "reg": { regex: /&(reg|#174);/g, val: "®" }, + "inr": { regex: /&(inr|#8377);/g, val: "₹" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_, str) => String.fromCodePoint(Number.parseInt(str, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str) => String.fromCodePoint(Number.parseInt(str, 16)) }, +}; +export default class EntitiesParser { + constructor(replaceHtmlEntities) { + this.replaceHtmlEntities = replaceHtmlEntities; + this.docTypeEntities = {}; + this.lastEntities = { + "apos": { regex: /&(apos|#39|#x27);/g, val: "'" }, + "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" }, + "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" }, + "quot": { regex: /&(quot|#34|#x22);/g, val: "\"" }, + }; + } + + addExternalEntities(externalEntities) { + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.addExternalEntity(ent, externalEntities[ent]) + } + } + addExternalEntity(key, val) { + validateEntityName(key); + const escaped = key.replace(/[.\-+*:]/g, '\\.'); + if (val.indexOf("&") !== -1) { + reportWarning(`Entity ${key} is not added as '&' is found in value;`) + return; + } else { + this.lastEntities[key] = { + regex: new RegExp("&" + escaped + ";", "g"), + val: val + } + } + } + + addDocTypeEntities(entities) { + const entKeys = Object.keys(entities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + const escaped = ent.replace(/[.\-+*:]/g, '\\.'); + this.docTypeEntities[ent] = { + regex: new RegExp("&" + escaped + ";", "g"), + val: entities[ent] + } + } + } + + parse(val) { + return this.replaceEntitiesValue(val) + } + + /** + * 1. Replace DOCTYPE entities + * 2. Replace external entities + * 3. Replace HTML entities if asked + * @param {string} val + */ + replaceEntitiesValue(val) { + if (typeof val === "string" && val.length > 0) { + for (let entityName in this.docTypeEntities) { + const entity = this.docTypeEntities[entityName]; + val = val.replace(entity.regx, entity.val); + } + for (let entityName in this.lastEntities) { + const entity = this.lastEntities[entityName]; + val = val.replace(entity.regex, entity.val); + } + if (this.replaceHtmlEntities) { + for (let entityName in htmlEntities) { + const entity = htmlEntities[entityName]; + val = val.replace(entity.regex, entity.val); + } + } + val = val.replace(ampEntity.regex, ampEntity.val); + } + return val; + } +} + +//an entity name should not contains special characters that may be used in regex +//Eg !?\\\/[]$%{}^&*()<> +const specialChar = "!?\\/[]$%{}^&*()<>|+"; + +function validateEntityName(name) { + for (let i = 0; i < specialChar.length; i++) { + const ch = specialChar[i]; + if (name.indexOf(ch) !== -1) throw new Error(`Invalid character ${ch} in entity name`); + } + return name; +} diff --git a/node_modules/fast-xml-parser/src/v6/OptionsBuilder.js b/node_modules/fast-xml-parser/src/v6/OptionsBuilder.js new file mode 100644 index 0000000..6e33919 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OptionsBuilder.js @@ -0,0 +1,61 @@ + +import { JsObjOutputBuilder } from './OutputBuilders/JsObjBuilder.js'; + +export const defaultOptions = { + preserveOrder: false, + removeNSPrefix: false, // remove NS from tag name or attribute name if true + //ignoreRootElement : false, + stopNodes: [], //nested tags will not be parsed even for errors + // isArray: () => false, //User will set it + htmlEntities: false, + // skipEmptyListItem: false + tags: { + unpaired: [], + nameFor: { + cdata: false, + comment: false, + text: '#text' + }, + separateTextProperty: false, + }, + attributes: { + ignore: false, + booleanType: true, + entities: true, + }, + + // select: ["img[src]"], + // stop: ["anim", "[ads]"] + only: [], // rest tags will be skipped. It will result in flat array + hierarchy: false, //will be used when a particular tag is set to be parsed. + skip: [], // will be skipped from parse result. on('skip') will be triggered + + select: [], // on('select', tag => tag ) will be called if match + stop: [], //given tagPath will not be parsed. innerXML will be set as string value + OutputBuilder: new JsObjOutputBuilder(), +}; + +export const buildOptions = function (options) { + const finalOptions = { ...defaultOptions }; + copyProperties(finalOptions, options) + return finalOptions; +}; + +function copyProperties(target, source) { + for (let key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + if (key === 'OutputBuilder') { + target[key] = source[key]; + } else if (typeof source[key] === 'object' && !Array.isArray(source[key])) { + // Recursively copy nested properties + if (typeof target[key] === 'undefined') { + target[key] = {}; + } + copyProperties(target[key], source[key]); + } else { + // Copy non-nested properties + target[key] = source[key]; + } + } + } +} diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/BaseOutputBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/BaseOutputBuilder.js new file mode 100644 index 0000000..aee7365 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/BaseOutputBuilder.js @@ -0,0 +1,69 @@ +export default class BaseOutputBuilder { + constructor() { + // this.attributes = {}; + } + + addAttribute(name, value) { + if (this.options.onAttribute) { + //TODO: better to pass tag path + const v = this.options.onAttribute(name, value, this.tagName); + if (v) this.attributes[v.name] = v.value; + } else { + name = this.options.attributes.prefix + name + this.options.attributes.suffix; + this.attributes[name] = this.parseValue(value, this.options.attributes.valueParsers); + } + } + + /** + * parse value by chain of parsers + * @param {string} val + * @returns {any} parsed value if matching parser found + */ + parseValue = function (val, valParsers) { + for (let i = 0; i < valParsers.length; i++) { + let valParser = valParsers[i]; + if (typeof valParser === "string") { + valParser = this.registeredParsers[valParser]; + } + if (valParser) { + val = valParser.parse(val); + } + } + return val; + } + + /** + * To add a nested empty tag. + * @param {string} key + * @param {any} val + */ + _addChild(key, val) { } + + /** + * skip the comment if property is not set + */ + addComment(text) { + if (this.options.nameFor.comment) + this._addChild(this.options.nameFor.comment, text); + } + + //store CDATA separately if property is set + //otherwise add to tag's value + addCdata(text) { + if (this.options.nameFor.cdata) { + this._addChild(this.options.nameFor.cdata, text); + } else { + this.addRawValue(text || ""); + } + } + + addRawValue = text => this.addValue(text); + + addDeclaration() { + if (!this.options.declaration) { + } else { + this.addPi("?xml"); + } + this.attributes = {} + } +} diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsArrBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsArrBuilder.js new file mode 100644 index 0000000..04205e5 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsArrBuilder.js @@ -0,0 +1,103 @@ +import { buildOptions, registerCommonValueParsers } from './ParserOptionsBuilder.js'; + +export default class OutputBuilder { + constructor(options) { + this.options = buildOptions(options); + this.registeredParsers = registerCommonValueParsers(this.options); + } + + registerValueParser(name, parserInstance) {//existing name will override the parser without warning + this.registeredParsers[name] = parserInstance; + } + + getInstance(parserOptions) { + return new JsArrBuilder(parserOptions, this.options, this.registeredParsers); + } +} + +const rootName = '!js_arr'; +import BaseOutputBuilder from './BaseOutputBuilder.js'; + +class JsArrBuilder extends BaseOutputBuilder { + + constructor(parserOptions, options, registeredParsers) { + super(); + this.tagsStack = []; + this.parserOptions = parserOptions; + this.options = options; + this.registeredParsers = registeredParsers; + + this.root = new Node(rootName); + this.currentNode = this.root; + this.attributes = {}; + } + + addTag(tag) { + //when a new tag is added, it should be added as child of current node + //TODO: shift this check to the parser + if (tag.name === "__proto__") tag.name = "#__proto__"; + + this.tagsStack.push(this.currentNode); + this.currentNode = new Node(tag.name, this.attributes); + this.attributes = {}; + } + + /** + * Check if the node should be added by checking user's preference + * @param {Node} node + * @returns boolean: true if the node should not be added + */ + closeTag() { + const node = this.currentNode; + this.currentNode = this.tagsStack.pop(); //set parent node in scope + if (this.options.onClose !== undefined) { + //TODO TagPathMatcher + const resultTag = this.options.onClose(node, + new TagPathMatcher(this.tagsStack, node)); + + if (resultTag) return; + } + this.currentNode.child.push(node); //to parent node + } + + //Called by parent class methods + _addChild(key, val) { + // if(key === "__proto__") tagName = "#__proto__"; + this.currentNode.child.push({ [key]: val }); + // this.currentNode.leafType = false; + } + + /** + * Add text value child node + * @param {string} text + */ + addValue(text) { + this.currentNode.child.push({ [this.options.nameFor.text]: this.parseValue(text, this.options.tags.valueParsers) }); + } + + addPi(name) { + //TODO: set pi flag + if (!this.options.ignorePiTags) { + const node = new Node(name, this.attributes); + this.currentNode[":@"] = this.attributes; + this.currentNode.child.push(node); + } + this.attributes = {}; + } + getOutput() { + return this.root.child[0]; + } +} + + + +class Node { + constructor(tagname, attributes) { + this.tagname = tagname; + this.child = []; //nested tags, text, cdata, comments + if (attributes && Object.keys(attributes).length > 0) + this[":@"] = attributes; + } +} + +module.exports = OutputBuilder; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsMinArrBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsMinArrBuilder.js new file mode 100644 index 0000000..f0eee0c --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsMinArrBuilder.js @@ -0,0 +1,100 @@ +import {buildOptions,registerCommonValueParsers} from"./ParserOptionsBuilder.js"; + +export default class OutputBuilder{ + constructor(options){ + this.options = buildOptions(options); + this.registeredParsers = registerCommonValueParsers(this.options); + } + + registerValueParser(name,parserInstance){//existing name will override the parser without warning + this.registeredParsers[name] = parserInstance; + } + + getInstance(parserOptions){ + return new JsMinArrBuilder(parserOptions, this.options, this.registeredParsers); + } +} + +import BaseOutputBuilder from "./BaseOutputBuilder.js"; +const rootName = '^'; + +class JsMinArrBuilder extends BaseOutputBuilder{ + + constructor(parserOptions, options,registeredParsers) { + super(); + this.tagsStack = []; + this.parserOptions = parserOptions; + this.options = options; + this.registeredParsers = registeredParsers; + + this.root = {[rootName]: []}; + this.currentNode = this.root; + this.currentNodeTagName = rootName; + this.attributes = {}; + } + + addTag(tag){ + //when a new tag is added, it should be added as child of current node + //TODO: shift this check to the parser + if(tag.name === "__proto__") tag.name = "#__proto__"; + + this.tagsStack.push([this.currentNodeTagName,this.currentNode]); //this.currentNode is parent node here + this.currentNodeTagName = tag.name; + this.currentNode = { [tag.name]:[]} + if(Object.keys(this.attributes).length > 0){ + this.currentNode[":@"] = this.attributes; + this.attributes = {}; + } + } + + /** + * Check if the node should be added by checking user's preference + * @param {Node} node + * @returns boolean: true if the node should not be added + */ + closeTag(){ + const node = this.currentNode; + const nodeName = this.currentNodeTagName; + const arr = this.tagsStack.pop(); //set parent node in scope + this.currentNodeTagName = arr[0]; + this.currentNode = arr[1]; + + if(this.options.onClose !== undefined){ + //TODO TagPathMatcher + const resultTag = this.options.onClose(node, + new TagPathMatcher(this.tagsStack,node)); + + if(resultTag) return; + } + this.currentNode[this.currentNodeTagName].push(node); //to parent node + } + + //Called by parent class methods + _addChild(key, val){ + // if(key === "__proto__") tagName = "#__proto__"; + this.currentNode.push( {[key]: val }); + // this.currentNode.leafType = false; + } + + /** + * Add text value child node + * @param {string} text + */ + addValue(text){ + this.currentNode[this.currentNodeTagName].push( {[this.options.nameFor.text]: this.parseValue(text, this.options.tags.valueParsers) }); + } + + addPi(name){ + if(!this.options.ignorePiTags){ + const node = { [name]:[]} + if(this.attributes){ + node[":@"] = this.attributes; + } + this.currentNode.push(node); + } + this.attributes = {}; + } + getOutput(){ + return this.root[rootName]; + } +} diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsObjBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsObjBuilder.js new file mode 100644 index 0000000..9e19de9 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsObjBuilder.js @@ -0,0 +1,154 @@ + + +import { buildOptions, registerCommonValueParsers } from './ParserOptionsBuilder.js'; + +export default class OutputBuilder { + constructor(builderOptions) { + this.options = buildOptions(builderOptions); + this.registeredParsers = registerCommonValueParsers(this.options); + } + + registerValueParser(name, parserInstance) {//existing name will override the parser without warning + this.registeredParsers[name] = parserInstance; + } + + getInstance(parserOptions) { + return new JsObjBuilder(parserOptions, this.options, this.registeredParsers); + } +} + +import BaseOutputBuilder from './BaseOutputBuilder.js'; +const rootName = '^'; + +class JsObjBuilder extends BaseOutputBuilder { + + constructor(parserOptions, builderOptions, registeredParsers) { + super(); + //hold the raw detail of a tag and sequence with reference to the output + this.tagsStack = []; + this.parserOptions = parserOptions; + this.options = builderOptions; + this.registeredParsers = registeredParsers; + + this.root = {}; + this.parent = this.root; + this.tagName = rootName; + this.value = {}; + this.textValue = ""; + this.attributes = {}; + } + + addTag(tag) { + + let value = ""; + if (!isEmpty(this.attributes)) { + value = {}; + if (this.options.attributes.groupBy) { + value[this.options.attributes.groupBy] = this.attributes; + } else { + value = this.attributes; + } + } + + this.tagsStack.push([this.tagName, this.textValue, this.value]); //parent tag, parent text value, parent tag value (jsobj) + this.tagName = tag.name; + this.value = value; + this.textValue = ""; + this.attributes = {}; + } + + /** + * Check if the node should be added by checking user's preference + * @param {Node} node + * @returns boolean: true if the node should not be added + */ + closeTag() { + const tagName = this.tagName; + let value = this.value; + let textValue = this.textValue; + + //update tag text value + if (typeof value !== "object" && !Array.isArray(value)) { + value = this.parseValue(textValue.trim(), this.options.tags.valueParsers); + } else if (textValue.length > 0) { + value[this.options.nameFor.text] = this.parseValue(textValue.trim(), this.options.tags.valueParsers); + } + + + let resultTag = { + tagName: tagName, + value: value + }; + + if (this.options.onTagClose !== undefined) { + //TODO TagPathMatcher + resultTag = this.options.onClose(tagName, value, this.textValue, new TagPathMatcher(this.tagsStack, node)); + + if (!resultTag) return; + } + + //set parent node in scope + let arr = this.tagsStack.pop(); + let parentTag = arr[2]; + parentTag = this._addChildTo(resultTag.tagName, resultTag.value, parentTag); + + this.tagName = arr[0]; + this.textValue = arr[1]; + this.value = parentTag; + } + + _addChild(key, val) { + if (typeof this.value === "string") { + this.value = { [this.options.nameFor.text]: this.value }; + } + + this._addChildTo(key, val, this.value); + // this.currentNode.leafType = false; + this.attributes = {}; + } + + _addChildTo(key, val, node) { + if (typeof node === 'string') node = {}; + if (!node[key]) { + node[key] = val; + } else { //Repeated + if (!Array.isArray(node[key])) { //but not stored as array + node[key] = [node[key]]; + } + node[key].push(val); + } + return node; + } + + + /** + * Add text value child node + * @param {string} text + */ + addValue(text) { + //TODO: use bytes join + if (this.textValue.length > 0) this.textValue += " " + text; + else this.textValue = text; + } + + addPi(name) { + let value = ""; + if (!isEmpty(this.attributes)) { + value = {}; + if (this.options.attributes.groupBy) { + value[this.options.attributes.groupBy] = this.attributes; + } else { + value = this.attributes; + } + } + this._addChild(name, value); + + } + getOutput() { + return this.value; + } +} + +function isEmpty(obj) { + return Object.keys(obj).length === 0; +} diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/ParserOptionsBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/ParserOptionsBuilder.js new file mode 100644 index 0000000..0e20683 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/ParserOptionsBuilder.js @@ -0,0 +1,94 @@ +import trimParser from "../valueParsers/trim.js"; +import booleanParser from "../valueParsers/booleanParser.js"; +import currencyParser from "../valueParsers/currency.js"; +import numberParser from "../valueParsers/number.js"; + +const defaultOptions = { + nameFor: { + text: "#text", + comment: "", + cdata: "", + }, + // onTagClose: () => {}, + // onAttribute: () => {}, + piTag: false, + declaration: false, //"?xml" + tags: { + valueParsers: [ + // "trim", + // "boolean", + // "number", + // "currency", + // "date", + ] + }, + attributes: { + prefix: "@_", + suffix: "", + groupBy: "", + + valueParsers: [ + // "trim", + // "boolean", + // "number", + // "currency", + // "date", + ] + }, + dataType: { + + } +} + +//TODO +const withJoin = ["trim", "join", /*"entities",*/"number", "boolean", "currency"/*, "date"*/] +const withoutJoin = ["trim", /*"entities",*/"number", "boolean", "currency"/*, "date"*/] + +export function buildOptions(options) { + //clone + const finalOptions = { ...defaultOptions }; + + //add config missed in cloning + finalOptions.tags.valueParsers.push(...withJoin) + if (!this.preserveOrder) + finalOptions.tags.valueParsers.push(...withoutJoin); + + //add config missed in cloning + finalOptions.attributes.valueParsers.push(...withJoin) + + //override configuration + copyProperties(finalOptions, options); + return finalOptions; +} + +function copyProperties(target, source) { + for (let key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + if (typeof source[key] === 'object' && !Array.isArray(source[key])) { + // Recursively copy nested properties + if (typeof target[key] === 'undefined') { + target[key] = {}; + } + copyProperties(target[key], source[key]); + } else { + // Copy non-nested properties + target[key] = source[key]; + } + } + } +} + +export function registerCommonValueParsers(options) { + return { + "trim": new trimParser(), + // "join": this.entityParser.parse, + "boolean": new booleanParser(), + "number": new numberParser({ + hex: true, + leadingZeros: true, + eNotation: true + }), + "currency": new currencyParser(), + // "date": this.entityParser.parse, + } +} diff --git a/node_modules/fast-xml-parser/src/v6/Report.js b/node_modules/fast-xml-parser/src/v6/Report.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/fast-xml-parser/src/v6/TagPath.js b/node_modules/fast-xml-parser/src/v6/TagPath.js new file mode 100644 index 0000000..98148c7 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/TagPath.js @@ -0,0 +1,81 @@ +export default class TagPath{ + constructor(pathStr){ + let text = ""; + let tName = ""; + let pos; + let aName = ""; + let aVal = ""; + this.stack = [] + + for (let i = 0; i < pathStr.length; i++) { + let ch = pathStr[i]; + if(ch === " ") { + if(text.length === 0) continue; + tName = text; text = ""; + }else if(ch === "["){ + if(tName.length === 0){ + tName = text; text = ""; + } + i++; + for (; i < pathStr.length; i++) { + ch = pathStr[i]; + if(ch=== "=") continue; + else if(ch=== "]") {aName = text.trim(); text=""; break; i--;} + else if(ch === "'" || ch === '"'){ + let attrEnd = pathStr.indexOf(ch,i+1); + aVal = pathStr.substring(i+1, attrEnd); + i = attrEnd; + }else{ + text +=ch; + } + } + }else if(ch !== " " && text.length === 0 && tName.length > 0){//reading tagName + //save previous tag + this.stack.push(new TagPathNode(tName,pos,aName,aVal)); + text = ch; tName = ""; aName = ""; aVal = ""; + }else{ + text+=ch; + } + } + + //last tag in the path + if(tName.length >0 || text.length>0){ + this.stack.push(new TagPathNode(text||tName,pos,aName,aVal)); + } + } + + match(tagStack,node){ + if(this.stack[0].name !== "*"){ + if(this.stack.length !== tagStack.length +1) return false; + + //loop through tagPath and tagStack and match + for (let i = 0; i < this.tagStack.length; i++) { + if(!this.stack[i].match(tagStack[i])) return false; + } + } + if(!this.stack[this.stack.length - 1].match(node)) return false; + return true; + } +} + +class TagPathNode{ + constructor(name,position,attrName,attrVal){ + this.name = name; + this.position = position; + this.attrName = attrName, + this.attrVal = attrVal; + } + + match(node){ + let matching = true; + matching = node.name === this.name; + if(this.position) matching = node.position === this.position; + if(this.attrName) matching = node.attrs[this.attrName !== undefined]; + if(this.attrVal) matching = node.attrs[this.attrName !== this.attrVal]; + return matching; + } +} + +// console.log((new TagPath("* b[b]")).stack); +// console.log((new TagPath("a[a] b[b] c")).stack); +// console.log((new TagPath(" b [ b= 'cf sdadwa' ] a ")).stack); \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/TagPathMatcher.js b/node_modules/fast-xml-parser/src/v6/TagPathMatcher.js new file mode 100644 index 0000000..8110447 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/TagPathMatcher.js @@ -0,0 +1,13 @@ +import {TagPath} from './TagPath.js'; + +export default class TagPathMatcher{ + constructor(stack,node){ + this.stack = stack; + this.node= node; + } + + match(path){ + const tagPath = new TagPath(path); + return tagPath.match(this.stack, this.node); + } +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/XMLParser.js b/node_modules/fast-xml-parser/src/v6/XMLParser.js new file mode 100644 index 0000000..44c70dc --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/XMLParser.js @@ -0,0 +1,83 @@ +import { buildOptions } from './OptionsBuilder.js'; +import Xml2JsParser from './Xml2JsParser.js'; + +export default class XMLParser { + + constructor(options) { + this.externalEntities = {}; + this.options = buildOptions(options); + // console.log(this.options) + } + /** + * Parse XML data string to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parse(xmlData) { + if (Array.isArray(xmlData) && xmlData.byteLength !== undefined) { + return this.parse(xmlData); + } else if (xmlData.toString) { + xmlData = xmlData.toString(); + } else { + throw new Error("XML data is accepted in String or Bytes[] form.") + } + // if( validationOption){ + // if(validationOption === true) validationOption = {}; //validate with default options + + // const result = validator.validate(xmlData, validationOption); + // if (result !== true) { + // throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` ) + // } + // } + const parser = new Xml2JsParser(this.options); + parser.entityParser.addExternalEntities(this.externalEntities); + return parser.parse(xmlData); + } + /** + * Parse XML data buffer to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parseBytesArr(xmlData) { + if (Array.isArray(xmlData) && xmlData.byteLength !== undefined) { + } else { + throw new Error("XML data is accepted in Bytes[] form.") + } + const parser = new Xml2JsParser(this.options); + parser.entityParser.addExternalEntities(this.externalEntities); + return parser.parseBytesArr(xmlData); + } + /** + * Parse XML data stream to JS object + * @param {fs.ReadableStream} xmlDataStream + */ + parseStream(xmlDataStream) { + if (!isStream(xmlDataStream)) throw new Error("FXP: Invalid stream input"); + + const orderedObjParser = new Xml2JsParser(this.options); + orderedObjParser.entityParser.addExternalEntities(this.externalEntities); + return orderedObjParser.parseStream(xmlDataStream); + } + + /** + * Add Entity which is not by default supported by this library + * @param {string} key + * @param {string} value + */ + addEntity(key, value) { + if (value.indexOf("&") !== -1) { + throw new Error("Entity value can't have '&'") + } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) { + throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") + } else if (value === "&") { + throw new Error("An entity with value '&' is not permitted"); + } else { + this.externalEntities[key] = value; + } + } +} + +function isStream(stream) { + if (stream && typeof stream.read === "function" && typeof stream.on === "function" && typeof stream.readableEnded === "boolean") return true; + return false; +} diff --git a/node_modules/fast-xml-parser/src/v6/Xml2JsParser.js b/node_modules/fast-xml-parser/src/v6/Xml2JsParser.js new file mode 100644 index 0000000..bd62265 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/Xml2JsParser.js @@ -0,0 +1,235 @@ +import StringSource from './inputSource/StringSource.js'; +import BufferSource from './inputSource/BufferSource.js'; +import {readTagExp,readClosingTagName} from './XmlPartReader.js'; +import {readComment, readCdata,readDocType,readPiTag} from './XmlSpecialTagsReader.js'; +import TagPath from './TagPath.js'; +import TagPathMatcher from './TagPathMatcher.js'; +import EntitiesParser from './EntitiesParser.js'; + +//To hold the data of current tag +//This is usually used to compare jpath expression against current tag +class TagDetail{ + constructor(name){ + this.name = name; + this.position = 0; + // this.attributes = {}; + } +} + +export default class Xml2JsParser { + constructor(options) { + this.options = options; + + this.currentTagDetail = null; + this.tagTextData = ""; + this.tagsStack = []; + this.entityParser = new EntitiesParser(options.htmlEntities); + this.stopNodes = []; + for (let i = 0; i < this.options.stopNodes.length; i++) { + this.stopNodes.push(new TagPath(this.options.stopNodes[i])); + } + } + + parse(strData) { + this.source = new StringSource(strData); + this.parseXml(); + return this.outputBuilder.getOutput(); + } + parseBytesArr(data) { + this.source = new BufferSource(data ); + this.parseXml(); + return this.outputBuilder.getOutput(); + } + + parseXml() { + //TODO: Separate TagValueParser as separate class. So no scope issue in node builder class + + //OutputBuilder should be set in XML Parser + this.outputBuilder = this.options.OutputBuilder.getInstance(this.options); + this.root = { root: true}; + this.currentTagDetail = this.root; + + while(this.source.canRead()){ + let ch = this.source.readCh(); + if (ch === "") break; + + if(ch === "<"){//tagStart + let nextChar = this.source.readChAt(0); + if (nextChar === "" ) throw new Error("Unexpected end of source"); + + + if(nextChar === "!" || nextChar === "?"){ + this.source.updateBufferBoundary(); + //previously collected text should be added to current node + this.addTextNode(); + + this.readSpecialTag(nextChar);// Read DOCTYPE, comment, CDATA, PI tag + }else if(nextChar === "/"){ + this.source.updateBufferBoundary(); + this.readClosingTag(); + // console.log(this.source.buffer.length, this.source.readable); + // console.log(this.tagsStack.length); + }else{//opening tag + this.readOpeningTag(); + } + }else{ + this.tagTextData += ch; + } + }//End While loop + if(this.tagsStack.length > 0 || ( this.tagTextData !== "undefined" && this.tagTextData.trimEnd().length > 0) ) throw new Error("Unexpected data in the end of document"); + } + + /** + * read closing paired tag. Set parent tag in scope. + * skip a node on user's choice + */ + readClosingTag(){ + const tagName = this.processTagName(readClosingTagName(this.source)); + // console.log(tagName, this.tagsStack.length); + this.validateClosingTag(tagName); + // All the text data collected, belongs to current tag. + if(!this.currentTagDetail.root) this.addTextNode(); + this.outputBuilder.closeTag(); + // Since the tag is closed now, parent tag comes in scope + this.currentTagDetail = this.tagsStack.pop(); + } + + validateClosingTag(tagName){ + // This can't be unpaired tag, or a stop tag. + if(this.isUnpaired(tagName) || this.isStopNode(tagName)) throw new Error(`Unexpected closing tag '${tagName}'`); + // This must match with last opening tag + else if(tagName !== this.currentTagDetail.name) + throw new Error(`Unexpected closing tag '${tagName}' expecting '${this.currentTagDetail.name}'`) + } + + /** + * Read paired, unpaired, self-closing, stop and special tags. + * Create a new node + * Push paired tag in stack. + */ + readOpeningTag(){ + //save previously collected text data to current node + this.addTextNode(); + + //create new tag + let tagExp = readTagExp(this, ">" ); + + // process and skip from tagsStack For unpaired tag, self closing tag, and stop node + const tagDetail = new TagDetail(tagExp.tagName); + if(this.isUnpaired(tagExp.tagName)) { + //TODO: this will lead 2 extra stack operation + this.outputBuilder.addTag(tagDetail); + this.outputBuilder.closeTag(); + } else if(tagExp.selfClosing){ + this.outputBuilder.addTag(tagDetail); + this.outputBuilder.closeTag(); + } else if(this.isStopNode(this.currentTagDetail)){ + // TODO: let's user set a stop node boundary detector for complex contents like script tag + //TODO: pass tag name only to avoid string operations + const content = source.readUptoCloseTag(` 0){ + //TODO: shift parsing to output builder + + this.outputBuilder.addValue(this.replaceEntities(this.tagTextData)); + } + this.tagTextData = ""; + } + // } + } + + processAttrName(name){ + if(name === "__proto__") name = "#__proto__"; + name = resolveNameSpace(name, this.removeNSPrefix); + return name; + } + + processTagName(name){ + if(name === "__proto__") name = "#__proto__"; + name = resolveNameSpace(name, this.removeNSPrefix); + return name; + } + + /** + * Generate tags path from tagsStack + */ + tagsPath(tagName){ + //TODO: return TagPath Object. User can call match method with path + return ""; + } + + isUnpaired(tagName){ + return this.options.tags.unpaired.indexOf(tagName) !== -1; + } + + /** + * valid expressions are + * tag nested + * * nested + * tag nested[attribute] + * tag nested[attribute=""] + * tag nested[attribute!=""] + * tag nested:0 //for future + * @param {string} tagName + * @returns + */ + isStopNode(node){ + for (let i = 0; i < this.stopNodes.length; i++) { + const givenPath = this.stopNodes[i]; + if(givenPath.match(this.tagsStack, node)) return true; + } + return false + } + + replaceEntities(text){ + //TODO: if option is set then replace entities + return this.entityParser.parse(text) + } +} + +function resolveNameSpace(name, removeNSPrefix) { + if (removeNSPrefix) { + const parts = name.split(':'); + if(parts.length === 2){ + if (parts[0] === 'xmlns') return ''; + else return parts[1]; + }else reportError(`Multiple namespaces ${name}`) + } + return name; +} diff --git a/node_modules/fast-xml-parser/src/v6/XmlPartReader.js b/node_modules/fast-xml-parser/src/v6/XmlPartReader.js new file mode 100644 index 0000000..61c57ec --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/XmlPartReader.js @@ -0,0 +1,210 @@ +'use strict'; + +/** + * find paired tag for a stop node + * @param {string} xmlDoc + * @param {string} tagName + * @param {number} i : start index + */ +export function readStopNode(xmlDoc, tagName, i){ + const startIndex = i; + // Starting at 1 since we already have an open tag + let openTagCount = 1; + + for (; i < xmlDoc.length; i++) { + if( xmlDoc[i] === "<"){ + if (xmlDoc[i+1] === "/") {//close tag + const closeIndex = findSubStrIndex(xmlDoc, ">", i, `${tagName} is not closed`); + let closeTagName = xmlDoc.substring(i+2,closeIndex).trim(); + if(closeTagName === tagName){ + openTagCount--; + if (openTagCount === 0) { + return { + tagContent: xmlDoc.substring(startIndex, i), + i : closeIndex + } + } + } + i=closeIndex; + } else if(xmlDoc[i+1] === '?') { + const closeIndex = findSubStrIndex(xmlDoc, "?>", i+1, "StopNode is not closed.") + i=closeIndex; + } else if(xmlDoc.substr(i + 1, 3) === '!--') { + const closeIndex = findSubStrIndex(xmlDoc, "-->", i+3, "StopNode is not closed.") + i=closeIndex; + } else if(xmlDoc.substr(i + 1, 2) === '![') { + const closeIndex = findSubStrIndex(xmlDoc, "]]>", i, "StopNode is not closed.") - 2; + i=closeIndex; + } else { + const tagData = readTagExp(xmlDoc, i, '>') + + if (tagData) { + const openTagName = tagData && tagData.tagName; + if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") { + openTagCount++; + } + i=tagData.closeIndex; + } + } + } + }//end for loop +} + +/** + * Read closing tag name + * @param {Source} source + * @returns tag name + */ +export function readClosingTagName(source){ + let text = ""; //temporary data + while(source.canRead()){ + let ch = source.readCh(); + // if (ch === null || ch === undefined) break; + // source.updateBuffer(); + + if (ch === ">") return text.trimEnd(); + else text += ch; + } + throw new Error(`Unexpected end of source. Reading '${substr}'`); +} + +/** + * Read XML tag and build attributes map + * This function can be used to read normal tag, pi tag. + * This function can't be used to read comment, CDATA, DOCTYPE. + * Eg + * @param {string} xmlDoc + * @param {number} startIndex starting index + * @returns tag expression includes tag name & attribute string + */ +export function readTagExp(parser) { + let inSingleQuotes = false; + let inDoubleQuotes = false; + let i; + let EOE = false; + + for (i = 0; parser.source.canRead(i); i++) { + const char = parser.source.readChAt(i); + + if (char === "'" && !inDoubleQuotes) { + inSingleQuotes = !inSingleQuotes; + } else if (char === '"' && !inSingleQuotes) { + inDoubleQuotes = !inDoubleQuotes; + } else if (char === '>' && !inSingleQuotes && !inDoubleQuotes) { + // If not inside quotes, stop reading at '>' + EOE = true; + break; + } + + } + if(inSingleQuotes || inDoubleQuotes){ + throw new Error("Invalid attribute expression. Quote is not properly closed"); + }else if(!EOE) throw new Error("Unexpected closing of source. Waiting for '>'"); + + + const exp = parser.source.readStr(i); + parser.source.updateBufferBoundary(i + 1); + return buildTagExpObj(exp, parser) +} + +export function readPiExp(parser) { + let inSingleQuotes = false; + let inDoubleQuotes = false; + let i; + let EOE = false; + + for (i = 0; parser.source.canRead(i) ; i++) { + const currentChar = parser.source.readChAt(i); + const nextChar = parser.source.readChAt(i+1); + + if (currentChar === "'" && !inDoubleQuotes) { + inSingleQuotes = !inSingleQuotes; + } else if (currentChar === '"' && !inSingleQuotes) { + inDoubleQuotes = !inDoubleQuotes; + } + + if (!inSingleQuotes && !inDoubleQuotes) { + if (currentChar === '?' && nextChar === '>') { + EOE = true; + break; // Exit the loop when '?>' is found + } + } + } + if(inSingleQuotes || inDoubleQuotes){ + throw new Error("Invalid attribute expression. Quote is not properly closed in PI tag expression"); + }else if(!EOE) throw new Error("Unexpected closing of source. Waiting for '?>'"); + + if(!parser.options.attributes.ignore){ + //TODO: use regex to verify attributes if not set to ignore + } + + const exp = parser.source.readStr(i); + parser.source.updateBufferBoundary(i + 1); + return buildTagExpObj(exp, parser) +} + +function buildTagExpObj(exp, parser){ + const tagExp = { + tagName: "", + selfClosing: false + }; + let attrsExp = ""; + + // Check for self-closing tag before setting the name + if(exp[exp.length -1] === "/") { + tagExp.selfClosing = true; + exp = exp.slice(0, -1); // Remove the trailing slash + } + + //separate tag name + let i = 0; + for (; i < exp.length; i++) { + const char = exp[i]; + if(char === " "){ + tagExp.tagName = exp.substring(0, i); + attrsExp = exp.substring(i + 1); + break; + } + } + //only tag + if(tagExp.tagName.length === 0 && i === exp.length)tagExp.tagName = exp; + + tagExp.tagName = tagExp.tagName.trimEnd(); + + if(!parser.options.attributes.ignore && attrsExp.length > 0){ + parseAttributesExp(attrsExp,parser) + } + + return tagExp; +} + +const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); + +function parseAttributesExp(attrStr, parser) { + const matches = getAllMatches(attrStr, attrsRegx); + const len = matches.length; //don't make it inline + for (let i = 0; i < len; i++) { + let attrName = parser.processAttrName(matches[i][1]); + let attrVal = parser.replaceEntities(matches[i][4] || true); + + parser.outputBuilder.addAttribute(attrName, attrVal); + } +} + + +const getAllMatches = function(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); + } + matches.push(allmatches); + match = regex.exec(string); + } + return matches; +}; + diff --git a/node_modules/fast-xml-parser/src/v6/XmlSpecialTagsReader.js b/node_modules/fast-xml-parser/src/v6/XmlSpecialTagsReader.js new file mode 100644 index 0000000..330e0a4 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/XmlSpecialTagsReader.js @@ -0,0 +1,111 @@ +import {readPiExp} from './XmlPartReader.js'; + +export function readCdata(parser){ + //"); + parser.outputBuilder.addCdata(text); +} +export function readPiTag(parser){ + //"); + if(!tagExp) throw new Error("Invalid Pi Tag expression."); + + if (tagExp.tagName === "?xml") {//TODO: test if tagName is just xml + parser.outputBuilder.addDeclaration(); + } else { + parser.outputBuilder.addPi("?"+tagExp.tagName); + } +} + +export function readComment(parser){ + //"); + parser.outputBuilder.addComment(text); +} + +const DOCTYPE_tags = { + "EL":/^EMENT\s+([^\s>]+)\s+(ANY|EMPTY|\(.+\)\s*$)/m, + "AT":/^TLIST\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+$/m, + "NO":/^TATION.+$/m +} +export function readDocType(parser){ + //"); + const regx = DOCTYPE_tags[str]; + if(regx){ + const match = dTagExp.match(regx); + if(!match) throw new Error("Invalid DOCTYPE"); + }else throw new Error("Invalid DOCTYPE"); + } + }else if( ch === '>' && lastch === "]"){//end of doctype + return; + } + }else if( ch === '>'){//end of doctype + return; + }else if( ch === '['){ + hasBody = true; + }else{ + lastch = ch; + } + }//End While loop + +} + +function registerEntity(parser){ + //read Entity + let attrBoundary=""; + let name ="", val =""; + while(source.canRead()){ + let ch = source.readCh(); + + if(attrBoundary){ + if (ch === attrBoundary){ + val = text; + text = "" + } + }else if(ch === " " || ch === "\t"){ + if(!name){ + name = text.trimStart(); + text = ""; + } + }else if (ch === '"' || ch === "'") {//start of attrBoundary + attrBoundary = ch; + }else if(ch === ">"){ + parser.entityParser.addExternalEntity(name,val); + return; + }else{ + text+=ch; + } + } +} diff --git a/node_modules/fast-xml-parser/src/v6/inputSource/BufferSource.js b/node_modules/fast-xml-parser/src/v6/inputSource/BufferSource.js new file mode 100644 index 0000000..2c5d8b5 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/inputSource/BufferSource.js @@ -0,0 +1,116 @@ +const Constants = { + space: 32, + tab: 9 +} +export default class BufferSource{ + constructor(bytesArr){ + this.line = 1; + this.cols = 0; + this.buffer = bytesArr; + this.startIndex = 0; + } + + + + readCh() { + return String.fromCharCode(this.buffer[this.startIndex++]); + } + + readChAt(index) { + return String.fromCharCode(this.buffer[this.startIndex+index]); + } + + readStr(n,from){ + if(typeof from === "undefined") from = this.startIndex; + return this.buffer.slice(from, from + n).toString(); + } + + readUpto(stopStr) { + const inputLength = this.buffer.length; + const stopLength = stopStr.length; + const stopBuffer = Buffer.from(stopStr); + + for (let i = this.startIndex; i < inputLength; i++) { + let match = true; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopBuffer[j]) { + match = false; + break; + } + } + + if (match) { + const result = this.buffer.slice(this.startIndex, i).toString(); + this.startIndex = i + stopLength; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); +} + +readUptoCloseTag(stopStr) { //stopStr: "'){ //TODO: if it should be equivalent ASCII + match = 2; + //tag boundary found + // this.startIndex + } + }else{ + match = 1; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopBuffer[j]) { + match = 0; + break; + } + } + } + if (match === 2) {//matched closing part + const result = this.buffer.slice(this.startIndex, stopIndex - 1 ).toString(); + this.startIndex = i + 1; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); +} + + readFromBuffer(n, shouldUpdate) { + let ch; + if (n === 1) { + ch = this.buffer[this.startIndex]; + if (ch === 10) { + this.line++; + this.cols = 1; + } else { + this.cols++; + } + ch = String.fromCharCode(ch); + } else { + this.cols += n; + ch = this.buffer.slice(this.startIndex, this.startIndex + n).toString(); + } + if (shouldUpdate) this.updateBuffer(n); + return ch; + } + + updateBufferBoundary(n = 1) { //n: number of characters read + this.startIndex += n; + } + + canRead(n){ + n = n || this.startIndex; + return this.buffer.length - n + 1 > 0; + } + +} diff --git a/node_modules/fast-xml-parser/src/v6/inputSource/StringSource.js b/node_modules/fast-xml-parser/src/v6/inputSource/StringSource.js new file mode 100644 index 0000000..275889a --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/inputSource/StringSource.js @@ -0,0 +1,121 @@ +const whiteSpaces = [" ", "\n", "\t"]; + + +export default class StringSource{ + constructor(str){ + this.line = 1; + this.cols = 0; + this.buffer = str; + //a boundary pointer to indicate where from the buffer dat should be read + // data before this pointer can be deleted to free the memory + this.startIndex = 0; + } + + readCh() { + return this.buffer[this.startIndex++]; + } + + readChAt(index) { + return this.buffer[this.startIndex+index]; + } + + readStr(n,from){ + if(typeof from === "undefined") from = this.startIndex; + return this.buffer.substring(from, from + n); + } + + readUpto(stopStr) { + const inputLength = this.buffer.length; + const stopLength = stopStr.length; + + for (let i = this.startIndex; i < inputLength; i++) { + let match = true; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopStr[j]) { + match = false; + break; + } + } + + if (match) { + const result = this.buffer.substring(this.startIndex, i); + this.startIndex = i + stopLength; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); + } + + readUptoCloseTag(stopStr) { //stopStr: "'){ + match = 2; + //tag boundary found + // this.startIndex + } + }else{ + match = 1; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopStr[j]) { + match = 0; + break; + } + } + } + if (match === 2) {//matched closing part + const result = this.buffer.substring(this.startIndex, stopIndex - 1 ); + this.startIndex = i + 1; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); + } + + readFromBuffer(n, updateIndex){ + let ch; + if(n===1){ + ch = this.buffer[this.startIndex]; + // if(ch === "\n") { + // this.line++; + // this.cols = 1; + // }else{ + // this.cols++; + // } + }else{ + ch = this.buffer.substring(this.startIndex, this.startIndex + n); + // if("".indexOf("\n") !== -1){ + // //TODO: handle the scenario when there are multiple lines + // //TODO: col should be set to number of chars after last '\n' + // // this.cols = 1; + // }else{ + // this.cols += n; + + // } + } + if(updateIndex) this.updateBufferBoundary(n); + return ch; + } + + //TODO: rename to updateBufferReadIndex + + updateBufferBoundary(n = 1) { //n: number of characters read + this.startIndex += n; + } + + canRead(n){ + n = n || this.startIndex; + return this.buffer.length - n + 1 > 0; + } + +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/EntitiesParser.js b/node_modules/fast-xml-parser/src/v6/valueParsers/EntitiesParser.js new file mode 100644 index 0000000..b7f7ba8 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/EntitiesParser.js @@ -0,0 +1,105 @@ +const ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }; +const htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent": { regex: /&(cent|#162);/g, val: "¢" }, + "pound": { regex: /&(pound|#163);/g, val: "£" }, + "yen": { regex: /&(yen|#165);/g, val: "¥" }, + "euro": { regex: /&(euro|#8364);/g, val: "€" }, + "copyright": { regex: /&(copy|#169);/g, val: "©" }, + "reg": { regex: /&(reg|#174);/g, val: "®" }, + "inr": { regex: /&(inr|#8377);/g, val: "₹" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_, str) => String.fromCodePoint(Number.parseInt(str, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str) => String.fromCodePoint(Number.parseInt(str, 16)) }, +}; + +export default class EntitiesParser { + constructor(replaceHtmlEntities) { + this.replaceHtmlEntities = replaceHtmlEntities; + this.docTypeEntities = {}; + this.lastEntities = { + "apos": { regex: /&(apos|#39|#x27);/g, val: "'" }, + "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" }, + "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" }, + "quot": { regex: /&(quot|#34|#x22);/g, val: "\"" }, + }; + } + + addExternalEntities(externalEntities) { + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.addExternalEntity(ent, externalEntities[ent]) + } + } + addExternalEntity(key, val) { + validateEntityName(key); + if (val.indexOf("&") !== -1) { + reportWarning(`Entity ${key} is not added as '&' is found in value;`) + return; + } else { + this.lastEntities[ent] = { + regex: new RegExp("&" + key + ";", "g"), + val: val + } + } + } + + addDocTypeEntities(entities) { + const entKeys = Object.keys(entities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.docTypeEntities[ent] = { + regex: new RegExp("&" + ent + ";", "g"), + val: entities[ent] + } + } + } + + parse(val) { + return this.replaceEntitiesValue(val) + } + + /** + * 1. Replace DOCTYPE entities + * 2. Replace external entities + * 3. Replace HTML entities if asked + * @param {string} val + */ + replaceEntitiesValue(val) { + if (typeof val === "string" && val.length > 0) { + for (let entityName in this.docTypeEntities) { + const entity = this.docTypeEntities[entityName]; + val = val.replace(entity.regx, entity.val); + } + for (let entityName in this.lastEntities) { + const entity = this.lastEntities[entityName]; + val = val.replace(entity.regex, entity.val); + } + if (this.replaceHtmlEntities) { + for (let entityName in htmlEntities) { + const entity = htmlEntities[entityName]; + val = val.replace(entity.regex, entity.val); + } + } + val = val.replace(ampEntity.regex, ampEntity.val); + } + return val; + } +}; + +//an entity name should not contains special characters that may be used in regex +//Eg !?\\\/[]$%{}^&*()<> +const specialChar = "!?\\\/[]$%{}^&*()<>|+"; + +function validateEntityName(name) { + for (let i = 0; i < specialChar.length; i++) { + const ch = specialChar[i]; + if (name.indexOf(ch) !== -1) throw new Error(`Invalid character ${ch} in entity name`); + } + return name; +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParser.js b/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParser.js new file mode 100644 index 0000000..bc8f806 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParser.js @@ -0,0 +1,22 @@ +export default class boolParser{ + constructor(trueList, falseList){ + if(trueList) + this.trueList = trueList; + else + this.trueList = ["true"]; + + if(falseList) + this.falseList = falseList; + else + this.falseList = ["false"]; + } + parse(val){ + if (typeof val === 'string') { + //TODO: performance: don't convert + const temp = val.toLowerCase(); + if(this.trueList.indexOf(temp) !== -1) return true; + else if(this.falseList.indexOf(temp) !== -1 ) return false; + } + return val; + } +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParserExt.js b/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParserExt.js new file mode 100644 index 0000000..ec3ba42 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParserExt.js @@ -0,0 +1,19 @@ +export default function boolParserExt(val){ + if(isArray(val)){ + for (let i = 0; i < val.length; i++) { + val[i] = parse(val[i]) + } + }else{ + val = parse(val) + } + return val; +} + +function parse(val){ + if (typeof val === 'string') { + const temp = val.toLowerCase(); + if(temp === 'true' || temp ==="yes" || temp==="1") return true; + else if(temp === 'false' || temp ==="no" || temp==="0") return false; + } + return val; +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/currency.js b/node_modules/fast-xml-parser/src/v6/valueParsers/currency.js new file mode 100644 index 0000000..3772817 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/currency.js @@ -0,0 +1,38 @@ +const defaultOptions = { + maxLength: 200, + // locale: "en-IN" +} +const localeMap = { + "$":"en-US", + "€":"de-DE", + "£":"en-GB", + "¥":"ja-JP", + "₹":"en-IN", +} +const sign = "(?:-|\+)?"; +const digitsAndSeparator = "(?:\d+|\d{1,3}(?:,\d{3})+)"; +const decimalPart = "(?:\.\d{1,2})?"; +const symbol = "(?:\$|€|¥|₹)?"; + +const currencyCheckRegex = /^\s*(?:-|\+)?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d{1,2})?\s*(?:\$|€|¥|₹)?\s*$/u; + +export default class CurrencyParser{ + constructor(options){ + this.options = options || defaultOptions; + } + parse(val){ + if (typeof val === 'string' && val.length <= this.options.maxLength) { + if(val.indexOf(",,") !== -1 && val.indexOf(".." !== -1)){ + const match = val.match(currencyCheckRegex); + if(match){ + const locale = this.options.locale || localeMap[match[2]||match[5]||"₹"]; + const formatter = new Intl.NumberFormat(locale) + val = val.replace(/[^0-9,.]/g, '').trim(); + val = Number(val.replace(formatter.format(1000)[1], '')); + } + } + } + return val; + } +} +CurrencyParser.defaultOptions = defaultOptions; diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/join.js b/node_modules/fast-xml-parser/src/v6/valueParsers/join.js new file mode 100644 index 0000000..f597d99 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/join.js @@ -0,0 +1,13 @@ +/** + * + * @param {array} val + * @param {string} by + * @returns + */ +export default function join(val, by=" "){ + if(isArray(val)){ + val.join(by) + } + return val; +} + diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/number.js b/node_modules/fast-xml-parser/src/v6/valueParsers/number.js new file mode 100644 index 0000000..8397fb6 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/number.js @@ -0,0 +1,14 @@ +import toNumber from "strnum"; + + +export default class numParser{ + constructor(options){ + this.options = options; + } + parse(val){ + if (typeof val === 'string') { + val = toNumber(val,this.options); + } + return val; + } +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/trim.js b/node_modules/fast-xml-parser/src/v6/valueParsers/trim.js new file mode 100644 index 0000000..50eed7f --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/trim.js @@ -0,0 +1,6 @@ +export default class trimmer{ + parse(val){ + if(typeof val === "string") return val.trim(); + else return val; + } +} diff --git a/node_modules/fast-xml-parser/src/validator.js b/node_modules/fast-xml-parser/src/validator.js new file mode 100644 index 0000000..277225c --- /dev/null +++ b/node_modules/fast-xml-parser/src/validator.js @@ -0,0 +1,425 @@ +'use strict'; + +import { getAllMatches, isName } from './util.js'; + +const defaultOptions = { + allowBooleanAttributes: false, //A tag can have attributes without any value + unpairedTags: [] +}; + +//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g"); +export function validate(xmlData, options) { + options = Object.assign({}, defaultOptions, options); + + //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line + //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag + //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE + const tags = []; + let tagFound = false; + + //indicates that the root tag has been closed (aka. depth 0 has been reached) + let reachedRoot = false; + + if (xmlData[0] === '\ufeff') { + // check for byte order mark (BOM) + xmlData = xmlData.substr(1); + } + + for (let i = 0; i < xmlData.length; i++) { + + if (xmlData[i] === '<' && xmlData[i + 1] === '?') { + i += 2; + i = readPI(xmlData, i); + if (i.err) return i; + } else if (xmlData[i] === '<') { + //starting of tag + //read until you reach to '>' avoiding any '>' in attribute value + let tagStartPos = i; + i++; + + if (xmlData[i] === '!') { + i = readCommentAndCDATA(xmlData, i); + continue; + } else { + let closingTag = false; + if (xmlData[i] === '/') { + //closing tag + closingTag = true; + i++; + } + //read tagname + let tagName = ''; + for (; i < xmlData.length && + xmlData[i] !== '>' && + xmlData[i] !== ' ' && + xmlData[i] !== '\t' && + xmlData[i] !== '\n' && + xmlData[i] !== '\r'; i++ + ) { + tagName += xmlData[i]; + } + tagName = tagName.trim(); + //console.log(tagName); + + if (tagName[tagName.length - 1] === '/') { + //self closing tag without attributes + tagName = tagName.substring(0, tagName.length - 1); + //continue; + i--; + } + if (!validateTagName(tagName)) { + let msg; + if (tagName.trim().length === 0) { + msg = "Invalid space after '<'."; + } else { + msg = "Tag '" + tagName + "' is an invalid name."; + } + return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i)); + } + + const result = readAttributeStr(xmlData, i); + if (result === false) { + return getErrorObject('InvalidAttr', "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i)); + } + let attrStr = result.value; + i = result.index; + + if (attrStr[attrStr.length - 1] === '/') { + //self closing tag + const attrStrStart = i - attrStr.length; + attrStr = attrStr.substring(0, attrStr.length - 1); + const isValid = validateAttributeString(attrStr, options); + if (isValid === true) { + tagFound = true; + //continue; //text may presents after self closing tag + } else { + //the result from the nested function returns the position of the error within the attribute + //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute + //this gives us the absolute index in the entire xml, which we can use to find the line at last + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); + } + } else if (closingTag) { + if (!result.tagClosed) { + return getErrorObject('InvalidTag', "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); + } else if (attrStr.trim().length > 0) { + return getErrorObject('InvalidTag', "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); + } else if (tags.length === 0) { + return getErrorObject('InvalidTag', "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); + } else { + const otg = tags.pop(); + if (tagName !== otg.tagName) { + let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); + return getErrorObject('InvalidTag', + "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", + getLineNumberForPosition(xmlData, tagStartPos)); + } + + //when there are no more tags, we reached the root level. + if (tags.length == 0) { + reachedRoot = true; + } + } + } else { + const isValid = validateAttributeString(attrStr, options); + if (isValid !== true) { + //the result from the nested function returns the position of the error within the attribute + //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute + //this gives us the absolute index in the entire xml, which we can use to find the line at last + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); + } + + //if the root level has been reached before ... + if (reachedRoot === true) { + return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i)); + } else if (options.unpairedTags.indexOf(tagName) !== -1) { + //don't push into stack + } else { + tags.push({ tagName, tagStartPos }); + } + tagFound = true; + } + + //skip tag text value + //It may include comments and CDATA value + for (i++; i < xmlData.length; i++) { + if (xmlData[i] === '<') { + if (xmlData[i + 1] === '!') { + //comment or CADATA + i++; + i = readCommentAndCDATA(xmlData, i); + continue; + } else if (xmlData[i + 1] === '?') { + i = readPI(xmlData, ++i); + if (i.err) return i; + } else { + break; + } + } else if (xmlData[i] === '&') { + const afterAmp = validateAmpersand(xmlData, i); + if (afterAmp == -1) + return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); + i = afterAmp; + } else { + if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { + return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i)); + } + } + } //end of reading tag text value + if (xmlData[i] === '<') { + i--; + } + } + } else { + if (isWhiteSpace(xmlData[i])) { + continue; + } + return getErrorObject('InvalidChar', "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i)); + } + } + + if (!tagFound) { + return getErrorObject('InvalidXml', 'Start tag expected.', 1); + } else if (tags.length == 1) { + return getErrorObject('InvalidTag', "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); + } else if (tags.length > 0) { + return getErrorObject('InvalidXml', "Invalid '" + + JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '') + + "' found.", { line: 1, col: 1 }); + } + + return true; +}; + +function isWhiteSpace(char) { + return char === ' ' || char === '\t' || char === '\n' || char === '\r'; +} +/** + * Read Processing insstructions and skip + * @param {*} xmlData + * @param {*} i + */ +function readPI(xmlData, i) { + const start = i; + for (; i < xmlData.length; i++) { + if (xmlData[i] == '?' || xmlData[i] == ' ') { + //tagname + const tagname = xmlData.substr(start, i - start); + if (i > 5 && tagname === 'xml') { + return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i)); + } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') { + //check if valid attribut string + i++; + break; + } else { + continue; + } + } + } + return i; +} + +function readCommentAndCDATA(xmlData, i) { + if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') { + //comment + for (i += 3; i < xmlData.length; i++) { + if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') { + i += 2; + break; + } + } + } else if ( + xmlData.length > i + 8 && + xmlData[i + 1] === 'D' && + xmlData[i + 2] === 'O' && + xmlData[i + 3] === 'C' && + xmlData[i + 4] === 'T' && + xmlData[i + 5] === 'Y' && + xmlData[i + 6] === 'P' && + xmlData[i + 7] === 'E' + ) { + let angleBracketsCount = 1; + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === '<') { + angleBracketsCount++; + } else if (xmlData[i] === '>') { + angleBracketsCount--; + if (angleBracketsCount === 0) { + break; + } + } + } + } else if ( + xmlData.length > i + 9 && + xmlData[i + 1] === '[' && + xmlData[i + 2] === 'C' && + xmlData[i + 3] === 'D' && + xmlData[i + 4] === 'A' && + xmlData[i + 5] === 'T' && + xmlData[i + 6] === 'A' && + xmlData[i + 7] === '[' + ) { + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') { + i += 2; + break; + } + } + } + + return i; +} + +const doubleQuote = '"'; +const singleQuote = "'"; + +/** + * Keep reading xmlData until '<' is found outside the attribute value. + * @param {string} xmlData + * @param {number} i + */ +function readAttributeStr(xmlData, i) { + let attrStr = ''; + let startChar = ''; + let tagClosed = false; + for (; i < xmlData.length; i++) { + if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { + if (startChar === '') { + startChar = xmlData[i]; + } else if (startChar !== xmlData[i]) { + //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa + } else { + startChar = ''; + } + } else if (xmlData[i] === '>') { + if (startChar === '') { + tagClosed = true; + break; + } + } + attrStr += xmlData[i]; + } + if (startChar !== '') { + return false; + } + + return { + value: attrStr, + index: i, + tagClosed: tagClosed + }; +} + +/** + * Select all the attributes whether valid or invalid. + */ +const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g'); + +//attr, ="sd", a="amit's", a="sd"b="saf", ab cd="" + +function validateAttributeString(attrStr, options) { + //console.log("start:"+attrStr+":end"); + + //if(attrStr.trim().length === 0) return true; //empty string + + const matches = getAllMatches(attrStr, validAttrStrRegxp); + const attrNames = {}; + + for (let i = 0; i < matches.length; i++) { + if (matches[i][1].length === 0) { + //nospace before attribute name: a="sd"b="saf" + return getErrorObject('InvalidAttr', "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i])) + } else if (matches[i][3] !== undefined && matches[i][4] === undefined) { + return getErrorObject('InvalidAttr', "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) { + //independent attribute: ab + return getErrorObject('InvalidAttr', "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i])); + } + /* else if(matches[i][6] === undefined){//attribute without value: ab= + return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}}; + } */ + const attrName = matches[i][2]; + if (!validateAttrName(attrName)) { + return getErrorObject('InvalidAttr', "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i])); + } + if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) { + //check for duplicate attribute. + attrNames[attrName] = 1; + } else { + return getErrorObject('InvalidAttr', "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i])); + } + } + + return true; +} + +function validateNumberAmpersand(xmlData, i) { + let re = /\d/; + if (xmlData[i] === 'x') { + i++; + re = /[\da-fA-F]/; + } + for (; i < xmlData.length; i++) { + if (xmlData[i] === ';') + return i; + if (!xmlData[i].match(re)) + break; + } + return -1; +} + +function validateAmpersand(xmlData, i) { + // https://www.w3.org/TR/xml/#dt-charref + i++; + if (xmlData[i] === ';') + return -1; + if (xmlData[i] === '#') { + i++; + return validateNumberAmpersand(xmlData, i); + } + let count = 0; + for (; i < xmlData.length; i++, count++) { + if (xmlData[i].match(/\w/) && count < 20) + continue; + if (xmlData[i] === ';') + break; + return -1; + } + return i; +} + +function getErrorObject(code, message, lineNumber) { + return { + err: { + code: code, + msg: message, + line: lineNumber.line || lineNumber, + col: lineNumber.col, + }, + }; +} + +function validateAttrName(attrName) { + return isName(attrName); +} + +// const startsWithXML = /^xml/i; + +function validateTagName(tagname) { + return isName(tagname) /* && !tagname.match(startsWithXML) */; +} + +//this function returns the line number for the character at the given index +function getLineNumberForPosition(xmlData, index) { + const lines = xmlData.substring(0, index).split(/\r?\n/); + return { + line: lines.length, + + // column number is last line's length + 1, because column numbering starts at 1: + col: lines[lines.length - 1].length + 1 + }; +} + +//this function returns the position of the first character of match within attrStr +function getPositionFromMatch(match) { + return match.startIndex + match[1].length; +} diff --git a/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js b/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js new file mode 100644 index 0000000..30cfaa1 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js @@ -0,0 +1,6 @@ +// Re-export from fast-xml-builder for backward compatibility +import XMLBuilder from 'fast-xml-builder'; +export default XMLBuilder; + +// If there are any named exports you also want to re-export: +export * from 'fast-xml-builder'; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js b/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js new file mode 100644 index 0000000..8b1ceb9 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js @@ -0,0 +1,407 @@ +import { isName } from '../util.js'; + +export default class DocTypeReader { + constructor(options) { + this.suppressValidationErr = !options; + this.options = options; + } + + readDocType(xmlData, i) { + const entities = Object.create(null); + let entityCount = 0; + + if (xmlData[i + 3] === 'O' && + xmlData[i + 4] === 'C' && + xmlData[i + 5] === 'T' && + xmlData[i + 6] === 'Y' && + xmlData[i + 7] === 'P' && + xmlData[i + 8] === 'E') { + i = i + 9; + let angleBracketsCount = 1; + let hasBody = false, comment = false; + let exp = ""; + for (; i < xmlData.length; i++) { + if (xmlData[i] === '<' && !comment) { //Determine the tag type + if (hasBody && hasSeq(xmlData, "!ENTITY", i)) { + i += 7; + let entityName, val; + [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr); + if (val.indexOf("&") === -1) { //Parameter entities are not supported + if (this.options.enabled !== false && + this.options.maxEntityCount != null && + entityCount >= this.options.maxEntityCount) { + throw new Error( + `Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})` + ); + } + //const escaped = entityName.replace(/[.\-+*:]/g, '\\.'); + //const escaped = entityName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + entities[entityName] = val; + entityCount++; + } + } + else if (hasBody && hasSeq(xmlData, "!ELEMENT", i)) { + i += 8;//Not supported + const { index } = this.readElementExp(xmlData, i + 1); + i = index; + } else if (hasBody && hasSeq(xmlData, "!ATTLIST", i)) { + i += 8;//Not supported + // const {index} = this.readAttlistExp(xmlData,i+1); + // i = index; + } else if (hasBody && hasSeq(xmlData, "!NOTATION", i)) { + i += 9;//Not supported + const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr); + i = index; + } else if (hasSeq(xmlData, "!--", i)) comment = true; + else throw new Error(`Invalid DOCTYPE`); + + angleBracketsCount++; + exp = ""; + } else if (xmlData[i] === '>') { //Read tag content + if (comment) { + if (xmlData[i - 1] === "-" && xmlData[i - 2] === "-") { + comment = false; + angleBracketsCount--; + } + } else { + angleBracketsCount--; + } + if (angleBracketsCount === 0) { + break; + } + } else if (xmlData[i] === '[') { + hasBody = true; + } else { + exp += xmlData[i]; + } + } + if (angleBracketsCount !== 0) { + throw new Error(`Unclosed DOCTYPE`); + } + } else { + throw new Error(`Invalid Tag instead of DOCTYPE`); + } + return { entities, i }; + } + readEntityExp(xmlData, i) { + //External entities are not supported + // + + //Parameter entities are not supported + // + + //Internal entities are supported + // + + // Skip leading whitespace after this.options.maxEntitySize) { + throw new Error( + `Entity "${entityName}" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})` + ); + } + + i--; + return [entityName, entityValue, i]; + } + + readNotationExp(xmlData, i) { + // Skip leading whitespace after + // + // + // + // + + // Skip leading whitespace after { + while (index < data.length && /\s/.test(data[index])) { + index++; + } + return index; +}; + + + +function hasSeq(data, seq, i) { + for (let j = 0; j < seq.length; j++) { + if (seq[j] !== data[i + j + 1]) return false; + } + return true; +} + +function validateEntityName(name) { + if (isName(name)) + return name; + else + throw new Error(`Invalid entity name ${name}`); +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js b/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js new file mode 100644 index 0000000..ea3fff8 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js @@ -0,0 +1,163 @@ +import { DANGEROUS_PROPERTY_NAMES, criticalProperties } from "../util.js"; +import { COMMON_HTML, CURRENCY } from '@nodable/entities'; + +const defaultOnDangerousProperty = (name) => { + if (DANGEROUS_PROPERTY_NAMES.includes(name)) { + return "__" + name; + } + return name; +}; + + +export const defaultOptions = { + preserveOrder: false, + attributeNamePrefix: '@_', + attributesGroupName: false, + textNodeName: '#text', + ignoreAttributes: true, + removeNSPrefix: false, // remove NS from tag name or attribute name if true + allowBooleanAttributes: false, //a tag can have attributes without any value + //ignoreRootElement : false, + parseTagValue: true, + parseAttributeValue: false, + trimValues: true, //Trim string values of tag and attributes + cdataPropName: false, + numberParseOptions: { + hex: true, + leadingZeros: true, + eNotation: true + }, + tagValueProcessor: function (tagName, val) { + return val; + }, + attributeValueProcessor: function (attrName, val) { + return val; + }, + stopNodes: [], //nested tags will not be parsed even for errors + alwaysCreateTextNode: false, + isArray: () => false, + commentPropName: false, + unpairedTags: [], + processEntities: true, + htmlEntities: false, + entityDecoder: null, + ignoreDeclaration: false, + ignorePiTags: false, + transformTagName: false, + transformAttributeName: false, + updateTag: function (tagName, jPath, attrs) { + return tagName + }, + // skipEmptyListItem: false + captureMetaData: false, + maxNestedTags: 100, + strictReservedNames: true, + jPath: true, // if true, pass jPath string to callbacks; if false, pass matcher instance + onDangerousProperty: defaultOnDangerousProperty +}; + + +/** + * Validates that a property name is safe to use + * @param {string} propertyName - The property name to validate + * @param {string} optionName - The option field name (for error message) + * @throws {Error} If property name is dangerous + */ +function validatePropertyName(propertyName, optionName) { + if (typeof propertyName !== 'string') { + return; // Only validate string property names + } + + const normalized = propertyName.toLowerCase(); + if (DANGEROUS_PROPERTY_NAMES.some(dangerous => normalized === dangerous.toLowerCase())) { + throw new Error( + `[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution` + ); + } + + if (criticalProperties.some(dangerous => normalized === dangerous.toLowerCase())) { + throw new Error( + `[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution` + ); + } +} + +/** + * Normalizes processEntities option for backward compatibility + * @param {boolean|object} value + * @returns {object} Always returns normalized object + */ +function normalizeProcessEntities(value, htmlEntities) { + // Boolean backward compatibility + if (typeof value === 'boolean') { + return { + enabled: value, // true or false + maxEntitySize: 10000, + maxExpansionDepth: 10000, + maxTotalExpansions: Infinity, + maxExpandedLength: 100000, + maxEntityCount: 1000, + allowedTags: null, + tagFilter: null, + appliesTo: "all", + }; + } + + // Object config - merge with defaults + if (typeof value === 'object' && value !== null) { + return { + enabled: value.enabled !== false, + maxEntitySize: Math.max(1, value.maxEntitySize ?? 10000), + maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 10000), + maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity), + maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 100000), + maxEntityCount: Math.max(1, value.maxEntityCount ?? 1000), + allowedTags: value.allowedTags ?? null, + tagFilter: value.tagFilter ?? null, + appliesTo: value.appliesTo ?? "all", + }; + } + + // Default to enabled with limits + return normalizeProcessEntities(true); +} + +export const buildOptions = function (options) { + const built = Object.assign({}, defaultOptions, options); + + // Validate property names to prevent prototype pollution + const propertyNameOptions = [ + { value: built.attributeNamePrefix, name: 'attributeNamePrefix' }, + { value: built.attributesGroupName, name: 'attributesGroupName' }, + { value: built.textNodeName, name: 'textNodeName' }, + { value: built.cdataPropName, name: 'cdataPropName' }, + { value: built.commentPropName, name: 'commentPropName' } + ]; + + for (const { value, name } of propertyNameOptions) { + if (value) { + validatePropertyName(value, name); + } + } + + if (built.onDangerousProperty === null) { + built.onDangerousProperty = defaultOnDangerousProperty; + } + + // Always normalize processEntities for backward compatibility and validation + built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities); + built.unpairedTagsSet = new Set(built.unpairedTags); + // Convert old-style stopNodes for backward compatibility + if (built.stopNodes && Array.isArray(built.stopNodes)) { + built.stopNodes = built.stopNodes.map(node => { + if (typeof node === 'string' && node.startsWith('*.')) { + // Old syntax: *.tagname meant "tagname anywhere" + // Convert to new syntax: ..tagname + return '..' + node.substring(2); + } + return node; + }); + } + //console.debug(built.processEntities) + return built; +}; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js b/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js new file mode 100644 index 0000000..c8da90b --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js @@ -0,0 +1,835 @@ +'use strict'; +///@ts-check + +import { getAllMatches, isExist, DANGEROUS_PROPERTY_NAMES, criticalProperties } from '../util.js'; +import xmlNode from './xmlNode.js'; +import DocTypeReader from './DocTypeReader.js'; +import toNumber from "strnum"; +import getIgnoreAttributesFn from "../ignoreAttributes.js"; +import { Expression, Matcher } from 'path-expression-matcher'; +import { ExpressionSet } from 'path-expression-matcher'; +import { EntityDecoder, XML, CURRENCY, COMMON_HTML } from '@nodable/entities'; + +// const regx = +// '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)' +// .replace(/NAME/g, util.nameRegexp); + +//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g"); +//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g"); + +// Helper functions for attribute and namespace handling + +/** + * Extract raw attributes (without prefix) from prefixed attribute map + * @param {object} prefixedAttrs - Attributes with prefix from buildAttributesMap + * @param {object} options - Parser options containing attributeNamePrefix + * @returns {object} Raw attributes for matcher + */ +function extractRawAttributes(prefixedAttrs, options) { + if (!prefixedAttrs) return {}; + + // Handle attributesGroupName option + const attrs = options.attributesGroupName + ? prefixedAttrs[options.attributesGroupName] + : prefixedAttrs; + + if (!attrs) return {}; + + const rawAttrs = {}; + for (const key in attrs) { + // Remove the attribute prefix to get raw name + if (key.startsWith(options.attributeNamePrefix)) { + const rawName = key.substring(options.attributeNamePrefix.length); + rawAttrs[rawName] = attrs[key]; + } else { + // Attribute without prefix (shouldn't normally happen, but be safe) + rawAttrs[key] = attrs[key]; + } + } + return rawAttrs; +} + +/** + * Extract namespace from raw tag name + * @param {string} rawTagName - Tag name possibly with namespace (e.g., "soap:Envelope") + * @returns {string|undefined} Namespace or undefined + */ +function extractNamespace(rawTagName) { + if (!rawTagName || typeof rawTagName !== 'string') return undefined; + + const colonIndex = rawTagName.indexOf(':'); + if (colonIndex !== -1 && colonIndex > 0) { + const ns = rawTagName.substring(0, colonIndex); + // Don't treat xmlns as a namespace + if (ns !== 'xmlns') { + return ns; + } + } + return undefined; +} + +export default class OrderedObjParser { + constructor(options) { + this.options = options; + this.currentNode = null; + this.tagsNodeStack = []; + this.parseXml = parseXml; + this.parseTextData = parseTextData; + this.resolveNameSpace = resolveNameSpace; + this.buildAttributesMap = buildAttributesMap; + this.isItStopNode = isItStopNode; + this.replaceEntitiesValue = replaceEntitiesValue; + this.readStopNodeData = readStopNodeData; + this.saveTextToParentTag = saveTextToParentTag; + this.addChild = addChild; + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes) + this.entityExpansionCount = 0; + this.currentExpandedLength = 0; + let namedEntities = { ...XML }; + if (this.options.entityDecoder) { + this.entityDecoder = this.options.entityDecoder + } else { + if (typeof this.options.htmlEntities === "object") namedEntities = this.options.htmlEntities; + else if (this.options.htmlEntities === true) namedEntities = { ...COMMON_HTML, ...CURRENCY }; + this.entityDecoder = new EntityDecoder({ + namedEntities: namedEntities, + numericAllowed: this.options.htmlEntities, + limit: { + maxTotalExpansions: this.options.processEntities.maxTotalExpansions, + maxExpandedLength: this.options.processEntities.maxExpandedLength, + applyLimitsTo: this.options.processEntities.appliesTo, + } + //postCheck: resolved => resolved + }); + } + + // Initialize path matcher for path-expression-matcher + this.matcher = new Matcher(); + + // Live read-only proxy of matcher — PEM creates and caches this internally. + // All user callbacks receive this instead of the mutable matcher. + this.readonlyMatcher = this.matcher.readOnly(); + + // Flag to track if current node is a stop node (optimization) + this.isCurrentNodeStopNode = false; + + // Pre-compile stopNodes expressions + this.stopNodeExpressionsSet = new ExpressionSet(); + const stopNodesOpts = this.options.stopNodes; + if (stopNodesOpts && stopNodesOpts.length > 0) { + for (let i = 0; i < stopNodesOpts.length; i++) { + const stopNodeExp = stopNodesOpts[i]; + if (typeof stopNodeExp === 'string') { + // Convert string to Expression object + this.stopNodeExpressionsSet.add(new Expression(stopNodeExp)); + } else if (stopNodeExp instanceof Expression) { + // Already an Expression object + this.stopNodeExpressionsSet.add(stopNodeExp); + } + } + this.stopNodeExpressionsSet.seal(); + } + } + +} + + +/** + * @param {string} val + * @param {string} tagName + * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath + * @param {boolean} dontTrim + * @param {boolean} hasAttributes + * @param {boolean} isLeafNode + * @param {boolean} escapeEntities + */ +function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { + const options = this.options; + if (val !== undefined) { + if (options.trimValues && !dontTrim) { + val = val.trim(); + } + if (val.length > 0) { + if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath); + + // Pass jPath string or matcher based on options.jPath setting + const jPathOrMatcher = options.jPath ? jPath.toString() : jPath; + const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode); + if (newval === null || newval === undefined) { + //don't parse + return val; + } else if (typeof newval !== typeof val || newval !== val) { + //overwrite + return newval; + } else if (options.trimValues) { + return parseValue(val, options.parseTagValue, options.numberParseOptions); + } else { + const trimmedVal = val.trim(); + if (trimmedVal === val) { + return parseValue(val, options.parseTagValue, options.numberParseOptions); + } else { + return val; + } + } + } + } +} + +function resolveNameSpace(tagname) { + if (this.options.removeNSPrefix) { + const tags = tagname.split(':'); + const prefix = tagname.charAt(0) === '/' ? '/' : ''; + if (tags[0] === 'xmlns') { + return ''; + } + if (tags.length === 2) { + tagname = prefix + tags[1]; + } + } + return tagname; +} + +//TODO: change regex to capture NS +//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm"); +const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); + +function buildAttributesMap(attrStr, jPath, tagName, force = false) { + const options = this.options; + if (force === true || (options.ignoreAttributes !== true && typeof attrStr === 'string')) { + // attrStr = attrStr.replace(/\r?\n/g, ' '); + //attrStr = attrStr || attrStr.trim(); + + const matches = getAllMatches(attrStr, attrsRegx); + const len = matches.length; //don't make it inline + const attrs = {}; + + // Pre-process values once: trim + entity replacement + // Reused in both matcher update and second pass + const processedVals = new Array(len); + let hasRawAttrs = false; + const rawAttrsForMatcher = {}; + + for (let i = 0; i < len; i++) { + const attrName = this.resolveNameSpace(matches[i][1]); + const oldVal = matches[i][4]; + + if (attrName.length && oldVal !== undefined) { + let val = oldVal; + if (options.trimValues) val = val.trim(); + val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher); + processedVals[i] = val; + + rawAttrsForMatcher[attrName] = val; + hasRawAttrs = true; + } + } + + // Update matcher ONCE before second pass, if applicable + if (hasRawAttrs && typeof jPath === 'object' && jPath.updateCurrent) { + jPath.updateCurrent(rawAttrsForMatcher); + } + + // Hoist toString() once — path doesn't change during attribute processing + const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher; + + // Second pass: apply processors, build final attrs + let hasAttrs = false; + for (let i = 0; i < len; i++) { + const attrName = this.resolveNameSpace(matches[i][1]); + + if (this.ignoreAttributesFn(attrName, jPathStr)) continue; + + let aName = options.attributeNamePrefix + attrName; + + if (attrName.length) { + if (options.transformAttributeName) { + aName = options.transformAttributeName(aName); + } + aName = sanitizeName(aName, options); + + if (matches[i][4] !== undefined) { + // Reuse already-processed value — no double entity replacement + const oldVal = processedVals[i]; + + const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr); + if (newVal === null || newVal === undefined) { + attrs[aName] = oldVal; + } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) { + attrs[aName] = newVal; + } else { + attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions); + } + hasAttrs = true; + } else if (options.allowBooleanAttributes) { + attrs[aName] = true; + hasAttrs = true; + } + } + } + + if (!hasAttrs) return; + + if (options.attributesGroupName) { + const attrCollection = {}; + attrCollection[options.attributesGroupName] = attrs; + return attrCollection; + } + return attrs; + } +} +const parseXml = function (xmlData) { + xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line + const xmlObj = new xmlNode('!xml'); + let currentNode = xmlObj; + let textData = ""; + + // Reset matcher for new document + this.matcher.reset(); + this.entityDecoder.reset(); + + // Reset entity expansion counters for this document + this.entityExpansionCount = 0; + this.currentExpandedLength = 0; + const options = this.options; + const docTypeReader = new DocTypeReader(options.processEntities); + const xmlLen = xmlData.length; + for (let i = 0; i < xmlLen; i++) {//for each char in XML data + const ch = xmlData[i]; + if (ch === '<') { + // const nextIndex = i+1; + // const _2ndChar = xmlData[nextIndex]; + const c1 = xmlData.charCodeAt(i + 1); + if (c1 === 47) {//Closing Tag '/' + const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.") + let tagName = xmlData.substring(i + 2, closeIndex).trim(); + + if (options.removeNSPrefix) { + const colonIndex = tagName.indexOf(":"); + if (colonIndex !== -1) { + tagName = tagName.substr(colonIndex + 1); + } + } + + tagName = transformTagName(options.transformTagName, tagName, "", options).tagName; + + if (currentNode) { + textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher); + } + + //check if last tag of nested tag was unpaired tag + const lastTagName = this.matcher.getCurrentTag(); + if (tagName && options.unpairedTagsSet.has(tagName)) { + throw new Error(`Unpaired tag can not be used as closing tag: `); + } + if (lastTagName && options.unpairedTagsSet.has(lastTagName)) { + // Pop the unpaired tag + this.matcher.pop(); + this.tagsNodeStack.pop(); + } + // Pop the closing tag + this.matcher.pop(); + this.isCurrentNodeStopNode = false; // Reset flag when closing tag + + currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope + textData = ""; + i = closeIndex; + } else if (c1 === 63) { //'?' + + let tagData = readTagExp(xmlData, i, false, "?>"); + if (!tagData) throw new Error("Pi Tag is not closed."); + + textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher); + const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true); + if (attsMap) { + const ver = attsMap[this.options.attributeNamePrefix + "version"]; + this.entityDecoder.setXmlVersion(Number(ver) || 1.0); + } + if ((options.ignoreDeclaration && tagData.tagName === "?xml") || options.ignorePiTags) { + //do nothing + } else { + + const childNode = new xmlNode(tagData.tagName); + childNode.add(options.textNodeName, ""); + + if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) { + childNode[":@"] = attsMap + } + this.addChild(currentNode, childNode, this.readonlyMatcher, i); + } + + + i = tagData.closeIndex + 1; + } else if (c1 === 33 + && xmlData.charCodeAt(i + 2) === 45 + && xmlData.charCodeAt(i + 3) === 45) { //'!--' + const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed.") + if (options.commentPropName) { + const comment = xmlData.substring(i + 4, endIndex - 2); + + textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher); + + currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]); + } + i = endIndex; + } else if (c1 === 33 + && xmlData.charCodeAt(i + 2) === 68) { //'!D' + const result = docTypeReader.readDocType(xmlData, i); + this.entityDecoder.addInputEntities(result.entities); + i = result.i; + } else if (c1 === 33 + && xmlData.charCodeAt(i + 2) === 91) { // '![' + const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; + const tagExp = xmlData.substring(i + 9, closeIndex); + + textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher); + + let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true); + if (val == undefined) val = ""; + + //cdata should be set even if it is 0 length string + if (options.cdataPropName) { + currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]); + } else { + currentNode.add(options.textNodeName, val); + } + + i = closeIndex + 2; + } else {//Opening tag + let result = readTagExp(xmlData, i, options.removeNSPrefix); + + // Safety check: readTagExp can return undefined + if (!result) { + // Log context for debugging + const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50)); + throw new Error(`readTagExp returned undefined at position ${i}. Context: "${context}"`); + } + + let tagName = result.tagName; + const rawTagName = result.rawTagName; + let tagExp = result.tagExp; + let attrExpPresent = result.attrExpPresent; + let closeIndex = result.closeIndex; + + ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options)); + + if (options.strictReservedNames && + (tagName === options.commentPropName + || tagName === options.cdataPropName + || tagName === options.textNodeName + || tagName === options.attributesGroupName + )) { + throw new Error(`Invalid tag name: ${tagName}`); + } + + //save text as child node + if (currentNode && textData) { + if (currentNode.tagname !== '!xml') { + //when nested tag is found + textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false); + } + } + + //check if last tag was unpaired tag + const lastTag = currentNode; + if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) { + currentNode = this.tagsNodeStack.pop(); + this.matcher.pop(); + } + + // Clean up self-closing syntax BEFORE processing attributes + // This is where tagExp gets the trailing / removed + let isSelfClosing = false; + if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { + isSelfClosing = true; + if (tagName[tagName.length - 1] === "/") { + tagName = tagName.substr(0, tagName.length - 1); + tagExp = tagName; + } else { + tagExp = tagExp.substr(0, tagExp.length - 1); + } + + // Re-check attrExpPresent after cleaning + attrExpPresent = (tagName !== tagExp); + } + + // Now process attributes with CLEAN tagExp (no trailing /) + let prefixedAttrs = null; + let rawAttrs = {}; + let namespace = undefined; + + // Extract namespace from rawTagName + namespace = extractNamespace(rawTagName); + + // Push tag to matcher FIRST (with empty attrs for now) so callbacks see correct path + if (tagName !== xmlObj.tagname) { + this.matcher.push(tagName, {}, namespace); + } + + // Now build attributes - callbacks will see correct matcher state + if (tagName !== tagExp && attrExpPresent) { + // Build attributes (returns prefixed attributes for the tree) + // Note: buildAttributesMap now internally updates the matcher with raw attributes + prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName); + + if (prefixedAttrs) { + // Extract raw attributes (without prefix) for our use + //TODO: seems a performance overhead + rawAttrs = extractRawAttributes(prefixedAttrs, options); + } + } + + // Now check if this is a stop node (after attributes are set) + if (tagName !== xmlObj.tagname) { + this.isCurrentNodeStopNode = this.isItStopNode(); + } + + const startIndex = i; + if (this.isCurrentNodeStopNode) { + let tagContent = ""; + + // For self-closing tags, content is empty + if (isSelfClosing) { + i = result.closeIndex; + } + //unpaired tag + else if (options.unpairedTagsSet.has(tagName)) { + i = result.closeIndex; + } + //normal tag + else { + //read until closing tag is found + const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); + if (!result) throw new Error(`Unexpected end of ${rawTagName}`); + i = result.i; + tagContent = result.tagContent; + } + + const childNode = new xmlNode(tagName); + + if (prefixedAttrs) { + childNode[":@"] = prefixedAttrs; + } + + // For stop nodes, store raw content as-is without any processing + childNode.add(options.textNodeName, tagContent); + + this.matcher.pop(); // Pop the stop node tag + this.isCurrentNodeStopNode = false; // Reset flag + + this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex); + } else { + //selfClosing tag + if (isSelfClosing) { + ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options)); + + const childNode = new xmlNode(tagName); + if (prefixedAttrs) { + childNode[":@"] = prefixedAttrs; + } + this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex); + this.matcher.pop(); // Pop self-closing tag + this.isCurrentNodeStopNode = false; // Reset flag + } + else if (options.unpairedTagsSet.has(tagName)) {//unpaired tag + const childNode = new xmlNode(tagName); + if (prefixedAttrs) { + childNode[":@"] = prefixedAttrs; + } + this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex); + this.matcher.pop(); // Pop unpaired tag + this.isCurrentNodeStopNode = false; // Reset flag + i = result.closeIndex; + // Continue to next iteration without changing currentNode + continue; + } + //opening tag + else { + const childNode = new xmlNode(tagName); + if (this.tagsNodeStack.length > options.maxNestedTags) { + throw new Error("Maximum nested tags exceeded"); + } + this.tagsNodeStack.push(currentNode); + + if (prefixedAttrs) { + childNode[":@"] = prefixedAttrs; + } + this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex); + currentNode = childNode; + } + textData = ""; + i = closeIndex; + } + } + } else { + textData += xmlData[i]; + } + } + return xmlObj.child; +} + +function addChild(currentNode, childNode, matcher, startIndex) { + // unset startIndex if not requested + if (!this.options.captureMetaData) startIndex = undefined; + + // Pass jPath string or matcher based on options.jPath setting + const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher; + const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[":@"]) + if (result === false) { + //do nothing + } else if (typeof result === "string") { + childNode.tagname = result + currentNode.addChild(childNode, startIndex); + } else { + currentNode.addChild(childNode, startIndex); + } +} + +/** + * @param {object} val - Entity object with regex and val properties + * @param {string} tagName - Tag name + * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath + */ +function replaceEntitiesValue(val, tagName, jPath) { + const entityConfig = this.options.processEntities; + + if (!entityConfig || !entityConfig.enabled) { + return val; + } + + // Check if tag is allowed to contain entities + if (entityConfig.allowedTags) { + const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath; + const allowed = Array.isArray(entityConfig.allowedTags) + ? entityConfig.allowedTags.includes(tagName) + : entityConfig.allowedTags(tagName, jPathOrMatcher); + + if (!allowed) { + return val; + } + } + + // Apply custom tag filter if provided + if (entityConfig.tagFilter) { + const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath; + if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) { + return val; // Skip based on custom filter + } + } + + return this.entityDecoder.decode(val); +} + + +function saveTextToParentTag(textData, parentNode, matcher, isLeafNode) { + if (textData) { //store previously collected data as textNode + if (isLeafNode === undefined) isLeafNode = parentNode.child.length === 0 + + textData = this.parseTextData(textData, + parentNode.tagname, + matcher, + false, + parentNode[":@"] ? Object.keys(parentNode[":@"]).length !== 0 : false, + isLeafNode); + + if (textData !== undefined && textData !== "") + parentNode.add(this.options.textNodeName, textData); + textData = ""; + } + return textData; +} + +/** + * @param {Array} stopNodeExpressions - Array of compiled Expression objects + * @param {Matcher} matcher - Current path matcher + */ +function isItStopNode() { + if (this.stopNodeExpressionsSet.size === 0) return false; + + return this.matcher.matchesAny(this.stopNodeExpressionsSet); +} + +/** + * Returns the tag Expression and where it is ending handling single-double quotes situation + * @param {string} xmlData + * @param {number} i starting index + * @returns + */ +function tagExpWithClosingIndex(xmlData, i, closingChar = ">") { + let attrBoundary = 0; + const chars = []; + const len = xmlData.length; + const closeCode0 = closingChar.charCodeAt(0); + const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1; + + for (let index = i; index < len; index++) { + const code = xmlData.charCodeAt(index); + + if (attrBoundary) { + if (code === attrBoundary) attrBoundary = 0; + } else if (code === 34 || code === 39) { // " or ' + attrBoundary = code; + } else if (code === closeCode0) { + if (closeCode1 !== -1) { + if (xmlData.charCodeAt(index + 1) === closeCode1) { + return { data: String.fromCharCode(...chars), index }; + } + } else { + return { data: String.fromCharCode(...chars), index }; + } + } else if (code === 9) { // \t + chars.push(32); // space + continue; + } + + chars.push(code); + } +} + +function findClosingIndex(xmlData, str, i, errMsg) { + const closingIndex = xmlData.indexOf(str, i); + if (closingIndex === -1) { + throw new Error(errMsg) + } else { + return closingIndex + str.length - 1; + } +} + +function findClosingChar(xmlData, char, i, errMsg) { + const closingIndex = xmlData.indexOf(char, i); + if (closingIndex === -1) throw new Error(errMsg); + return closingIndex; // no offset needed +} + +function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") { + const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar); + if (!result) return; + let tagExp = result.data; + const closeIndex = result.index; + const separatorIndex = tagExp.search(/\s/); + let tagName = tagExp; + let attrExpPresent = true; + if (separatorIndex !== -1) {//separate tag name and attributes expression + tagName = tagExp.substring(0, separatorIndex); + tagExp = tagExp.substring(separatorIndex + 1).trimStart(); + } + + const rawTagName = tagName; + if (removeNSPrefix) { + const colonIndex = tagName.indexOf(":"); + if (colonIndex !== -1) { + tagName = tagName.substr(colonIndex + 1); + attrExpPresent = tagName !== result.data.substr(colonIndex + 1); + } + } + + return { + tagName: tagName, + tagExp: tagExp, + closeIndex: closeIndex, + attrExpPresent: attrExpPresent, + rawTagName: rawTagName, + } +} +/** + * find paired tag for a stop node + * @param {string} xmlData + * @param {string} tagName + * @param {number} i + */ +function readStopNodeData(xmlData, tagName, i) { + const startIndex = i; + // Starting at 1 since we already have an open tag + let openTagCount = 1; + + const xmllen = xmlData.length; + for (; i < xmllen; i++) { + if (xmlData[i] === "<") { + const c1 = xmlData.charCodeAt(i + 1); + if (c1 === 47) {//close tag '/' + const closeIndex = findClosingChar(xmlData, ">", i, `${tagName} is not closed`); + let closeTagName = xmlData.substring(i + 2, closeIndex).trim(); + if (closeTagName === tagName) { + openTagCount--; + if (openTagCount === 0) { + return { + tagContent: xmlData.substring(startIndex, i), + i: closeIndex + } + } + } + i = closeIndex; + } else if (c1 === 63) { //? + const closeIndex = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed.") + i = closeIndex; + } else if (c1 === 33 + && xmlData.charCodeAt(i + 2) === 45 + && xmlData.charCodeAt(i + 3) === 45) { // '!--' + const closeIndex = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed.") + i = closeIndex; + } else if (c1 === 33 + && xmlData.charCodeAt(i + 2) === 91) { // '![' + const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; + i = closeIndex; + } else { + const tagData = readTagExp(xmlData, i, '>') + + if (tagData) { + const openTagName = tagData && tagData.tagName; + if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") { + openTagCount++; + } + i = tagData.closeIndex; + } + } + } + }//end for loop +} + +function parseValue(val, shouldParse, options) { + if (shouldParse && typeof val === 'string') { + //console.log(options) + const newval = val.trim(); + if (newval === 'true') return true; + else if (newval === 'false') return false; + else return toNumber(val, options); + } else { + if (isExist(val)) { + return val; + } else { + return ''; + } + } +} + +function fromCodePoint(str, base, prefix) { + const codePoint = Number.parseInt(str, base); + + if (codePoint >= 0 && codePoint <= 0x10FFFF) { + return String.fromCodePoint(codePoint); + } else { + return prefix + str + ";"; + } +} + +function transformTagName(fn, tagName, tagExp, options) { + if (fn) { + const newTagName = fn(tagName); + if (tagExp === tagName) { + tagExp = newTagName + } + tagName = newTagName; + } + tagName = sanitizeName(tagName, options); + return { tagName, tagExp }; +} + + + +function sanitizeName(name, options) { + if (criticalProperties.includes(name)) { + throw new Error(`[SECURITY] Invalid name: "${name}" is a reserved JavaScript keyword that could cause prototype pollution`); + } else if (DANGEROUS_PROPERTY_NAMES.includes(name)) { + return options.onDangerousProperty(name); + } + return name; +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js b/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js new file mode 100644 index 0000000..292efa1 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js @@ -0,0 +1,71 @@ +import { buildOptions } from './OptionsBuilder.js'; +import OrderedObjParser from './OrderedObjParser.js'; +import prettify from './node2json.js'; +import { validate } from "../validator.js"; +import XmlNode from './xmlNode.js'; + +export default class XMLParser { + + constructor(options) { + this.externalEntities = {}; + this.options = buildOptions(options); + + } + /** + * Parse XML dats to JS object + * @param {string|Uint8Array} xmlData + * @param {boolean|Object} validationOption + */ + parse(xmlData, validationOption) { + if (typeof xmlData !== "string" && xmlData.toString) { + xmlData = xmlData.toString(); + } else if (typeof xmlData !== "string") { + throw new Error("XML data is accepted in String or Bytes[] form.") + } + + if (validationOption) { + if (validationOption === true) validationOption = {}; //validate with default options + + const result = validate(xmlData, validationOption); + if (result !== true) { + throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`) + } + } + const orderedObjParser = new OrderedObjParser(this.options); + orderedObjParser.entityDecoder.setExternalEntities(this.externalEntities); + const orderedResult = orderedObjParser.parseXml(xmlData); + if (this.options.preserveOrder || orderedResult === undefined) return orderedResult; + else return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher); + } + + /** + * Add Entity which is not by default supported by this library + * @param {string} key + * @param {string} value + */ + addEntity(key, value) { + if (value.indexOf("&") !== -1) { + throw new Error("Entity value can't have '&'") + } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) { + throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") + } else if (value === "&") { + throw new Error("An entity with value '&' is not permitted"); + } else { + this.externalEntities[key] = value; + } + } + + /** + * Returns a Symbol that can be used to access the metadata + * property on a node. + * + * If Symbol is not available in the environment, an ordinary property is used + * and the name of the property is here returned. + * + * The XMLMetaData property is only present when `captureMetaData` + * is true in the options. + */ + static getMetaDataSymbol() { + return XmlNode.getMetaDataSymbol(); + } +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/node2json.js b/node_modules/fast-xml-parser/src/xmlparser/node2json.js new file mode 100644 index 0000000..c31968a --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/node2json.js @@ -0,0 +1,173 @@ +'use strict'; + +import XmlNode from './xmlNode.js'; +import { Matcher } from 'path-expression-matcher'; + +const METADATA_SYMBOL = XmlNode.getMetaDataSymbol(); + +/** + * Helper function to strip attribute prefix from attribute map + * @param {object} attrs - Attributes with prefix (e.g., {"@_class": "code"}) + * @param {string} prefix - Attribute prefix to remove (e.g., "@_") + * @returns {object} Attributes without prefix (e.g., {"class": "code"}) + */ +function stripAttributePrefix(attrs, prefix) { + if (!attrs || typeof attrs !== 'object') return {}; + if (!prefix) return attrs; + + const rawAttrs = {}; + for (const key in attrs) { + if (key.startsWith(prefix)) { + const rawName = key.substring(prefix.length); + rawAttrs[rawName] = attrs[key]; + } else { + // Attribute without prefix (shouldn't normally happen, but be safe) + rawAttrs[key] = attrs[key]; + } + } + return rawAttrs; +} + +/** + * + * @param {array} node + * @param {any} options + * @param {Matcher} matcher - Path matcher instance + * @returns + */ +export default function prettify(node, options, matcher, readonlyMatcher) { + return compress(node, options, matcher, readonlyMatcher); +} + +/** + * @param {array} arr + * @param {object} options + * @param {Matcher} matcher - Path matcher instance + * @returns object + */ +function compress(arr, options, matcher, readonlyMatcher) { + let text; + const compressedObj = {}; //This is intended to be a plain object + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const property = propName(tagObj); + + // Push current property to matcher WITH RAW ATTRIBUTES (no prefix) + if (property !== undefined && property !== options.textNodeName) { + const rawAttrs = stripAttributePrefix( + tagObj[":@"] || {}, + options.attributeNamePrefix + ); + matcher.push(property, rawAttrs); + } + + if (property === options.textNodeName) { + if (text === undefined) text = tagObj[property]; + else text += "" + tagObj[property]; + } else if (property === undefined) { + continue; + } else if (tagObj[property]) { + + let val = compress(tagObj[property], options, matcher, readonlyMatcher); + const isLeaf = isLeafTag(val, options); + + if (tagObj[":@"]) { + assignAttributes(val, tagObj[":@"], readonlyMatcher, options); + } else if (Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode) { + val = val[options.textNodeName]; + } else if (Object.keys(val).length === 0) { + if (options.alwaysCreateTextNode) val[options.textNodeName] = ""; + else val = ""; + } + + if (tagObj[METADATA_SYMBOL] !== undefined && typeof val === "object" && val !== null) { + val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL]; // copy over metadata + } + + + if (compressedObj[property] !== undefined && Object.prototype.hasOwnProperty.call(compressedObj, property)) { + if (!Array.isArray(compressedObj[property])) { + compressedObj[property] = [compressedObj[property]]; + } + compressedObj[property].push(val); + } else { + //TODO: if a node is not an array, then check if it should be an array + //also determine if it is a leaf node + + // Pass jPath string or readonlyMatcher based on options.jPath setting + const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher; + if (options.isArray(property, jPathOrMatcher, isLeaf)) { + compressedObj[property] = [val]; + } else { + compressedObj[property] = val; + } + } + + // Pop property from matcher after processing + if (property !== undefined && property !== options.textNodeName) { + matcher.pop(); + } + } + + } + // if(text && text.length > 0) compressedObj[options.textNodeName] = text; + if (typeof text === "string") { + if (text.length > 0) compressedObj[options.textNodeName] = text; + } else if (text !== undefined) compressedObj[options.textNodeName] = text; + + + return compressedObj; +} + +function propName(obj) { + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (key !== ":@") return key; + } +} + +function assignAttributes(obj, attrMap, readonlyMatcher, options) { + if (attrMap) { + const keys = Object.keys(attrMap); + const len = keys.length; //don't make it inline + for (let i = 0; i < len; i++) { + const atrrName = keys[i]; // This is the PREFIXED name (e.g., "@_class") + + // Strip prefix for matcher path (for isArray callback) + const rawAttrName = atrrName.startsWith(options.attributeNamePrefix) + ? atrrName.substring(options.attributeNamePrefix.length) + : atrrName; + + // For attributes, we need to create a temporary path + // Pass jPath string or matcher based on options.jPath setting + const jPathOrMatcher = options.jPath + ? readonlyMatcher.toString() + "." + rawAttrName + : readonlyMatcher; + + if (options.isArray(atrrName, jPathOrMatcher, true, true)) { + obj[atrrName] = [attrMap[atrrName]]; + } else { + obj[atrrName] = attrMap[atrrName]; + } + } + } +} + +function isLeafTag(obj, options) { + const { textNodeName } = options; + const propCount = Object.keys(obj).length; + + if (propCount === 0) { + return true; + } + + if ( + propCount === 1 && + (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0) + ) { + return true; + } + + return false; +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js b/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js new file mode 100644 index 0000000..4223a8d --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js @@ -0,0 +1,40 @@ +'use strict'; + +let METADATA_SYMBOL; + +if (typeof Symbol !== "function") { + METADATA_SYMBOL = "@@xmlMetadata"; +} else { + METADATA_SYMBOL = Symbol("XML Node Metadata"); +} + +export default class XmlNode { + constructor(tagname) { + this.tagname = tagname; + this.child = []; //nested tags, text, cdata, comments in order + this[":@"] = Object.create(null); //attributes map + } + add(key, val) { + // this.child.push( {name : key, val: val, isCdata: isCdata }); + if (key === "__proto__") key = "#__proto__"; + this.child.push({ [key]: val }); + } + addChild(node, startIndex) { + if (node.tagname === "__proto__") node.tagname = "#__proto__"; + if (node[":@"] && Object.keys(node[":@"]).length > 0) { + this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] }); + } else { + this.child.push({ [node.tagname]: node.child }); + } + // if requested, add the startIndex + if (startIndex !== undefined) { + // Note: for now we just overwrite the metadata. If we had more complex metadata, + // we might need to do an object append here: metadata = { ...metadata, startIndex } + this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex }; + } + } + /** symbol used for metadata */ + static getMetaDataSymbol() { + return METADATA_SYMBOL; + } +} diff --git a/node_modules/filter-obj/index.js b/node_modules/filter-obj/index.js new file mode 100644 index 0000000..c462e03 --- /dev/null +++ b/node_modules/filter-obj/index.js @@ -0,0 +1,17 @@ +'use strict'; +module.exports = function (obj, predicate) { + var ret = {}; + var keys = Object.keys(obj); + var isArr = Array.isArray(predicate); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var val = obj[key]; + + if (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) { + ret[key] = val; + } + } + + return ret; +}; diff --git a/node_modules/filter-obj/license b/node_modules/filter-obj/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/filter-obj/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/filter-obj/package.json b/node_modules/filter-obj/package.json new file mode 100644 index 0000000..0705b90 --- /dev/null +++ b/node_modules/filter-obj/package.json @@ -0,0 +1,37 @@ +{ + "name": "filter-obj", + "version": "1.1.0", + "description": "Filter object keys and values into a new object", + "license": "MIT", + "repository": "sindresorhus/filter-obj", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && node test.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "filter", + "obj", + "object", + "key", + "keys", + "value", + "values", + "val", + "iterate", + "iterator" + ], + "devDependencies": { + "ava": "0.0.4", + "xo": "*" + } +} diff --git a/node_modules/filter-obj/readme.md b/node_modules/filter-obj/readme.md new file mode 100644 index 0000000..6de3c59 --- /dev/null +++ b/node_modules/filter-obj/readme.md @@ -0,0 +1,41 @@ +# filter-obj [![Build Status](https://travis-ci.org/sindresorhus/filter-obj.svg?branch=master)](https://travis-ci.org/sindresorhus/filter-obj) + +> Filter object keys and values into a new object + + +## Install + +``` +$ npm install --save filter-obj +``` + + +## Usage + +```js +var filterObj = require('filter-obj'); + +var obj = { + foo: true, + bar: false +}; + +var newObject = filterObj(obj, function (key, value, object) { + return value === true; +}); +//=> {foo: true} + +var newObject2 = filterObj(obj, ['bar']); +//=> {bar: true} +``` + + +## Related + +- [map-obj](https://github.com/sindresorhus/map-obj) - Map object keys and values into a new object +- [object-assign](https://github.com/sindresorhus/object-assign) - Copy enumerable own properties from one or more source objects to a target object + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 0000000..f71f2d9 --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,9 @@ +try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..86bbb3d --- /dev/null +++ b/node_modules/inherits/inherits_browser.js @@ -0,0 +1,27 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 0000000..37b4366 --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,29 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.4", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": "git://github.com/isaacs/inherits", + "license": "ISC", + "scripts": { + "test": "tap" + }, + "devDependencies": { + "tap": "^14.2.4" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ] +} diff --git a/node_modules/ipaddr.js/LICENSE b/node_modules/ipaddr.js/LICENSE new file mode 100644 index 0000000..f6b37b5 --- /dev/null +++ b/node_modules/ipaddr.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011-2017 whitequark + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/ipaddr.js/README.md b/node_modules/ipaddr.js/README.md new file mode 100644 index 0000000..a8ceff6 --- /dev/null +++ b/node_modules/ipaddr.js/README.md @@ -0,0 +1,233 @@ +# ipaddr.js — an IPv6 and IPv4 address manipulation library + +[![Build Status](https://github.com/whitequark/ipaddr.js/workflows/CI%20Tests/badge.svg)](https://github.com/whitequark/ipaddr.js/actions?query=workflow%3A%22CI+Tests%22) + +ipaddr.js is a small (1.9K minified and gzipped) library for manipulating +IP addresses in JavaScript environments. It runs on both CommonJS runtimes +(e.g. [nodejs]) and in a web browser. + +ipaddr.js allows you to verify and parse string representation of an IP +address, match it against a CIDR range or range list, determine if it falls +into some reserved ranges (examples include loopback and private ranges), +and convert between IPv4 and IPv4-mapped IPv6 addresses. + +[nodejs]: http://nodejs.org + +## Installation + +`npm install ipaddr.js` + +or + +`bower install ipaddr.js` + +## Older Node support + +Use 2.x release for nodejs versions 10+. +Use the 1.x release for versions of nodejs older than 10. + +## API + +ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, +it is exported from the module: + +```js +const ipaddr = require('ipaddr.js'); +``` + +The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. + +### Global methods + +There are four global methods defined: `ipaddr.isValid`, `ipaddr.isValidCIDR`, +`ipaddr.parse`, and `ipaddr.process`. All of them receive a string as a single +parameter. + +The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or +IPv6 address, and `false` otherwise. It does not throw any exceptions. + +The `ipaddr.isValidCIDR` method returns `true` if the address is a valid IPv4 or +IPv6 address in CIDR notation, and `false` otherwise. It does not throw any exceptions. + +The `ipaddr.parse` method returns an object representing the IP address, +or throws an `Error` if the passed string is not a valid representation of an +IP address. + +The `ipaddr.process` method works just like the `ipaddr.parse` one, but it +automatically converts IPv4-mapped IPv6 addresses to their IPv4 counterparts +before returning. It is useful when you have a Node.js instance listening +on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its +equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 +connections on your IPv6-only socket, but the remote address will be mangled. +Use `ipaddr.process` method to automatically demangle it. + +### Object representation + +Parsing methods return an object which descends from `ipaddr.IPv6` or +`ipaddr.IPv4`. These objects share some properties, but most of them differ. + +#### Shared properties + +One can determine the type of address by calling `addr.kind()`. It will return +either `"ipv6"` or `"ipv4"`. + +An address can be converted back to its string representation with `addr.toString()`. +Note that this method: + * does not return the original string used to create the object (in fact, there is + no way of getting that string) + * returns a compact representation (when it is applicable) + +A `match(range, bits)` method can be used to check if the address falls into a +certain CIDR range. Note that an address can be (obviously) matched only against an address of the same type. + +For example: + +```js +const addr = ipaddr.parse('2001:db8:1234::1'); +const range = ipaddr.parse('2001:db8::'); + +addr.match(range, 32); // => true +``` + +Alternatively, `match` can also be called as `match([range, bits])`. In this way, it can be used together with the `parseCIDR(string)` method, which parses an IP address together with a CIDR range. + +For example: + +```js +const addr = ipaddr.parse('2001:db8:1234::1'); + +addr.match(ipaddr.parseCIDR('2001:db8::/32')); // => true +``` + +A `range()` method returns one of predefined names for several special ranges defined by IP protocols. The exact names (and their respective CIDR ranges) can be looked up in the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `"unicast"` (the default one) and `"reserved"`. + +You can match against your own range list by using +`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with a mix of IPv6 or IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: + +```js +const rangeList = { + documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], + tunnelProviders: [ + [ ipaddr.parse('2001:470::'), 32 ], // he.net + [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 + ] +}; +ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "tunnelProviders" +``` + +The addresses can be converted to their byte representation with `toByteArray()`. (Actually, JavaScript mostly does not know about byte buffers. They are emulated with arrays of numbers, each in range of 0..255.) + +```js +const bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com +bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ] +``` + +The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them have the same interface for both protocols, and are similar to global methods. + +`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. + +`ipaddr.IPvX.isValid(string)` uses the same format for parsing as the POSIX `inet_ntoa` function, which accepts unusual formats like `0xc0.168.1.1` or `0x10000000`. The function `ipaddr.IPv4.isValidFourPartDecimal(string)` validates the IPv4 address and also ensures that it is written in four-part decimal format. +`ipaddr.IPv4.isValidCIDRFourPartDecimal(string)` validates an IPv4 address in CIDR notation and also ensures that its address portion is written in four-part decimal format. + +[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/lib/ipaddr.js#L530 +[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/lib/ipaddr.js#L182 + +#### IPv6 properties + +Sometimes you will want to convert IPv6 not to a compact string representation (with the `::` substitution); the `toNormalizedString()` method will return an address where all zeroes are explicit. + +For example: + +```js +const addr = ipaddr.parse('2001:0db8::0001'); +addr.toString(); // => '2001:db8::1' +addr.toNormalizedString(); // => '2001:db8:0:0:0:0:0:1' +``` + +The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped +one, and `toIPv4Address()` will return an IPv4 object address. + +To access the underlying binary representation of the address, use `addr.parts`. + +```js +const addr = ipaddr.parse('2001:db8:10::1234:DEAD'); +addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] +``` + +A IPv6 zone index can be accessed via `addr.zoneId`: + +```js +const addr = ipaddr.parse('2001:db8::%eth0'); +addr.zoneId // => 'eth0' +``` + +#### IPv4 properties + +`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. + +To access the underlying representation of the address, use `addr.octets`. + +```js +const addr = ipaddr.parse('192.168.1.1'); +addr.octets // => [192, 168, 1, 1] +``` + +`prefixLengthFromSubnetMask()` will return a CIDR prefix length for a valid IPv4 netmask or +null if the netmask is not valid. + +```js +ipaddr.IPv4.parse('255.255.255.240').prefixLengthFromSubnetMask() == 28 +ipaddr.IPv4.parse('255.192.164.0').prefixLengthFromSubnetMask() == null +``` + +`subnetMaskFromPrefixLength()` will return an IPv4 netmask for a valid CIDR prefix length. + +```js +ipaddr.IPv4.subnetMaskFromPrefixLength(24) == '255.255.255.0' +ipaddr.IPv4.subnetMaskFromPrefixLength(29) == '255.255.255.248' +``` + +`broadcastAddressFromCIDR()` will return the broadcast address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.broadcastAddressFromCIDR('172.0.0.1/24') == '172.0.0.255' +``` +`networkAddressFromCIDR()` will return the network address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.networkAddressFromCIDR('172.0.0.1/24') == '172.0.0.0' +``` + +#### Conversion + +IPv4 and IPv6 can be converted bidirectionally to and from network byte order (MSB) byte arrays. + +The `fromByteArray()` method will take an array and create an appropriate IPv4 or IPv6 object +if the input satisfies the requirements. For IPv4 it has to be an array of four 8-bit values, +while for IPv6 it has to be an array of sixteen 8-bit values. + +For example: +```js +const addr = ipaddr.fromByteArray([0x7f, 0, 0, 1]); +addr.toString(); // => '127.0.0.1' +``` + +or + +```js +const addr = ipaddr.fromByteArray([0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) +addr.toString(); // => '2001:db8::1' +``` + +Both objects also offer a `toByteArray()` method, which returns an array in network byte order (MSB). + +For example: +```js +const addr = ipaddr.parse('127.0.0.1'); +addr.toByteArray(); // => [0x7f, 0, 0, 1] +``` + +or + +```js +const addr = ipaddr.parse('2001:db8::1'); +addr.toByteArray(); // => [0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] +``` diff --git a/node_modules/ipaddr.js/ipaddr.min.js b/node_modules/ipaddr.js/ipaddr.min.js new file mode 100644 index 0000000..03da67e --- /dev/null +++ b/node_modules/ipaddr.js/ipaddr.min.js @@ -0,0 +1 @@ +!function(t){!function(t){"use strict";const r="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp(`^${r}\\.${r}\\.${r}\\.${r}$`,"i"),threeOctet:new RegExp(`^${r}\\.${r}\\.${r}$`,"i"),twoOctet:new RegExp(`^${r}\\.${r}$`,"i"),longValue:new RegExp(`^${r}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),o="(?:[0-9a-f]+::?)+",s={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp(`^(::)?(${o})?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${r}\\.${r}\\.${r}\\.${r}(%[0-9a-z]{1,})?)$`,"i"),transitional:new RegExp(`^((?:${o})|(?:::)(?:${o})?)${r}\\.${r}\\.${r}\\.${r}(%[0-9a-z]{1,})?$`,"i")};function a(t,r){if(t.indexOf("::")!==t.lastIndexOf("::"))return null;let e,n,i=0,o=-1,a=(t.match(s.zoneIndex)||[])[0];for(a&&(a=a.substring(1),t=t.replace(/%.+$/,""));(o=t.indexOf(":",o+1))>=0;)i++;if("::"===t.substr(0,2)&&i--,"::"===t.substr(-2,2)&&i--,i>r)return null;for(n=r-i,e=":";n--;)e+="0:";return":"===(t=t.replace("::",e))[0]&&(t=t.slice(1)),":"===t[t.length-1]&&(t=t.slice(0,-1)),{parts:r=function(){const r=t.split(":"),e=[];for(let t=0;t0;){if((i=e-n)<0&&(i=0),t[o]>>i!=r[o]>>i)return!1;n-=e,o+=1}return!0}function u(t){if(i.test(t))return parseInt(t,16);if("0"===t[0]&&!isNaN(parseInt(t[1],10))){if(n.test(t))return parseInt(t,8);throw new Error(`ipaddr: cannot parse ${t} as octal`)}return parseInt(t,10)}function d(t,r){for(;t.length=0;n-=1){if(!((i=this.octets[n])in e))return null;if(o=e[i],r&&0!==o)return null;8!==o&&(r=!0),t+=o}return 32-t},t.prototype.range=function(){return c.subnetMatch(this,this.SpecialRanges)},t.prototype.toByteArray=function(){return this.octets.slice(0)},t.prototype.toIPv4MappedAddress=function(){return c.IPv6.parse(`::ffff:${this.toString()}`)},t.prototype.toNormalizedString=function(){return this.toString()},t.prototype.toString=function(){return this.octets.join(".")},t}(),c.IPv4.broadcastAddressFromCIDR=function(t){try{const r=this.parseCIDR(t),e=r[0].toByteArray(),n=this.subnetMaskFromPrefixLength(r[1]).toByteArray(),i=[];let o=0;for(;o<4;)i.push(parseInt(e[o],10)|255^parseInt(n[o],10)),o++;return new this(i)}catch(t){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},c.IPv4.isIPv4=function(t){return null!==this.parser(t)},c.IPv4.isValid=function(t){try{return new this(this.parser(t)),!0}catch(t){return!1}},c.IPv4.isValidCIDR=function(t){try{return this.parseCIDR(t),!0}catch(t){return!1}},c.IPv4.isValidFourPartDecimal=function(t){return!(!c.IPv4.isValid(t)||!t.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},c.IPv4.isValidCIDRFourPartDecimal=function(t){const r=t.match(/^(.+)\/(\d+)$/);return!(!c.IPv4.isValidCIDR(t)||!r)&&c.IPv4.isValidFourPartDecimal(r[1])},c.IPv4.networkAddressFromCIDR=function(t){let r,e,n,i,o;try{for(n=(r=this.parseCIDR(t))[0].toByteArray(),o=this.subnetMaskFromPrefixLength(r[1]).toByteArray(),i=[],e=0;e<4;)i.push(parseInt(n[e],10)&parseInt(o[e],10)),e++;return new this(i)}catch(t){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},c.IPv4.parse=function(t){const r=this.parser(t);if(null===r)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(r)},c.IPv4.parseCIDR=function(t){let r;if(r=t.match(/^(.+)\/(\d+)$/)){const t=parseInt(r[2]);if(t>=0&&t<=32){const e=[this.parse(r[1]),t];return Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},c.IPv4.parser=function(t){let r,n,i;if(r=t.match(e.fourOctet))return function(){const t=r.slice(1,6),e=[];for(let r=0;r4294967295||i<0)throw new Error("ipaddr: address outside defined range");return function(){const t=[];let r;for(r=0;r<=24;r+=8)t.push(i>>r&255);return t}().reverse()}return(r=t.match(e.twoOctet))?function(){const t=r.slice(1,4),e=[];if((i=u(t[1]))>16777215||i<0)throw new Error("ipaddr: address outside defined range");return e.push(u(t[0])),e.push(i>>16&255),e.push(i>>8&255),e.push(255&i),e}():(r=t.match(e.threeOctet))?function(){const t=r.slice(1,5),e=[];if((i=u(t[2]))>65535||i<0)throw new Error("ipaddr: address outside defined range");return e.push(u(t[0])),e.push(u(t[1])),e.push(i>>8&255),e.push(255&i),e}():null},c.IPv4.subnetMaskFromPrefixLength=function(t){if((t=parseInt(t))<0||t>32)throw new Error("ipaddr: invalid IPv4 prefix length");const r=[0,0,0,0];let e=0;const n=Math.floor(t/8);for(;e=0;o-=1){if(!((n=this.parts[o])in e))return null;if(i=e[n],r&&0!==i)return null;16!==i&&(r=!0),t+=i}return 128-t},t.prototype.range=function(){return c.subnetMatch(this,this.SpecialRanges)},t.prototype.toByteArray=function(){let t;const r=[],e=this.parts;for(let n=0;n>8),r.push(255&t);return r},t.prototype.toFixedLengthString=function(){const t=function(){const t=[];for(let r=0;r>8,255&r,e>>8,255&e])},t.prototype.toNormalizedString=function(){const t=function(){const t=[];for(let r=0;ri&&(n=e.index,i=e[0].length);return i<0?r:`${r.substring(0,n)}::${r.substring(n+i)}`},t.prototype.toString=function(){return this.toRFC5952String()},t}(),c.IPv6.broadcastAddressFromCIDR=function(t){try{const r=this.parseCIDR(t),e=r[0].toByteArray(),n=this.subnetMaskFromPrefixLength(r[1]).toByteArray(),i=[];let o=0;for(;o<16;)i.push(parseInt(e[o],10)|255^parseInt(n[o],10)),o++;return new this(i)}catch(t){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${t})`)}},c.IPv6.isIPv6=function(t){return null!==this.parser(t)},c.IPv6.isValid=function(t){if("string"==typeof t&&-1===t.indexOf(":"))return!1;try{const r=this.parser(t);return new this(r.parts,r.zoneId),!0}catch(t){return!1}},c.IPv6.isValidCIDR=function(t){if("string"==typeof t&&-1===t.indexOf(":"))return!1;try{return this.parseCIDR(t),!0}catch(t){return!1}},c.IPv6.networkAddressFromCIDR=function(t){let r,e,n,i,o;try{for(n=(r=this.parseCIDR(t))[0].toByteArray(),o=this.subnetMaskFromPrefixLength(r[1]).toByteArray(),i=[],e=0;e<16;)i.push(parseInt(n[e],10)&parseInt(o[e],10)),e++;return new this(i)}catch(t){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${t})`)}},c.IPv6.parse=function(t){const r=this.parser(t);if(null===r.parts)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(r.parts,r.zoneId)},c.IPv6.parseCIDR=function(t){let r,e,n;if((e=t.match(/^(.+)\/(\d+)$/))&&(r=parseInt(e[2]))>=0&&r<=128)return n=[this.parse(e[1]),r],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},c.IPv6.parser=function(t){let r,e,n,i,o,p;if(n=t.match(s.deprecatedTransitional))return this.parser(`::ffff:${n[1]}`);if(s.native.test(t))return a(t,8);if((n=t.match(s.transitional))&&(p=n[6]||"",r=n[1],n[1].endsWith("::")||(r=r.slice(0,-1)),(r=a(r+p,6)).parts)){for(o=[parseInt(n[2]),parseInt(n[3]),parseInt(n[4]),parseInt(n[5])],e=0;e128)throw new Error("ipaddr: invalid IPv6 prefix length");const r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let e=0;const n=Math.floor(t/8);for(;e= 0) { + colonCount++; + } + + // 0::0 is two parts more than :: + if (string.substr(0, 2) === '::') { + colonCount--; + } + + if (string.substr(-2, 2) === '::') { + colonCount--; + } + + // The following loop would hang if colonCount > parts + if (colonCount > parts) { + return null; + } + + // replacement = ':' + '0:' * (parts - colonCount) + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + + // Insert the missing zeroes + string = string.replace('::', replacement); + + // Trim any garbage which may be hanging around if :: was at the edge in + // the source strin + if (string[0] === ':') { + string = string.slice(1); + } + + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + + parts = (function () { + const ref = string.split(':'); + const results = []; + + for (let i = 0; i < ref.length; i++) { + results.push(parseInt(ref[i], 16)); + } + + return results; + })(); + + return { + parts: parts, + zoneId: zoneId + }; + } + + // A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher. + function matchCIDR (first, second, partSize, cidrBits) { + if (first.length !== second.length) { + throw new Error('ipaddr: cannot match CIDR for objects with different lengths'); + } + + let part = 0; + let shift; + + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + + cidrBits -= partSize; + part += 1; + } + + return true; + } + + function parseIntAuto (string) { + // Hexadedimal base 16 (0x#) + if (hexRegex.test(string)) { + return parseInt(string, 16); + } + // While octal representation is discouraged by ECMAScript 3 + // and forbidden by ECMAScript 5, we silently allow it to + // work only if the rest of the string has numbers less than 8. + if (string[0] === '0' && !isNaN(parseInt(string[1], 10))) { + if (octalRegex.test(string)) { + return parseInt(string, 8); + } + throw new Error(`ipaddr: cannot parse ${string} as octal`); + } + // Always include the base 10 radix! + return parseInt(string, 10); + } + + function padPart (part, length) { + while (part.length < length) { + part = `0${part}`; + } + + return part; + } + + const ipaddr = {}; + + // An IPv4 address (RFC791). + ipaddr.IPv4 = (function () { + // Constructs a new IPv4 address from an array of four octets + // in network order (MSB first) + // Verifies the input. + function IPv4 (octets) { + if (octets.length !== 4) { + throw new Error('ipaddr: ipv4 octet count should be 4'); + } + + let i, octet; + + for (i = 0; i < octets.length; i++) { + octet = octets[i]; + if (!((0 <= octet && octet <= 255))) { + throw new Error('ipaddr: ipv4 octet should fit in 8 bits'); + } + } + + this.octets = octets; + } + + // Special IPv4 address ranges. + // See also https://en.wikipedia.org/wiki/Reserved_IP_addresses + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + // RFC3171 + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + // RFC3927 + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + // RFC5735 + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + // RFC6598 + carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], + // RFC1918 + 'private': [ + [new IPv4([10, 0, 0, 0]), 8], + [new IPv4([172, 16, 0, 0]), 12], + [new IPv4([192, 168, 0, 0]), 16] + ], + // Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700 + reserved: [ + [new IPv4([192, 0, 0, 0]), 24], + [new IPv4([192, 0, 2, 0]), 24], + [new IPv4([192, 88, 99, 0]), 24], + [new IPv4([198, 18, 0, 0]), 15], + [new IPv4([198, 51, 100, 0]), 24], + [new IPv4([203, 0, 113, 0]), 24], + [new IPv4([240, 0, 0, 0]), 4] + ], + // RFC7534, RFC7535 + as112: [ + [new IPv4([192, 175, 48, 0]), 24], + [new IPv4([192, 31, 196, 0]), 24], + ], + // RFC7450 + amt: [ + [new IPv4([192, 52, 193, 0]), 24], + ], + }; + + // The 'kind' method exists on both IPv4 and IPv6 classes. + IPv4.prototype.kind = function () { + return 'ipv4'; + }; + + // Checks if this address matches other one within given CIDR range. + IPv4.prototype.match = function (other, cidrRange) { + let ref; + if (cidrRange === undefined) { + ref = other; + other = ref[0]; + cidrRange = ref[1]; + } + + if (other.kind() !== 'ipv4') { + throw new Error('ipaddr: cannot match ipv4 address with non-ipv4 one'); + } + + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + + // returns a number of leading ones in IPv4 address, making sure that + // the rest is a solid sequence of 0's (valid netmask) + // returns either the CIDR length or null if mask is not valid + IPv4.prototype.prefixLengthFromSubnetMask = function () { + let cidr = 0; + // non-zero encountered stop scanning for zeroes + let stop = false; + // number of zeroes in octet + const zerotable = { + 0: 8, + 128: 7, + 192: 6, + 224: 5, + 240: 4, + 248: 3, + 252: 2, + 254: 1, + 255: 0 + }; + let i, octet, zeros; + + for (i = 3; i >= 0; i -= 1) { + octet = this.octets[i]; + if (octet in zerotable) { + zeros = zerotable[octet]; + if (stop && zeros !== 0) { + return null; + } + + if (zeros !== 8) { + stop = true; + } + + cidr += zeros; + } else { + return null; + } + } + + return 32 - cidr; + }; + + // Checks if the address corresponds to one of the special ranges. + IPv4.prototype.range = function () { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + // Returns an array of byte-sized values in network order (MSB first) + IPv4.prototype.toByteArray = function () { + return this.octets.slice(0); + }; + + // Converts this IPv4 address to an IPv4-mapped IPv6 address. + IPv4.prototype.toIPv4MappedAddress = function () { + return ipaddr.IPv6.parse(`::ffff:${this.toString()}`); + }; + + // Symmetrical method strictly for aligning with the IPv6 methods. + IPv4.prototype.toNormalizedString = function () { + return this.toString(); + }; + + // Returns the address in convenient, decimal-dotted format. + IPv4.prototype.toString = function () { + return this.octets.join('.'); + }; + + return IPv4; + })(); + + // A utility function to return broadcast address given the IPv4 interface and prefix length in CIDR notation + ipaddr.IPv4.broadcastAddressFromCIDR = function (string) { + + try { + const cidr = this.parseCIDR(string); + const ipInterfaceOctets = cidr[0].toByteArray(); + const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + const octets = []; + let i = 0; + while (i < 4) { + // Broadcast address is bitwise OR between ip interface and inverted mask + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + + return new this(octets); + } catch (e) { + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + // Checks if a given string is formatted like IPv4 address. + ipaddr.IPv4.isIPv4 = function (string) { + return this.parser(string) !== null; + }; + + // Checks if a given string is a valid IPv4 address. + ipaddr.IPv4.isValid = function (string) { + try { + new this(this.parser(string)); + return true; + } catch (e) { + return false; + } + }; + + // Checks if a given string is a valid IPv4 address in CIDR notation. + ipaddr.IPv4.isValidCIDR = function (string) { + try { + this.parseCIDR(string); + return true; + } catch (e) { + return false; + } + }; + + // Checks if a given string is a full four-part IPv4 Address. + ipaddr.IPv4.isValidFourPartDecimal = function (string) { + if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { + return true; + } else { + return false; + } + }; + + // Checks if a given string is a full four-part IPv4 Address with CIDR prefix. + ipaddr.IPv4.isValidCIDRFourPartDecimal = function (string) { + const match = string.match(/^(.+)\/(\d+)$/); + + if (!ipaddr.IPv4.isValidCIDR(string) || !match) { + return false; + } + + return ipaddr.IPv4.isValidFourPartDecimal(match[1]); + }; + + // A utility function to return network address given the IPv4 interface and prefix length in CIDR notation + ipaddr.IPv4.networkAddressFromCIDR = function (string) { + let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets; + + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + // Network address is bitwise AND between ip interface and mask + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + + return new this(octets); + } catch (e) { + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + // Tries to parse and validate a string with IPv4 address. + // Throws an error if it fails. + ipaddr.IPv4.parse = function (string) { + const parts = this.parser(string); + + if (parts === null) { + throw new Error('ipaddr: string is not formatted like an IPv4 Address'); + } + + return new this(parts); + }; + + // Parses the string as an IPv4 Address with CIDR Notation. + ipaddr.IPv4.parseCIDR = function (string) { + let match; + + if ((match = string.match(/^(.+)\/(\d+)$/))) { + const maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + const parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function () { + return this.join('/'); + } + }); + return parsed; + } + } + + throw new Error('ipaddr: string is not formatted like an IPv4 CIDR range'); + }; + + // Classful variants (like a.b, where a is an octet, and b is a 24-bit + // value representing last three octets; this corresponds to a class C + // address) are omitted due to classless nature of modern Internet. + ipaddr.IPv4.parser = function (string) { + let match, part, value; + + // parseInt recognizes all that octal & hexadecimal weirdness for us + if ((match = string.match(ipv4Regexes.fourOctet))) { + return (function () { + const ref = match.slice(1, 6); + const results = []; + + for (let i = 0; i < ref.length; i++) { + part = ref[i]; + results.push(parseIntAuto(part)); + } + + return results; + })(); + } else if ((match = string.match(ipv4Regexes.longValue))) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error('ipaddr: address outside defined range'); + } + + return ((function () { + const results = []; + let shift; + + for (shift = 0; shift <= 24; shift += 8) { + results.push((value >> shift) & 0xff); + } + + return results; + })()).reverse(); + } else if ((match = string.match(ipv4Regexes.twoOctet))) { + return (function () { + const ref = match.slice(1, 4); + const results = []; + + value = parseIntAuto(ref[1]); + if (value > 0xffffff || value < 0) { + throw new Error('ipaddr: address outside defined range'); + } + + results.push(parseIntAuto(ref[0])); + results.push((value >> 16) & 0xff); + results.push((value >> 8) & 0xff); + results.push( value & 0xff); + + return results; + })(); + } else if ((match = string.match(ipv4Regexes.threeOctet))) { + return (function () { + const ref = match.slice(1, 5); + const results = []; + + value = parseIntAuto(ref[2]); + if (value > 0xffff || value < 0) { + throw new Error('ipaddr: address outside defined range'); + } + + results.push(parseIntAuto(ref[0])); + results.push(parseIntAuto(ref[1])); + results.push((value >> 8) & 0xff); + results.push( value & 0xff); + + return results; + })(); + } else { + return null; + } + }; + + // A utility function to return subnet mask in IPv4 format given the prefix length + ipaddr.IPv4.subnetMaskFromPrefixLength = function (prefix) { + prefix = parseInt(prefix); + if (prefix < 0 || prefix > 32) { + throw new Error('ipaddr: invalid IPv4 prefix length'); + } + + const octets = [0, 0, 0, 0]; + let j = 0; + const filledOctetCount = Math.floor(prefix / 8); + + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + + if (filledOctetCount < 4) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + } + + return new this(octets); + }; + + // An IPv6 address (RFC2460) + ipaddr.IPv6 = (function () { + // Constructs an IPv6 address from an array of eight 16 - bit parts + // or sixteen 8 - bit parts in network order(MSB first). + // Throws an error if the input is invalid. + function IPv6 (parts, zoneId) { + let i, part; + + if (parts.length === 16) { + this.parts = []; + for (i = 0; i <= 14; i += 2) { + this.parts.push((parts[i] << 8) | parts[i + 1]); + } + } else if (parts.length === 8) { + this.parts = parts; + } else { + throw new Error('ipaddr: ipv6 part count should be 8 or 16'); + } + + for (i = 0; i < this.parts.length; i++) { + part = this.parts[i]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error('ipaddr: ipv6 part should fit in 16 bits'); + } + } + + if (zoneId) { + this.zoneId = zoneId; + } + } + + // Special IPv6 ranges + IPv6.prototype.SpecialRanges = { + // RFC4291, here and after + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + // RFC6666 + discard: [new IPv6([0x100, 0, 0, 0, 0, 0, 0, 0]), 64], + // RFC6145 + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + // RFC6052 + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + // RFC3056 + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + // RFC6052, RFC6146 + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + // RFC5180 + benchmarking: [new IPv6([0x2001, 0x2, 0, 0, 0, 0, 0, 0]), 48], + // RFC7450 + amt: [new IPv6([0x2001, 0x3, 0, 0, 0, 0, 0, 0]), 32], + as112v6: [ + [new IPv6([0x2001, 0x4, 0x112, 0, 0, 0, 0, 0]), 48], + [new IPv6([0x2620, 0x4f, 0x8000, 0, 0, 0, 0, 0]), 48], + ], + deprecated: [new IPv6([0x2001, 0x10, 0, 0, 0, 0, 0, 0]), 28], + orchid2: [new IPv6([0x2001, 0x20, 0, 0, 0, 0, 0, 0]), 28], + droneRemoteIdProtocolEntityTags: [new IPv6([0x2001, 0x30, 0, 0, 0, 0, 0, 0]), 28], + reserved: [ + // RFC3849 + [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 23], + // RFC2928 + [new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32], + ], + }; + + // Checks if this address is an IPv4-mapped IPv6 address. + IPv6.prototype.isIPv4MappedAddress = function () { + return this.range() === 'ipv4Mapped'; + }; + + // The 'kind' method exists on both IPv4 and IPv6 classes. + IPv6.prototype.kind = function () { + return 'ipv6'; + }; + + // Checks if this address matches other one within given CIDR range. + IPv6.prototype.match = function (other, cidrRange) { + let ref; + + if (cidrRange === undefined) { + ref = other; + other = ref[0]; + cidrRange = ref[1]; + } + + if (other.kind() !== 'ipv6') { + throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one'); + } + + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + + // returns a number of leading ones in IPv6 address, making sure that + // the rest is a solid sequence of 0's (valid netmask) + // returns either the CIDR length or null if mask is not valid + IPv6.prototype.prefixLengthFromSubnetMask = function () { + let cidr = 0; + // non-zero encountered stop scanning for zeroes + let stop = false; + // number of zeroes in octet + const zerotable = { + 0: 16, + 32768: 15, + 49152: 14, + 57344: 13, + 61440: 12, + 63488: 11, + 64512: 10, + 65024: 9, + 65280: 8, + 65408: 7, + 65472: 6, + 65504: 5, + 65520: 4, + 65528: 3, + 65532: 2, + 65534: 1, + 65535: 0 + }; + let part, zeros; + + for (let i = 7; i >= 0; i -= 1) { + part = this.parts[i]; + if (part in zerotable) { + zeros = zerotable[part]; + if (stop && zeros !== 0) { + return null; + } + + if (zeros !== 16) { + stop = true; + } + + cidr += zeros; + } else { + return null; + } + } + + return 128 - cidr; + }; + + + // Checks if the address corresponds to one of the special ranges. + IPv6.prototype.range = function () { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + // Returns an array of byte-sized values in network order (MSB first) + IPv6.prototype.toByteArray = function () { + let part; + const bytes = []; + const ref = this.parts; + for (let i = 0; i < ref.length; i++) { + part = ref[i]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + + return bytes; + }; + + // Returns the address in expanded format with all zeroes included, like + // 2001:0db8:0008:0066:0000:0000:0000:0001 + IPv6.prototype.toFixedLengthString = function () { + const addr = ((function () { + const results = []; + for (let i = 0; i < this.parts.length; i++) { + results.push(padPart(this.parts[i].toString(16), 4)); + } + + return results; + }).call(this)).join(':'); + + let suffix = ''; + + if (this.zoneId) { + suffix = `%${this.zoneId}`; + } + + return addr + suffix; + }; + + // Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address. + // Throws an error otherwise. + IPv6.prototype.toIPv4Address = function () { + if (!this.isIPv4MappedAddress()) { + throw new Error('ipaddr: trying to convert a generic ipv6 address to ipv4'); + } + + const ref = this.parts.slice(-2); + const high = ref[0]; + const low = ref[1]; + + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; + + // Returns the address in expanded format with all zeroes included, like + // 2001:db8:8:66:0:0:0:1 + // + // Deprecated: use toFixedLengthString() instead. + IPv6.prototype.toNormalizedString = function () { + const addr = ((function () { + const results = []; + + for (let i = 0; i < this.parts.length; i++) { + results.push(this.parts[i].toString(16)); + } + + return results; + }).call(this)).join(':'); + + let suffix = ''; + + if (this.zoneId) { + suffix = `%${this.zoneId}`; + } + + return addr + suffix; + }; + + // Returns the address in compact, human-readable format like + // 2001:db8:8:66::1 + // in line with RFC 5952 (see https://tools.ietf.org/html/rfc5952#section-4) + IPv6.prototype.toRFC5952String = function () { + const regex = /((^|:)(0(:|$)){2,})/g; + const string = this.toNormalizedString(); + let bestMatchIndex = 0; + let bestMatchLength = -1; + let match; + + while ((match = regex.exec(string))) { + if (match[0].length > bestMatchLength) { + bestMatchIndex = match.index; + bestMatchLength = match[0].length; + } + } + + if (bestMatchLength < 0) { + return string; + } + + return `${string.substring(0, bestMatchIndex)}::${string.substring(bestMatchIndex + bestMatchLength)}`; + }; + + // Returns the address in compact, human-readable format like + // 2001:db8:8:66::1 + // Calls toRFC5952String under the hood. + IPv6.prototype.toString = function () { + return this.toRFC5952String(); + }; + + return IPv6; + + })(); + + // A utility function to return broadcast address given the IPv6 interface and prefix length in CIDR notation + ipaddr.IPv6.broadcastAddressFromCIDR = function (string) { + try { + const cidr = this.parseCIDR(string); + const ipInterfaceOctets = cidr[0].toByteArray(); + const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + const octets = []; + let i = 0; + while (i < 16) { + // Broadcast address is bitwise OR between ip interface and inverted mask + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + + return new this(octets); + } catch (e) { + throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`); + } + }; + + // Checks if a given string is formatted like IPv6 address. + ipaddr.IPv6.isIPv6 = function (string) { + return this.parser(string) !== null; + }; + + // Checks to see if string is a valid IPv6 Address + ipaddr.IPv6.isValid = function (string) { + + // Since IPv6.isValid is always called first, this shortcut + // provides a substantial performance gain. + if (typeof string === 'string' && string.indexOf(':') === -1) { + return false; + } + + try { + const addr = this.parser(string); + new this(addr.parts, addr.zoneId); + return true; + } catch (e) { + return false; + } + }; + + // Checks if a given string is a valid IPv6 address in CIDR notation. + ipaddr.IPv6.isValidCIDR = function (string) { + + // See note in IPv6.isValid + if (typeof string === 'string' && string.indexOf(':') === -1) { + return false; + } + + try { + this.parseCIDR(string); + return true; + } catch (e) { + return false; + } + }; + + // A utility function to return network address given the IPv6 interface and prefix length in CIDR notation + ipaddr.IPv6.networkAddressFromCIDR = function (string) { + let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets; + + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 16) { + // Network address is bitwise AND between ip interface and mask + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + + return new this(octets); + } catch (e) { + throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`); + } + }; + + // Tries to parse and validate a string with IPv6 address. + // Throws an error if it fails. + ipaddr.IPv6.parse = function (string) { + const addr = this.parser(string); + + if (addr.parts === null) { + throw new Error('ipaddr: string is not formatted like an IPv6 Address'); + } + + return new this(addr.parts, addr.zoneId); + }; + + ipaddr.IPv6.parseCIDR = function (string) { + let maskLength, match, parsed; + + if ((match = string.match(/^(.+)\/(\d+)$/))) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function () { + return this.join('/'); + } + }); + return parsed; + } + } + + throw new Error('ipaddr: string is not formatted like an IPv6 CIDR range'); + }; + + // Parse an IPv6 address. + ipaddr.IPv6.parser = function (string) { + let addr, i, match, octet, octets, zoneId; + + if ((match = string.match(ipv6Regexes.deprecatedTransitional))) { + return this.parser(`::ffff:${match[1]}`); + } + if (ipv6Regexes.native.test(string)) { + return expandIPv6(string, 8); + } + if ((match = string.match(ipv6Regexes.transitional))) { + zoneId = match[6] || ''; + addr = match[1] + if (!match[1].endsWith('::')) { + addr = addr.slice(0, -1) + } + addr = expandIPv6(addr + zoneId, 6); + if (addr.parts) { + octets = [ + parseInt(match[2]), + parseInt(match[3]), + parseInt(match[4]), + parseInt(match[5]) + ]; + for (i = 0; i < octets.length; i++) { + octet = octets[i]; + if (!((0 <= octet && octet <= 255))) { + return null; + } + } + + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; + } + } + + return null; + }; + + // A utility function to return subnet mask in IPv6 format given the prefix length + ipaddr.IPv6.subnetMaskFromPrefixLength = function (prefix) { + prefix = parseInt(prefix); + if (prefix < 0 || prefix > 128) { + throw new Error('ipaddr: invalid IPv6 prefix length'); + } + + const octets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let j = 0; + const filledOctetCount = Math.floor(prefix / 8); + + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + + if (filledOctetCount < 16) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + } + + return new this(octets); + }; + + // Try to parse an array in network order (MSB first) for IPv4 and IPv6 + ipaddr.fromByteArray = function (bytes) { + const length = bytes.length; + + if (length === 4) { + return new ipaddr.IPv4(bytes); + } else if (length === 16) { + return new ipaddr.IPv6(bytes); + } else { + throw new Error('ipaddr: the binary input is neither an IPv6 nor IPv4 address'); + } + }; + + // Checks if the address is valid IP address + ipaddr.isValid = function (string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + + // Checks if the address is valid IP address in CIDR notation + ipaddr.isValidCIDR = function (string) { + return ipaddr.IPv6.isValidCIDR(string) || ipaddr.IPv4.isValidCIDR(string); + }; + + + // Attempts to parse an IP Address, first through IPv6 then IPv4. + // Throws an error if it could not be parsed. + ipaddr.parse = function (string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error('ipaddr: the address has neither IPv6 nor IPv4 format'); + } + }; + + // Attempt to parse CIDR notation, first through IPv6 then IPv4. + // Throws an error if it could not be parsed. + ipaddr.parseCIDR = function (string) { + try { + return ipaddr.IPv6.parseCIDR(string); + } catch (e) { + try { + return ipaddr.IPv4.parseCIDR(string); + } catch (e2) { + throw new Error('ipaddr: the address has neither IPv6 nor IPv4 CIDR format'); + } + } + }; + + // Parse an address and return plain IPv4 address if it is an IPv4-mapped address + ipaddr.process = function (string) { + const addr = this.parse(string); + + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + + // An utility function to ease named range matching. See examples below. + // rangeList can contain both IPv4 and IPv6 subnet entries and will not throw errors + // on matching IPv4 addresses to IPv6 ranges or vice versa. + ipaddr.subnetMatch = function (address, rangeList, defaultName) { + let i, rangeName, rangeSubnets, subnet; + + if (defaultName === undefined || defaultName === null) { + defaultName = 'unicast'; + } + + for (rangeName in rangeList) { + if (Object.prototype.hasOwnProperty.call(rangeList, rangeName)) { + rangeSubnets = rangeList[rangeName]; + // ECMA5 Array.isArray isn't available everywhere + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + + for (i = 0; i < rangeSubnets.length; i++) { + subnet = rangeSubnets[i]; + if (address.kind() === subnet[0].kind() && address.match.apply(address, subnet)) { + return rangeName; + } + } + } + } + + return defaultName; + }; + + // Export for both the CommonJS and browser-like environment + if (typeof module !== 'undefined' && module.exports) { + module.exports = ipaddr; + + } else { + root.ipaddr = ipaddr; + } + +}(this)); diff --git a/node_modules/ipaddr.js/lib/ipaddr.js.d.ts b/node_modules/ipaddr.js/lib/ipaddr.js.d.ts new file mode 100644 index 0000000..ee02c02 --- /dev/null +++ b/node_modules/ipaddr.js/lib/ipaddr.js.d.ts @@ -0,0 +1,72 @@ +declare module "ipaddr.js" { + type IPvXRangeDefaults = 'unicast' | 'unspecified' | 'multicast' | 'linkLocal' | 'loopback' | 'reserved' | 'benchmarking' | 'amt'; + type IPv4Range = IPvXRangeDefaults | 'broadcast' | 'carrierGradeNat' | 'private' | 'as112'; + type IPv6Range = IPvXRangeDefaults | 'uniqueLocal' | 'ipv4Mapped' | 'rfc6145' | 'rfc6052' | '6to4' | 'teredo' | 'as112v6' | 'orchid2' | 'droneRemoteIdProtocolEntityTags'; + + interface RangeList { + [name: string]: [T, number] | [T, number][]; + } + + // Common methods/properties for IPv4 and IPv6 classes. + class IP { + prefixLengthFromSubnetMask(): number | null; + toByteArray(): number[]; + toNormalizedString(): string; + toString(): string; + } + + namespace Address { + export function fromByteArray(bytes: number[]): IPv4 | IPv6; + export function isValid(addr: string): boolean; + export function isValidCIDR(addr: string): boolean; + export function parse(addr: string): IPv4 | IPv6; + export function parseCIDR(mask: string): [IPv4 | IPv6, number]; + export function process(addr: string): IPv4 | IPv6; + export function subnetMatch(addr: IPv4 | IPv6, rangeList: RangeList, defaultName?: string): string; + + export class IPv4 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv4; + static isIPv4(addr: string): boolean; + static isValid(addr: string): boolean; + static isValidCIDR(addr: string): boolean; + static isValidFourPartDecimal(addr: string): boolean; + static isValidCIDRFourPartDecimal(addr: string): boolean; + static networkAddressFromCIDR(addr: string): IPv4; + static parse(addr: string): IPv4; + static parseCIDR(addr: string): [IPv4, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv4; + constructor(octets: number[]); + octets: number[] + + kind(): 'ipv4'; + match(what: IPv4 | IPv6 | [IPv4 | IPv6, number], bits?: number): boolean; + range(): IPv4Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4MappedAddress(): IPv6; + } + + export class IPv6 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv6; + static isIPv6(addr: string): boolean; + static isValid(addr: string): boolean; + static isValidCIDR(addr: string): boolean; + static networkAddressFromCIDR(addr: string): IPv6; + static parse(addr: string): IPv6; + static parseCIDR(addr: string): [IPv6, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv6; + constructor(parts: number[]); + parts: number[] + zoneId?: string + + isIPv4MappedAddress(): boolean; + kind(): 'ipv6'; + match(what: IPv4 | IPv6 | [IPv4 | IPv6, number], bits?: number): boolean; + range(): IPv6Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4Address(): IPv4; + toRFC5952String(): string; + } + } + + export = Address; +} diff --git a/node_modules/ipaddr.js/package.json b/node_modules/ipaddr.js/package.json new file mode 100644 index 0000000..8f1daf4 --- /dev/null +++ b/node_modules/ipaddr.js/package.json @@ -0,0 +1,36 @@ +{ + "name": "ipaddr.js", + "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", + "version": "2.3.0", + "author": "whitequark ", + "directories": { + "lib": "./lib" + }, + "dependencies": {}, + "devDependencies": { + "eslint": "^9.19.0", + "uglify-es": "*" + }, + "scripts": { + "lint": "npx eslint lib", + "lintfix": "npx eslint --fix lib test", + "build": "npx uglifyjs --compress --mangle --wrap=window -o ipaddr.min.js lib/ipaddr.js", + "test": "node --test" + }, + "files": [ + "lib", + "ipaddr.min.js" + ], + "keywords": [ + "ip", + "ipv4", + "ipv6" + ], + "repository": "git://github.com/whitequark/ipaddr.js", + "main": "./lib/ipaddr.js", + "engines": { + "node": ">= 10" + }, + "license": "MIT", + "types": "./lib/ipaddr.js.d.ts" +} diff --git a/node_modules/lodash/LICENSE b/node_modules/lodash/LICENSE new file mode 100644 index 0000000..77c42f1 --- /dev/null +++ b/node_modules/lodash/LICENSE @@ -0,0 +1,47 @@ +Copyright OpenJS Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +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. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash/README.md b/node_modules/lodash/README.md new file mode 100644 index 0000000..fc93193 --- /dev/null +++ b/node_modules/lodash/README.md @@ -0,0 +1,39 @@ +# lodash v4.18.1 + +The [Lodash](https://lodash.com/) library exported as [Node.js](https://nodejs.org/) modules. + +## Installation + +Using npm: +```shell +$ npm i -g npm +$ npm i --save lodash +``` + +In Node.js: +```js +// Load the full build. +var _ = require('lodash'); +// Load the core build. +var _ = require('lodash/core'); +// Load the FP build for immutable auto-curried iteratee-first data-last methods. +var fp = require('lodash/fp'); + +// Load method categories. +var array = require('lodash/array'); +var object = require('lodash/fp/object'); + +// Cherry-pick methods for smaller browserify/rollup/webpack bundles. +var at = require('lodash/at'); +var curryN = require('lodash/fp/curryN'); +``` + +See the [package source](https://github.com/lodash/lodash/tree/4.18.1-npm) for more details. + +**Note:**
+Install [n_](https://www.npmjs.com/package/n_) for Lodash use in the Node.js < 6 REPL. + +## Support + +Tested in Chrome 74-75, Firefox 66-67, IE 11, Edge 18, Safari 11-12, & Node.js 8-12.
+Automated [browser](https://saucelabs.com/u/lodash) & [CI](https://travis-ci.org/lodash/lodash/) test runs are available. diff --git a/node_modules/lodash/_DataView.js b/node_modules/lodash/_DataView.js new file mode 100644 index 0000000..ac2d57c --- /dev/null +++ b/node_modules/lodash/_DataView.js @@ -0,0 +1,7 @@ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var DataView = getNative(root, 'DataView'); + +module.exports = DataView; diff --git a/node_modules/lodash/_Hash.js b/node_modules/lodash/_Hash.js new file mode 100644 index 0000000..b504fe3 --- /dev/null +++ b/node_modules/lodash/_Hash.js @@ -0,0 +1,32 @@ +var hashClear = require('./_hashClear'), + hashDelete = require('./_hashDelete'), + hashGet = require('./_hashGet'), + hashHas = require('./_hashHas'), + hashSet = require('./_hashSet'); + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +module.exports = Hash; diff --git a/node_modules/lodash/_LazyWrapper.js b/node_modules/lodash/_LazyWrapper.js new file mode 100644 index 0000000..81786c7 --- /dev/null +++ b/node_modules/lodash/_LazyWrapper.js @@ -0,0 +1,28 @@ +var baseCreate = require('./_baseCreate'), + baseLodash = require('./_baseLodash'); + +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH = 4294967295; + +/** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ +function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; +} + +// Ensure `LazyWrapper` is an instance of `baseLodash`. +LazyWrapper.prototype = baseCreate(baseLodash.prototype); +LazyWrapper.prototype.constructor = LazyWrapper; + +module.exports = LazyWrapper; diff --git a/node_modules/lodash/_ListCache.js b/node_modules/lodash/_ListCache.js new file mode 100644 index 0000000..26895c3 --- /dev/null +++ b/node_modules/lodash/_ListCache.js @@ -0,0 +1,32 @@ +var listCacheClear = require('./_listCacheClear'), + listCacheDelete = require('./_listCacheDelete'), + listCacheGet = require('./_listCacheGet'), + listCacheHas = require('./_listCacheHas'), + listCacheSet = require('./_listCacheSet'); + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +module.exports = ListCache; diff --git a/node_modules/lodash/_LodashWrapper.js b/node_modules/lodash/_LodashWrapper.js new file mode 100644 index 0000000..c1e4d9d --- /dev/null +++ b/node_modules/lodash/_LodashWrapper.js @@ -0,0 +1,22 @@ +var baseCreate = require('./_baseCreate'), + baseLodash = require('./_baseLodash'); + +/** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ +function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; +} + +LodashWrapper.prototype = baseCreate(baseLodash.prototype); +LodashWrapper.prototype.constructor = LodashWrapper; + +module.exports = LodashWrapper; diff --git a/node_modules/lodash/_Map.js b/node_modules/lodash/_Map.js new file mode 100644 index 0000000..b73f29a --- /dev/null +++ b/node_modules/lodash/_Map.js @@ -0,0 +1,7 @@ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'); + +module.exports = Map; diff --git a/node_modules/lodash/_MapCache.js b/node_modules/lodash/_MapCache.js new file mode 100644 index 0000000..4a4eea7 --- /dev/null +++ b/node_modules/lodash/_MapCache.js @@ -0,0 +1,32 @@ +var mapCacheClear = require('./_mapCacheClear'), + mapCacheDelete = require('./_mapCacheDelete'), + mapCacheGet = require('./_mapCacheGet'), + mapCacheHas = require('./_mapCacheHas'), + mapCacheSet = require('./_mapCacheSet'); + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; + +module.exports = MapCache; diff --git a/node_modules/lodash/_Promise.js b/node_modules/lodash/_Promise.js new file mode 100644 index 0000000..247b9e1 --- /dev/null +++ b/node_modules/lodash/_Promise.js @@ -0,0 +1,7 @@ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var Promise = getNative(root, 'Promise'); + +module.exports = Promise; diff --git a/node_modules/lodash/_Set.js b/node_modules/lodash/_Set.js new file mode 100644 index 0000000..b3c8dcb --- /dev/null +++ b/node_modules/lodash/_Set.js @@ -0,0 +1,7 @@ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var Set = getNative(root, 'Set'); + +module.exports = Set; diff --git a/node_modules/lodash/_SetCache.js b/node_modules/lodash/_SetCache.js new file mode 100644 index 0000000..6468b06 --- /dev/null +++ b/node_modules/lodash/_SetCache.js @@ -0,0 +1,27 @@ +var MapCache = require('./_MapCache'), + setCacheAdd = require('./_setCacheAdd'), + setCacheHas = require('./_setCacheHas'); + +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } +} + +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; + +module.exports = SetCache; diff --git a/node_modules/lodash/_Stack.js b/node_modules/lodash/_Stack.js new file mode 100644 index 0000000..80b2cf1 --- /dev/null +++ b/node_modules/lodash/_Stack.js @@ -0,0 +1,27 @@ +var ListCache = require('./_ListCache'), + stackClear = require('./_stackClear'), + stackDelete = require('./_stackDelete'), + stackGet = require('./_stackGet'), + stackHas = require('./_stackHas'), + stackSet = require('./_stackSet'); + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; +} + +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; + +module.exports = Stack; diff --git a/node_modules/lodash/_Symbol.js b/node_modules/lodash/_Symbol.js new file mode 100644 index 0000000..a013f7c --- /dev/null +++ b/node_modules/lodash/_Symbol.js @@ -0,0 +1,6 @@ +var root = require('./_root'); + +/** Built-in value references. */ +var Symbol = root.Symbol; + +module.exports = Symbol; diff --git a/node_modules/lodash/_Uint8Array.js b/node_modules/lodash/_Uint8Array.js new file mode 100644 index 0000000..2fb30e1 --- /dev/null +++ b/node_modules/lodash/_Uint8Array.js @@ -0,0 +1,6 @@ +var root = require('./_root'); + +/** Built-in value references. */ +var Uint8Array = root.Uint8Array; + +module.exports = Uint8Array; diff --git a/node_modules/lodash/_WeakMap.js b/node_modules/lodash/_WeakMap.js new file mode 100644 index 0000000..567f86c --- /dev/null +++ b/node_modules/lodash/_WeakMap.js @@ -0,0 +1,7 @@ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var WeakMap = getNative(root, 'WeakMap'); + +module.exports = WeakMap; diff --git a/node_modules/lodash/_apply.js b/node_modules/lodash/_apply.js new file mode 100644 index 0000000..36436dd --- /dev/null +++ b/node_modules/lodash/_apply.js @@ -0,0 +1,21 @@ +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +module.exports = apply; diff --git a/node_modules/lodash/_arrayAggregator.js b/node_modules/lodash/_arrayAggregator.js new file mode 100644 index 0000000..d96c3ca --- /dev/null +++ b/node_modules/lodash/_arrayAggregator.js @@ -0,0 +1,22 @@ +/** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ +function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; +} + +module.exports = arrayAggregator; diff --git a/node_modules/lodash/_arrayEach.js b/node_modules/lodash/_arrayEach.js new file mode 100644 index 0000000..2c5f579 --- /dev/null +++ b/node_modules/lodash/_arrayEach.js @@ -0,0 +1,22 @@ +/** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; +} + +module.exports = arrayEach; diff --git a/node_modules/lodash/_arrayEachRight.js b/node_modules/lodash/_arrayEachRight.js new file mode 100644 index 0000000..976ca5c --- /dev/null +++ b/node_modules/lodash/_arrayEachRight.js @@ -0,0 +1,21 @@ +/** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; +} + +module.exports = arrayEachRight; diff --git a/node_modules/lodash/_arrayEvery.js b/node_modules/lodash/_arrayEvery.js new file mode 100644 index 0000000..e26a918 --- /dev/null +++ b/node_modules/lodash/_arrayEvery.js @@ -0,0 +1,23 @@ +/** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ +function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; +} + +module.exports = arrayEvery; diff --git a/node_modules/lodash/_arrayFilter.js b/node_modules/lodash/_arrayFilter.js new file mode 100644 index 0000000..75ea254 --- /dev/null +++ b/node_modules/lodash/_arrayFilter.js @@ -0,0 +1,25 @@ +/** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; +} + +module.exports = arrayFilter; diff --git a/node_modules/lodash/_arrayIncludes.js b/node_modules/lodash/_arrayIncludes.js new file mode 100644 index 0000000..3737a6d --- /dev/null +++ b/node_modules/lodash/_arrayIncludes.js @@ -0,0 +1,17 @@ +var baseIndexOf = require('./_baseIndexOf'); + +/** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; +} + +module.exports = arrayIncludes; diff --git a/node_modules/lodash/_arrayIncludesWith.js b/node_modules/lodash/_arrayIncludesWith.js new file mode 100644 index 0000000..235fd97 --- /dev/null +++ b/node_modules/lodash/_arrayIncludesWith.js @@ -0,0 +1,22 @@ +/** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; +} + +module.exports = arrayIncludesWith; diff --git a/node_modules/lodash/_arrayLikeKeys.js b/node_modules/lodash/_arrayLikeKeys.js new file mode 100644 index 0000000..b2ec9ce --- /dev/null +++ b/node_modules/lodash/_arrayLikeKeys.js @@ -0,0 +1,49 @@ +var baseTimes = require('./_baseTimes'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isBuffer = require('./isBuffer'), + isIndex = require('./_isIndex'), + isTypedArray = require('./isTypedArray'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; +} + +module.exports = arrayLikeKeys; diff --git a/node_modules/lodash/_arrayMap.js b/node_modules/lodash/_arrayMap.js new file mode 100644 index 0000000..22b2246 --- /dev/null +++ b/node_modules/lodash/_arrayMap.js @@ -0,0 +1,21 @@ +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +module.exports = arrayMap; diff --git a/node_modules/lodash/_arrayPush.js b/node_modules/lodash/_arrayPush.js new file mode 100644 index 0000000..7d742b3 --- /dev/null +++ b/node_modules/lodash/_arrayPush.js @@ -0,0 +1,20 @@ +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +module.exports = arrayPush; diff --git a/node_modules/lodash/_arrayReduce.js b/node_modules/lodash/_arrayReduce.js new file mode 100644 index 0000000..de8b79b --- /dev/null +++ b/node_modules/lodash/_arrayReduce.js @@ -0,0 +1,26 @@ +/** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; +} + +module.exports = arrayReduce; diff --git a/node_modules/lodash/_arrayReduceRight.js b/node_modules/lodash/_arrayReduceRight.js new file mode 100644 index 0000000..22d8976 --- /dev/null +++ b/node_modules/lodash/_arrayReduceRight.js @@ -0,0 +1,24 @@ +/** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; +} + +module.exports = arrayReduceRight; diff --git a/node_modules/lodash/_arraySample.js b/node_modules/lodash/_arraySample.js new file mode 100644 index 0000000..fcab010 --- /dev/null +++ b/node_modules/lodash/_arraySample.js @@ -0,0 +1,15 @@ +var baseRandom = require('./_baseRandom'); + +/** + * A specialized version of `_.sample` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ +function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; +} + +module.exports = arraySample; diff --git a/node_modules/lodash/_arraySampleSize.js b/node_modules/lodash/_arraySampleSize.js new file mode 100644 index 0000000..8c7e364 --- /dev/null +++ b/node_modules/lodash/_arraySampleSize.js @@ -0,0 +1,17 @@ +var baseClamp = require('./_baseClamp'), + copyArray = require('./_copyArray'), + shuffleSelf = require('./_shuffleSelf'); + +/** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ +function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); +} + +module.exports = arraySampleSize; diff --git a/node_modules/lodash/_arrayShuffle.js b/node_modules/lodash/_arrayShuffle.js new file mode 100644 index 0000000..46313a3 --- /dev/null +++ b/node_modules/lodash/_arrayShuffle.js @@ -0,0 +1,15 @@ +var copyArray = require('./_copyArray'), + shuffleSelf = require('./_shuffleSelf'); + +/** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ +function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); +} + +module.exports = arrayShuffle; diff --git a/node_modules/lodash/_arraySome.js b/node_modules/lodash/_arraySome.js new file mode 100644 index 0000000..6fd02fd --- /dev/null +++ b/node_modules/lodash/_arraySome.js @@ -0,0 +1,23 @@ +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; +} + +module.exports = arraySome; diff --git a/node_modules/lodash/_asciiSize.js b/node_modules/lodash/_asciiSize.js new file mode 100644 index 0000000..11d29c3 --- /dev/null +++ b/node_modules/lodash/_asciiSize.js @@ -0,0 +1,12 @@ +var baseProperty = require('./_baseProperty'); + +/** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ +var asciiSize = baseProperty('length'); + +module.exports = asciiSize; diff --git a/node_modules/lodash/_asciiToArray.js b/node_modules/lodash/_asciiToArray.js new file mode 100644 index 0000000..8e3dd5b --- /dev/null +++ b/node_modules/lodash/_asciiToArray.js @@ -0,0 +1,12 @@ +/** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function asciiToArray(string) { + return string.split(''); +} + +module.exports = asciiToArray; diff --git a/node_modules/lodash/_asciiWords.js b/node_modules/lodash/_asciiWords.js new file mode 100644 index 0000000..d765f0f --- /dev/null +++ b/node_modules/lodash/_asciiWords.js @@ -0,0 +1,15 @@ +/** Used to match words composed of alphanumeric characters. */ +var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + +/** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function asciiWords(string) { + return string.match(reAsciiWord) || []; +} + +module.exports = asciiWords; diff --git a/node_modules/lodash/_assignMergeValue.js b/node_modules/lodash/_assignMergeValue.js new file mode 100644 index 0000000..cb1185e --- /dev/null +++ b/node_modules/lodash/_assignMergeValue.js @@ -0,0 +1,20 @@ +var baseAssignValue = require('./_baseAssignValue'), + eq = require('./eq'); + +/** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +module.exports = assignMergeValue; diff --git a/node_modules/lodash/_assignValue.js b/node_modules/lodash/_assignValue.js new file mode 100644 index 0000000..4083957 --- /dev/null +++ b/node_modules/lodash/_assignValue.js @@ -0,0 +1,28 @@ +var baseAssignValue = require('./_baseAssignValue'), + eq = require('./eq'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +module.exports = assignValue; diff --git a/node_modules/lodash/_assocIndexOf.js b/node_modules/lodash/_assocIndexOf.js new file mode 100644 index 0000000..5b77a2b --- /dev/null +++ b/node_modules/lodash/_assocIndexOf.js @@ -0,0 +1,21 @@ +var eq = require('./eq'); + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +module.exports = assocIndexOf; diff --git a/node_modules/lodash/_baseAggregator.js b/node_modules/lodash/_baseAggregator.js new file mode 100644 index 0000000..4bc9e91 --- /dev/null +++ b/node_modules/lodash/_baseAggregator.js @@ -0,0 +1,21 @@ +var baseEach = require('./_baseEach'); + +/** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ +function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; +} + +module.exports = baseAggregator; diff --git a/node_modules/lodash/_baseAssign.js b/node_modules/lodash/_baseAssign.js new file mode 100644 index 0000000..e5c4a1a --- /dev/null +++ b/node_modules/lodash/_baseAssign.js @@ -0,0 +1,17 @@ +var copyObject = require('./_copyObject'), + keys = require('./keys'); + +/** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ +function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); +} + +module.exports = baseAssign; diff --git a/node_modules/lodash/_baseAssignIn.js b/node_modules/lodash/_baseAssignIn.js new file mode 100644 index 0000000..6624f90 --- /dev/null +++ b/node_modules/lodash/_baseAssignIn.js @@ -0,0 +1,17 @@ +var copyObject = require('./_copyObject'), + keysIn = require('./keysIn'); + +/** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ +function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); +} + +module.exports = baseAssignIn; diff --git a/node_modules/lodash/_baseAssignValue.js b/node_modules/lodash/_baseAssignValue.js new file mode 100644 index 0000000..d6f66ef --- /dev/null +++ b/node_modules/lodash/_baseAssignValue.js @@ -0,0 +1,25 @@ +var defineProperty = require('./_defineProperty'); + +/** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } +} + +module.exports = baseAssignValue; diff --git a/node_modules/lodash/_baseAt.js b/node_modules/lodash/_baseAt.js new file mode 100644 index 0000000..90e4237 --- /dev/null +++ b/node_modules/lodash/_baseAt.js @@ -0,0 +1,23 @@ +var get = require('./get'); + +/** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. + */ +function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; +} + +module.exports = baseAt; diff --git a/node_modules/lodash/_baseClamp.js b/node_modules/lodash/_baseClamp.js new file mode 100644 index 0000000..a1c5692 --- /dev/null +++ b/node_modules/lodash/_baseClamp.js @@ -0,0 +1,22 @@ +/** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ +function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; +} + +module.exports = baseClamp; diff --git a/node_modules/lodash/_baseClone.js b/node_modules/lodash/_baseClone.js new file mode 100644 index 0000000..69f8705 --- /dev/null +++ b/node_modules/lodash/_baseClone.js @@ -0,0 +1,166 @@ +var Stack = require('./_Stack'), + arrayEach = require('./_arrayEach'), + assignValue = require('./_assignValue'), + baseAssign = require('./_baseAssign'), + baseAssignIn = require('./_baseAssignIn'), + cloneBuffer = require('./_cloneBuffer'), + copyArray = require('./_copyArray'), + copySymbols = require('./_copySymbols'), + copySymbolsIn = require('./_copySymbolsIn'), + getAllKeys = require('./_getAllKeys'), + getAllKeysIn = require('./_getAllKeysIn'), + getTag = require('./_getTag'), + initCloneArray = require('./_initCloneArray'), + initCloneByTag = require('./_initCloneByTag'), + initCloneObject = require('./_initCloneObject'), + isArray = require('./isArray'), + isBuffer = require('./isBuffer'), + isMap = require('./isMap'), + isObject = require('./isObject'), + isSet = require('./isSet'), + keys = require('./keys'), + keysIn = require('./keysIn'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values supported by `_.clone`. */ +var cloneableTags = {}; +cloneableTags[argsTag] = cloneableTags[arrayTag] = +cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = +cloneableTags[boolTag] = cloneableTags[dateTag] = +cloneableTags[float32Tag] = cloneableTags[float64Tag] = +cloneableTags[int8Tag] = cloneableTags[int16Tag] = +cloneableTags[int32Tag] = cloneableTags[mapTag] = +cloneableTags[numberTag] = cloneableTags[objectTag] = +cloneableTags[regexpTag] = cloneableTags[setTag] = +cloneableTags[stringTag] = cloneableTags[symbolTag] = +cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = +cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; +cloneableTags[errorTag] = cloneableTags[funcTag] = +cloneableTags[weakMapTag] = false; + +/** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ +function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; +} + +module.exports = baseClone; diff --git a/node_modules/lodash/_baseConforms.js b/node_modules/lodash/_baseConforms.js new file mode 100644 index 0000000..947e20d --- /dev/null +++ b/node_modules/lodash/_baseConforms.js @@ -0,0 +1,18 @@ +var baseConformsTo = require('./_baseConformsTo'), + keys = require('./keys'); + +/** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ +function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; +} + +module.exports = baseConforms; diff --git a/node_modules/lodash/_baseConformsTo.js b/node_modules/lodash/_baseConformsTo.js new file mode 100644 index 0000000..e449cb8 --- /dev/null +++ b/node_modules/lodash/_baseConformsTo.js @@ -0,0 +1,27 @@ +/** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ +function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; +} + +module.exports = baseConformsTo; diff --git a/node_modules/lodash/_baseCreate.js b/node_modules/lodash/_baseCreate.js new file mode 100644 index 0000000..ffa6a52 --- /dev/null +++ b/node_modules/lodash/_baseCreate.js @@ -0,0 +1,30 @@ +var isObject = require('./isObject'); + +/** Built-in value references. */ +var objectCreate = Object.create; + +/** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ +var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; +}()); + +module.exports = baseCreate; diff --git a/node_modules/lodash/_baseDelay.js b/node_modules/lodash/_baseDelay.js new file mode 100644 index 0000000..1486d69 --- /dev/null +++ b/node_modules/lodash/_baseDelay.js @@ -0,0 +1,21 @@ +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ +function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); +} + +module.exports = baseDelay; diff --git a/node_modules/lodash/_baseDifference.js b/node_modules/lodash/_baseDifference.js new file mode 100644 index 0000000..343ac19 --- /dev/null +++ b/node_modules/lodash/_baseDifference.js @@ -0,0 +1,67 @@ +var SetCache = require('./_SetCache'), + arrayIncludes = require('./_arrayIncludes'), + arrayIncludesWith = require('./_arrayIncludesWith'), + arrayMap = require('./_arrayMap'), + baseUnary = require('./_baseUnary'), + cacheHas = require('./_cacheHas'); + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ +function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; +} + +module.exports = baseDifference; diff --git a/node_modules/lodash/_baseEach.js b/node_modules/lodash/_baseEach.js new file mode 100644 index 0000000..512c067 --- /dev/null +++ b/node_modules/lodash/_baseEach.js @@ -0,0 +1,14 @@ +var baseForOwn = require('./_baseForOwn'), + createBaseEach = require('./_createBaseEach'); + +/** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ +var baseEach = createBaseEach(baseForOwn); + +module.exports = baseEach; diff --git a/node_modules/lodash/_baseEachRight.js b/node_modules/lodash/_baseEachRight.js new file mode 100644 index 0000000..0a8feec --- /dev/null +++ b/node_modules/lodash/_baseEachRight.js @@ -0,0 +1,14 @@ +var baseForOwnRight = require('./_baseForOwnRight'), + createBaseEach = require('./_createBaseEach'); + +/** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ +var baseEachRight = createBaseEach(baseForOwnRight, true); + +module.exports = baseEachRight; diff --git a/node_modules/lodash/_baseEvery.js b/node_modules/lodash/_baseEvery.js new file mode 100644 index 0000000..fa52f7b --- /dev/null +++ b/node_modules/lodash/_baseEvery.js @@ -0,0 +1,21 @@ +var baseEach = require('./_baseEach'); + +/** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ +function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; +} + +module.exports = baseEvery; diff --git a/node_modules/lodash/_baseExtremum.js b/node_modules/lodash/_baseExtremum.js new file mode 100644 index 0000000..9d6aa77 --- /dev/null +++ b/node_modules/lodash/_baseExtremum.js @@ -0,0 +1,32 @@ +var isSymbol = require('./isSymbol'); + +/** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ +function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; +} + +module.exports = baseExtremum; diff --git a/node_modules/lodash/_baseFill.js b/node_modules/lodash/_baseFill.js new file mode 100644 index 0000000..46ef9c7 --- /dev/null +++ b/node_modules/lodash/_baseFill.js @@ -0,0 +1,32 @@ +var toInteger = require('./toInteger'), + toLength = require('./toLength'); + +/** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ +function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; +} + +module.exports = baseFill; diff --git a/node_modules/lodash/_baseFilter.js b/node_modules/lodash/_baseFilter.js new file mode 100644 index 0000000..4678477 --- /dev/null +++ b/node_modules/lodash/_baseFilter.js @@ -0,0 +1,21 @@ +var baseEach = require('./_baseEach'); + +/** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; +} + +module.exports = baseFilter; diff --git a/node_modules/lodash/_baseFindIndex.js b/node_modules/lodash/_baseFindIndex.js new file mode 100644 index 0000000..e3f5d8a --- /dev/null +++ b/node_modules/lodash/_baseFindIndex.js @@ -0,0 +1,24 @@ +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; +} + +module.exports = baseFindIndex; diff --git a/node_modules/lodash/_baseFindKey.js b/node_modules/lodash/_baseFindKey.js new file mode 100644 index 0000000..2e430f3 --- /dev/null +++ b/node_modules/lodash/_baseFindKey.js @@ -0,0 +1,23 @@ +/** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ +function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; +} + +module.exports = baseFindKey; diff --git a/node_modules/lodash/_baseFlatten.js b/node_modules/lodash/_baseFlatten.js new file mode 100644 index 0000000..4b1e009 --- /dev/null +++ b/node_modules/lodash/_baseFlatten.js @@ -0,0 +1,38 @@ +var arrayPush = require('./_arrayPush'), + isFlattenable = require('./_isFlattenable'); + +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; +} + +module.exports = baseFlatten; diff --git a/node_modules/lodash/_baseFor.js b/node_modules/lodash/_baseFor.js new file mode 100644 index 0000000..d946590 --- /dev/null +++ b/node_modules/lodash/_baseFor.js @@ -0,0 +1,16 @@ +var createBaseFor = require('./_createBaseFor'); + +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseFor = createBaseFor(); + +module.exports = baseFor; diff --git a/node_modules/lodash/_baseForOwn.js b/node_modules/lodash/_baseForOwn.js new file mode 100644 index 0000000..503d523 --- /dev/null +++ b/node_modules/lodash/_baseForOwn.js @@ -0,0 +1,16 @@ +var baseFor = require('./_baseFor'), + keys = require('./keys'); + +/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); +} + +module.exports = baseForOwn; diff --git a/node_modules/lodash/_baseForOwnRight.js b/node_modules/lodash/_baseForOwnRight.js new file mode 100644 index 0000000..a4b10e6 --- /dev/null +++ b/node_modules/lodash/_baseForOwnRight.js @@ -0,0 +1,16 @@ +var baseForRight = require('./_baseForRight'), + keys = require('./keys'); + +/** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); +} + +module.exports = baseForOwnRight; diff --git a/node_modules/lodash/_baseForRight.js b/node_modules/lodash/_baseForRight.js new file mode 100644 index 0000000..32842cd --- /dev/null +++ b/node_modules/lodash/_baseForRight.js @@ -0,0 +1,15 @@ +var createBaseFor = require('./_createBaseFor'); + +/** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseForRight = createBaseFor(true); + +module.exports = baseForRight; diff --git a/node_modules/lodash/_baseFunctions.js b/node_modules/lodash/_baseFunctions.js new file mode 100644 index 0000000..d23bc9b --- /dev/null +++ b/node_modules/lodash/_baseFunctions.js @@ -0,0 +1,19 @@ +var arrayFilter = require('./_arrayFilter'), + isFunction = require('./isFunction'); + +/** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ +function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); +} + +module.exports = baseFunctions; diff --git a/node_modules/lodash/_baseGet.js b/node_modules/lodash/_baseGet.js new file mode 100644 index 0000000..a194913 --- /dev/null +++ b/node_modules/lodash/_baseGet.js @@ -0,0 +1,24 @@ +var castPath = require('./_castPath'), + toKey = require('./_toKey'); + +/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ +function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; +} + +module.exports = baseGet; diff --git a/node_modules/lodash/_baseGetAllKeys.js b/node_modules/lodash/_baseGetAllKeys.js new file mode 100644 index 0000000..8ad204e --- /dev/null +++ b/node_modules/lodash/_baseGetAllKeys.js @@ -0,0 +1,20 @@ +var arrayPush = require('./_arrayPush'), + isArray = require('./isArray'); + +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); +} + +module.exports = baseGetAllKeys; diff --git a/node_modules/lodash/_baseGetTag.js b/node_modules/lodash/_baseGetTag.js new file mode 100644 index 0000000..b927ccc --- /dev/null +++ b/node_modules/lodash/_baseGetTag.js @@ -0,0 +1,28 @@ +var Symbol = require('./_Symbol'), + getRawTag = require('./_getRawTag'), + objectToString = require('./_objectToString'); + +/** `Object#toString` result references. */ +var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; + +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); +} + +module.exports = baseGetTag; diff --git a/node_modules/lodash/_baseGt.js b/node_modules/lodash/_baseGt.js new file mode 100644 index 0000000..502d273 --- /dev/null +++ b/node_modules/lodash/_baseGt.js @@ -0,0 +1,14 @@ +/** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ +function baseGt(value, other) { + return value > other; +} + +module.exports = baseGt; diff --git a/node_modules/lodash/_baseHas.js b/node_modules/lodash/_baseHas.js new file mode 100644 index 0000000..1b73032 --- /dev/null +++ b/node_modules/lodash/_baseHas.js @@ -0,0 +1,19 @@ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); +} + +module.exports = baseHas; diff --git a/node_modules/lodash/_baseHasIn.js b/node_modules/lodash/_baseHasIn.js new file mode 100644 index 0000000..2e0d042 --- /dev/null +++ b/node_modules/lodash/_baseHasIn.js @@ -0,0 +1,13 @@ +/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHasIn(object, key) { + return object != null && key in Object(object); +} + +module.exports = baseHasIn; diff --git a/node_modules/lodash/_baseInRange.js b/node_modules/lodash/_baseInRange.js new file mode 100644 index 0000000..ec95666 --- /dev/null +++ b/node_modules/lodash/_baseInRange.js @@ -0,0 +1,18 @@ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ +function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); +} + +module.exports = baseInRange; diff --git a/node_modules/lodash/_baseIndexOf.js b/node_modules/lodash/_baseIndexOf.js new file mode 100644 index 0000000..167e706 --- /dev/null +++ b/node_modules/lodash/_baseIndexOf.js @@ -0,0 +1,20 @@ +var baseFindIndex = require('./_baseFindIndex'), + baseIsNaN = require('./_baseIsNaN'), + strictIndexOf = require('./_strictIndexOf'); + +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); +} + +module.exports = baseIndexOf; diff --git a/node_modules/lodash/_baseIndexOfWith.js b/node_modules/lodash/_baseIndexOfWith.js new file mode 100644 index 0000000..f815fe0 --- /dev/null +++ b/node_modules/lodash/_baseIndexOfWith.js @@ -0,0 +1,23 @@ +/** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; +} + +module.exports = baseIndexOfWith; diff --git a/node_modules/lodash/_baseIntersection.js b/node_modules/lodash/_baseIntersection.js new file mode 100644 index 0000000..c1d250c --- /dev/null +++ b/node_modules/lodash/_baseIntersection.js @@ -0,0 +1,74 @@ +var SetCache = require('./_SetCache'), + arrayIncludes = require('./_arrayIncludes'), + arrayIncludesWith = require('./_arrayIncludesWith'), + arrayMap = require('./_arrayMap'), + baseUnary = require('./_baseUnary'), + cacheHas = require('./_cacheHas'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin = Math.min; + +/** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ +function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; +} + +module.exports = baseIntersection; diff --git a/node_modules/lodash/_baseInverter.js b/node_modules/lodash/_baseInverter.js new file mode 100644 index 0000000..fbc337f --- /dev/null +++ b/node_modules/lodash/_baseInverter.js @@ -0,0 +1,21 @@ +var baseForOwn = require('./_baseForOwn'); + +/** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ +function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; +} + +module.exports = baseInverter; diff --git a/node_modules/lodash/_baseInvoke.js b/node_modules/lodash/_baseInvoke.js new file mode 100644 index 0000000..49bcf3c --- /dev/null +++ b/node_modules/lodash/_baseInvoke.js @@ -0,0 +1,24 @@ +var apply = require('./_apply'), + castPath = require('./_castPath'), + last = require('./last'), + parent = require('./_parent'), + toKey = require('./_toKey'); + +/** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ +function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); +} + +module.exports = baseInvoke; diff --git a/node_modules/lodash/_baseIsArguments.js b/node_modules/lodash/_baseIsArguments.js new file mode 100644 index 0000000..b3562cc --- /dev/null +++ b/node_modules/lodash/_baseIsArguments.js @@ -0,0 +1,18 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]'; + +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; +} + +module.exports = baseIsArguments; diff --git a/node_modules/lodash/_baseIsArrayBuffer.js b/node_modules/lodash/_baseIsArrayBuffer.js new file mode 100644 index 0000000..a2c4f30 --- /dev/null +++ b/node_modules/lodash/_baseIsArrayBuffer.js @@ -0,0 +1,17 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +var arrayBufferTag = '[object ArrayBuffer]'; + +/** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ +function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; +} + +module.exports = baseIsArrayBuffer; diff --git a/node_modules/lodash/_baseIsDate.js b/node_modules/lodash/_baseIsDate.js new file mode 100644 index 0000000..ba67c78 --- /dev/null +++ b/node_modules/lodash/_baseIsDate.js @@ -0,0 +1,18 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var dateTag = '[object Date]'; + +/** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ +function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; +} + +module.exports = baseIsDate; diff --git a/node_modules/lodash/_baseIsEqual.js b/node_modules/lodash/_baseIsEqual.js new file mode 100644 index 0000000..00a68a4 --- /dev/null +++ b/node_modules/lodash/_baseIsEqual.js @@ -0,0 +1,28 @@ +var baseIsEqualDeep = require('./_baseIsEqualDeep'), + isObjectLike = require('./isObjectLike'); + +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ +function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); +} + +module.exports = baseIsEqual; diff --git a/node_modules/lodash/_baseIsEqualDeep.js b/node_modules/lodash/_baseIsEqualDeep.js new file mode 100644 index 0000000..e3cfd6a --- /dev/null +++ b/node_modules/lodash/_baseIsEqualDeep.js @@ -0,0 +1,83 @@ +var Stack = require('./_Stack'), + equalArrays = require('./_equalArrays'), + equalByTag = require('./_equalByTag'), + equalObjects = require('./_equalObjects'), + getTag = require('./_getTag'), + isArray = require('./isArray'), + isBuffer = require('./isBuffer'), + isTypedArray = require('./isTypedArray'); + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + objectTag = '[object Object]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); +} + +module.exports = baseIsEqualDeep; diff --git a/node_modules/lodash/_baseIsMap.js b/node_modules/lodash/_baseIsMap.js new file mode 100644 index 0000000..02a4021 --- /dev/null +++ b/node_modules/lodash/_baseIsMap.js @@ -0,0 +1,18 @@ +var getTag = require('./_getTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var mapTag = '[object Map]'; + +/** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ +function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; +} + +module.exports = baseIsMap; diff --git a/node_modules/lodash/_baseIsMatch.js b/node_modules/lodash/_baseIsMatch.js new file mode 100644 index 0000000..72494be --- /dev/null +++ b/node_modules/lodash/_baseIsMatch.js @@ -0,0 +1,62 @@ +var Stack = require('./_Stack'), + baseIsEqual = require('./_baseIsEqual'); + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ +function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; +} + +module.exports = baseIsMatch; diff --git a/node_modules/lodash/_baseIsNaN.js b/node_modules/lodash/_baseIsNaN.js new file mode 100644 index 0000000..316f1eb --- /dev/null +++ b/node_modules/lodash/_baseIsNaN.js @@ -0,0 +1,12 @@ +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} + +module.exports = baseIsNaN; diff --git a/node_modules/lodash/_baseIsNative.js b/node_modules/lodash/_baseIsNative.js new file mode 100644 index 0000000..8702330 --- /dev/null +++ b/node_modules/lodash/_baseIsNative.js @@ -0,0 +1,47 @@ +var isFunction = require('./isFunction'), + isMasked = require('./_isMasked'), + isObject = require('./isObject'), + toSource = require('./_toSource'); + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} + +module.exports = baseIsNative; diff --git a/node_modules/lodash/_baseIsRegExp.js b/node_modules/lodash/_baseIsRegExp.js new file mode 100644 index 0000000..6cd7c1a --- /dev/null +++ b/node_modules/lodash/_baseIsRegExp.js @@ -0,0 +1,18 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var regexpTag = '[object RegExp]'; + +/** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ +function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; +} + +module.exports = baseIsRegExp; diff --git a/node_modules/lodash/_baseIsSet.js b/node_modules/lodash/_baseIsSet.js new file mode 100644 index 0000000..6dee367 --- /dev/null +++ b/node_modules/lodash/_baseIsSet.js @@ -0,0 +1,18 @@ +var getTag = require('./_getTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var setTag = '[object Set]'; + +/** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ +function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; +} + +module.exports = baseIsSet; diff --git a/node_modules/lodash/_baseIsTypedArray.js b/node_modules/lodash/_baseIsTypedArray.js new file mode 100644 index 0000000..1edb32f --- /dev/null +++ b/node_modules/lodash/_baseIsTypedArray.js @@ -0,0 +1,60 @@ +var baseGetTag = require('./_baseGetTag'), + isLength = require('./isLength'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; +} + +module.exports = baseIsTypedArray; diff --git a/node_modules/lodash/_baseIteratee.js b/node_modules/lodash/_baseIteratee.js new file mode 100644 index 0000000..995c257 --- /dev/null +++ b/node_modules/lodash/_baseIteratee.js @@ -0,0 +1,31 @@ +var baseMatches = require('./_baseMatches'), + baseMatchesProperty = require('./_baseMatchesProperty'), + identity = require('./identity'), + isArray = require('./isArray'), + property = require('./property'); + +/** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ +function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); +} + +module.exports = baseIteratee; diff --git a/node_modules/lodash/_baseKeys.js b/node_modules/lodash/_baseKeys.js new file mode 100644 index 0000000..45e9e6f --- /dev/null +++ b/node_modules/lodash/_baseKeys.js @@ -0,0 +1,30 @@ +var isPrototype = require('./_isPrototype'), + nativeKeys = require('./_nativeKeys'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +module.exports = baseKeys; diff --git a/node_modules/lodash/_baseKeysIn.js b/node_modules/lodash/_baseKeysIn.js new file mode 100644 index 0000000..ea8a0a1 --- /dev/null +++ b/node_modules/lodash/_baseKeysIn.js @@ -0,0 +1,33 @@ +var isObject = require('./isObject'), + isPrototype = require('./_isPrototype'), + nativeKeysIn = require('./_nativeKeysIn'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; +} + +module.exports = baseKeysIn; diff --git a/node_modules/lodash/_baseLodash.js b/node_modules/lodash/_baseLodash.js new file mode 100644 index 0000000..f76c790 --- /dev/null +++ b/node_modules/lodash/_baseLodash.js @@ -0,0 +1,10 @@ +/** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ +function baseLodash() { + // No operation performed. +} + +module.exports = baseLodash; diff --git a/node_modules/lodash/_baseLt.js b/node_modules/lodash/_baseLt.js new file mode 100644 index 0000000..8674d29 --- /dev/null +++ b/node_modules/lodash/_baseLt.js @@ -0,0 +1,14 @@ +/** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ +function baseLt(value, other) { + return value < other; +} + +module.exports = baseLt; diff --git a/node_modules/lodash/_baseMap.js b/node_modules/lodash/_baseMap.js new file mode 100644 index 0000000..0bf5cea --- /dev/null +++ b/node_modules/lodash/_baseMap.js @@ -0,0 +1,22 @@ +var baseEach = require('./_baseEach'), + isArrayLike = require('./isArrayLike'); + +/** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; +} + +module.exports = baseMap; diff --git a/node_modules/lodash/_baseMatches.js b/node_modules/lodash/_baseMatches.js new file mode 100644 index 0000000..e56582a --- /dev/null +++ b/node_modules/lodash/_baseMatches.js @@ -0,0 +1,22 @@ +var baseIsMatch = require('./_baseIsMatch'), + getMatchData = require('./_getMatchData'), + matchesStrictComparable = require('./_matchesStrictComparable'); + +/** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; +} + +module.exports = baseMatches; diff --git a/node_modules/lodash/_baseMatchesProperty.js b/node_modules/lodash/_baseMatchesProperty.js new file mode 100644 index 0000000..24afd89 --- /dev/null +++ b/node_modules/lodash/_baseMatchesProperty.js @@ -0,0 +1,33 @@ +var baseIsEqual = require('./_baseIsEqual'), + get = require('./get'), + hasIn = require('./hasIn'), + isKey = require('./_isKey'), + isStrictComparable = require('./_isStrictComparable'), + matchesStrictComparable = require('./_matchesStrictComparable'), + toKey = require('./_toKey'); + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; +} + +module.exports = baseMatchesProperty; diff --git a/node_modules/lodash/_baseMean.js b/node_modules/lodash/_baseMean.js new file mode 100644 index 0000000..fa9e00a --- /dev/null +++ b/node_modules/lodash/_baseMean.js @@ -0,0 +1,20 @@ +var baseSum = require('./_baseSum'); + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ +function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; +} + +module.exports = baseMean; diff --git a/node_modules/lodash/_baseMerge.js b/node_modules/lodash/_baseMerge.js new file mode 100644 index 0000000..c98b5eb --- /dev/null +++ b/node_modules/lodash/_baseMerge.js @@ -0,0 +1,42 @@ +var Stack = require('./_Stack'), + assignMergeValue = require('./_assignMergeValue'), + baseFor = require('./_baseFor'), + baseMergeDeep = require('./_baseMergeDeep'), + isObject = require('./isObject'), + keysIn = require('./keysIn'), + safeGet = require('./_safeGet'); + +/** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); +} + +module.exports = baseMerge; diff --git a/node_modules/lodash/_baseMergeDeep.js b/node_modules/lodash/_baseMergeDeep.js new file mode 100644 index 0000000..4679e8d --- /dev/null +++ b/node_modules/lodash/_baseMergeDeep.js @@ -0,0 +1,94 @@ +var assignMergeValue = require('./_assignMergeValue'), + cloneBuffer = require('./_cloneBuffer'), + cloneTypedArray = require('./_cloneTypedArray'), + copyArray = require('./_copyArray'), + initCloneObject = require('./_initCloneObject'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isArrayLikeObject = require('./isArrayLikeObject'), + isBuffer = require('./isBuffer'), + isFunction = require('./isFunction'), + isObject = require('./isObject'), + isPlainObject = require('./isPlainObject'), + isTypedArray = require('./isTypedArray'), + safeGet = require('./_safeGet'), + toPlainObject = require('./toPlainObject'); + +/** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); +} + +module.exports = baseMergeDeep; diff --git a/node_modules/lodash/_baseNth.js b/node_modules/lodash/_baseNth.js new file mode 100644 index 0000000..0403c2a --- /dev/null +++ b/node_modules/lodash/_baseNth.js @@ -0,0 +1,20 @@ +var isIndex = require('./_isIndex'); + +/** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ +function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; +} + +module.exports = baseNth; diff --git a/node_modules/lodash/_baseOrderBy.js b/node_modules/lodash/_baseOrderBy.js new file mode 100644 index 0000000..cf588c6 --- /dev/null +++ b/node_modules/lodash/_baseOrderBy.js @@ -0,0 +1,49 @@ +var arrayMap = require('./_arrayMap'), + baseGet = require('./_baseGet'), + baseIteratee = require('./_baseIteratee'), + baseMap = require('./_baseMap'), + baseSortBy = require('./_baseSortBy'), + baseUnary = require('./_baseUnary'), + compareMultiple = require('./_compareMultiple'), + identity = require('./identity'), + isArray = require('./isArray'); + +/** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ +function baseOrderBy(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = arrayMap(iteratees, function(iteratee) { + if (isArray(iteratee)) { + return function(value) { + return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); + }; + } + return iteratee; + }); + } else { + iteratees = [identity]; + } + + var index = -1; + iteratees = arrayMap(iteratees, baseUnary(baseIteratee)); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); +} + +module.exports = baseOrderBy; diff --git a/node_modules/lodash/_basePick.js b/node_modules/lodash/_basePick.js new file mode 100644 index 0000000..09b458a --- /dev/null +++ b/node_modules/lodash/_basePick.js @@ -0,0 +1,19 @@ +var basePickBy = require('./_basePickBy'), + hasIn = require('./hasIn'); + +/** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ +function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); +} + +module.exports = basePick; diff --git a/node_modules/lodash/_basePickBy.js b/node_modules/lodash/_basePickBy.js new file mode 100644 index 0000000..85be68c --- /dev/null +++ b/node_modules/lodash/_basePickBy.js @@ -0,0 +1,30 @@ +var baseGet = require('./_baseGet'), + baseSet = require('./_baseSet'), + castPath = require('./_castPath'); + +/** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ +function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; +} + +module.exports = basePickBy; diff --git a/node_modules/lodash/_baseProperty.js b/node_modules/lodash/_baseProperty.js new file mode 100644 index 0000000..496281e --- /dev/null +++ b/node_modules/lodash/_baseProperty.js @@ -0,0 +1,14 @@ +/** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; +} + +module.exports = baseProperty; diff --git a/node_modules/lodash/_basePropertyDeep.js b/node_modules/lodash/_basePropertyDeep.js new file mode 100644 index 0000000..1e5aae5 --- /dev/null +++ b/node_modules/lodash/_basePropertyDeep.js @@ -0,0 +1,16 @@ +var baseGet = require('./_baseGet'); + +/** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; +} + +module.exports = basePropertyDeep; diff --git a/node_modules/lodash/_basePropertyOf.js b/node_modules/lodash/_basePropertyOf.js new file mode 100644 index 0000000..4617399 --- /dev/null +++ b/node_modules/lodash/_basePropertyOf.js @@ -0,0 +1,14 @@ +/** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; +} + +module.exports = basePropertyOf; diff --git a/node_modules/lodash/_basePullAll.js b/node_modules/lodash/_basePullAll.js new file mode 100644 index 0000000..305720e --- /dev/null +++ b/node_modules/lodash/_basePullAll.js @@ -0,0 +1,51 @@ +var arrayMap = require('./_arrayMap'), + baseIndexOf = require('./_baseIndexOf'), + baseIndexOfWith = require('./_baseIndexOfWith'), + baseUnary = require('./_baseUnary'), + copyArray = require('./_copyArray'); + +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/** Built-in value references. */ +var splice = arrayProto.splice; + +/** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ +function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; +} + +module.exports = basePullAll; diff --git a/node_modules/lodash/_basePullAt.js b/node_modules/lodash/_basePullAt.js new file mode 100644 index 0000000..c3e9e71 --- /dev/null +++ b/node_modules/lodash/_basePullAt.js @@ -0,0 +1,37 @@ +var baseUnset = require('./_baseUnset'), + isIndex = require('./_isIndex'); + +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/** Built-in value references. */ +var splice = arrayProto.splice; + +/** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ +function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; +} + +module.exports = basePullAt; diff --git a/node_modules/lodash/_baseRandom.js b/node_modules/lodash/_baseRandom.js new file mode 100644 index 0000000..94f76a7 --- /dev/null +++ b/node_modules/lodash/_baseRandom.js @@ -0,0 +1,18 @@ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeFloor = Math.floor, + nativeRandom = Math.random; + +/** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ +function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); +} + +module.exports = baseRandom; diff --git a/node_modules/lodash/_baseRange.js b/node_modules/lodash/_baseRange.js new file mode 100644 index 0000000..0fb8e41 --- /dev/null +++ b/node_modules/lodash/_baseRange.js @@ -0,0 +1,28 @@ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeCeil = Math.ceil, + nativeMax = Math.max; + +/** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ +function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; +} + +module.exports = baseRange; diff --git a/node_modules/lodash/_baseReduce.js b/node_modules/lodash/_baseReduce.js new file mode 100644 index 0000000..5a1f8b5 --- /dev/null +++ b/node_modules/lodash/_baseReduce.js @@ -0,0 +1,23 @@ +/** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ +function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; +} + +module.exports = baseReduce; diff --git a/node_modules/lodash/_baseRepeat.js b/node_modules/lodash/_baseRepeat.js new file mode 100644 index 0000000..ee44c31 --- /dev/null +++ b/node_modules/lodash/_baseRepeat.js @@ -0,0 +1,35 @@ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeFloor = Math.floor; + +/** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ +function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; +} + +module.exports = baseRepeat; diff --git a/node_modules/lodash/_baseRest.js b/node_modules/lodash/_baseRest.js new file mode 100644 index 0000000..d0dc4bd --- /dev/null +++ b/node_modules/lodash/_baseRest.js @@ -0,0 +1,17 @@ +var identity = require('./identity'), + overRest = require('./_overRest'), + setToString = require('./_setToString'); + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); +} + +module.exports = baseRest; diff --git a/node_modules/lodash/_baseSample.js b/node_modules/lodash/_baseSample.js new file mode 100644 index 0000000..58582b9 --- /dev/null +++ b/node_modules/lodash/_baseSample.js @@ -0,0 +1,15 @@ +var arraySample = require('./_arraySample'), + values = require('./values'); + +/** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ +function baseSample(collection) { + return arraySample(values(collection)); +} + +module.exports = baseSample; diff --git a/node_modules/lodash/_baseSampleSize.js b/node_modules/lodash/_baseSampleSize.js new file mode 100644 index 0000000..5c90ec5 --- /dev/null +++ b/node_modules/lodash/_baseSampleSize.js @@ -0,0 +1,18 @@ +var baseClamp = require('./_baseClamp'), + shuffleSelf = require('./_shuffleSelf'), + values = require('./values'); + +/** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ +function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); +} + +module.exports = baseSampleSize; diff --git a/node_modules/lodash/_baseSet.js b/node_modules/lodash/_baseSet.js new file mode 100644 index 0000000..99f4fbf --- /dev/null +++ b/node_modules/lodash/_baseSet.js @@ -0,0 +1,51 @@ +var assignValue = require('./_assignValue'), + castPath = require('./_castPath'), + isIndex = require('./_isIndex'), + isObject = require('./isObject'), + toKey = require('./_toKey'); + +/** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ +function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + return object; + } + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; +} + +module.exports = baseSet; diff --git a/node_modules/lodash/_baseSetData.js b/node_modules/lodash/_baseSetData.js new file mode 100644 index 0000000..c409947 --- /dev/null +++ b/node_modules/lodash/_baseSetData.js @@ -0,0 +1,17 @@ +var identity = require('./identity'), + metaMap = require('./_metaMap'); + +/** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ +var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; +}; + +module.exports = baseSetData; diff --git a/node_modules/lodash/_baseSetToString.js b/node_modules/lodash/_baseSetToString.js new file mode 100644 index 0000000..89eaca3 --- /dev/null +++ b/node_modules/lodash/_baseSetToString.js @@ -0,0 +1,22 @@ +var constant = require('./constant'), + defineProperty = require('./_defineProperty'), + identity = require('./identity'); + +/** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); +}; + +module.exports = baseSetToString; diff --git a/node_modules/lodash/_baseShuffle.js b/node_modules/lodash/_baseShuffle.js new file mode 100644 index 0000000..023077a --- /dev/null +++ b/node_modules/lodash/_baseShuffle.js @@ -0,0 +1,15 @@ +var shuffleSelf = require('./_shuffleSelf'), + values = require('./values'); + +/** + * The base implementation of `_.shuffle`. + * + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + */ +function baseShuffle(collection) { + return shuffleSelf(values(collection)); +} + +module.exports = baseShuffle; diff --git a/node_modules/lodash/_baseSlice.js b/node_modules/lodash/_baseSlice.js new file mode 100644 index 0000000..786f6c9 --- /dev/null +++ b/node_modules/lodash/_baseSlice.js @@ -0,0 +1,31 @@ +/** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; +} + +module.exports = baseSlice; diff --git a/node_modules/lodash/_baseSome.js b/node_modules/lodash/_baseSome.js new file mode 100644 index 0000000..58f3f44 --- /dev/null +++ b/node_modules/lodash/_baseSome.js @@ -0,0 +1,22 @@ +var baseEach = require('./_baseEach'); + +/** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; +} + +module.exports = baseSome; diff --git a/node_modules/lodash/_baseSortBy.js b/node_modules/lodash/_baseSortBy.js new file mode 100644 index 0000000..a25c92e --- /dev/null +++ b/node_modules/lodash/_baseSortBy.js @@ -0,0 +1,21 @@ +/** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ +function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; +} + +module.exports = baseSortBy; diff --git a/node_modules/lodash/_baseSortedIndex.js b/node_modules/lodash/_baseSortedIndex.js new file mode 100644 index 0000000..638c366 --- /dev/null +++ b/node_modules/lodash/_baseSortedIndex.js @@ -0,0 +1,42 @@ +var baseSortedIndexBy = require('./_baseSortedIndexBy'), + identity = require('./identity'), + isSymbol = require('./isSymbol'); + +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH = 4294967295, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + +/** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ +function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); +} + +module.exports = baseSortedIndex; diff --git a/node_modules/lodash/_baseSortedIndexBy.js b/node_modules/lodash/_baseSortedIndexBy.js new file mode 100644 index 0000000..c247b37 --- /dev/null +++ b/node_modules/lodash/_baseSortedIndexBy.js @@ -0,0 +1,67 @@ +var isSymbol = require('./isSymbol'); + +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeFloor = Math.floor, + nativeMin = Math.min; + +/** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ +function baseSortedIndexBy(array, value, iteratee, retHighest) { + var low = 0, + high = array == null ? 0 : array.length; + if (high === 0) { + return 0; + } + + value = iteratee(value); + var valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); +} + +module.exports = baseSortedIndexBy; diff --git a/node_modules/lodash/_baseSortedUniq.js b/node_modules/lodash/_baseSortedUniq.js new file mode 100644 index 0000000..802159a --- /dev/null +++ b/node_modules/lodash/_baseSortedUniq.js @@ -0,0 +1,30 @@ +var eq = require('./eq'); + +/** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ +function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; +} + +module.exports = baseSortedUniq; diff --git a/node_modules/lodash/_baseSum.js b/node_modules/lodash/_baseSum.js new file mode 100644 index 0000000..a9e84c1 --- /dev/null +++ b/node_modules/lodash/_baseSum.js @@ -0,0 +1,24 @@ +/** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ +function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; +} + +module.exports = baseSum; diff --git a/node_modules/lodash/_baseTimes.js b/node_modules/lodash/_baseTimes.js new file mode 100644 index 0000000..0603fc3 --- /dev/null +++ b/node_modules/lodash/_baseTimes.js @@ -0,0 +1,20 @@ +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +module.exports = baseTimes; diff --git a/node_modules/lodash/_baseToNumber.js b/node_modules/lodash/_baseToNumber.js new file mode 100644 index 0000000..04859f3 --- /dev/null +++ b/node_modules/lodash/_baseToNumber.js @@ -0,0 +1,24 @@ +var isSymbol = require('./isSymbol'); + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ +function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; +} + +module.exports = baseToNumber; diff --git a/node_modules/lodash/_baseToPairs.js b/node_modules/lodash/_baseToPairs.js new file mode 100644 index 0000000..bff1991 --- /dev/null +++ b/node_modules/lodash/_baseToPairs.js @@ -0,0 +1,18 @@ +var arrayMap = require('./_arrayMap'); + +/** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ +function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); +} + +module.exports = baseToPairs; diff --git a/node_modules/lodash/_baseToString.js b/node_modules/lodash/_baseToString.js new file mode 100644 index 0000000..ada6ad2 --- /dev/null +++ b/node_modules/lodash/_baseToString.js @@ -0,0 +1,37 @@ +var Symbol = require('./_Symbol'), + arrayMap = require('./_arrayMap'), + isArray = require('./isArray'), + isSymbol = require('./isSymbol'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +module.exports = baseToString; diff --git a/node_modules/lodash/_baseTrim.js b/node_modules/lodash/_baseTrim.js new file mode 100644 index 0000000..3e2797d --- /dev/null +++ b/node_modules/lodash/_baseTrim.js @@ -0,0 +1,19 @@ +var trimmedEndIndex = require('./_trimmedEndIndex'); + +/** Used to match leading whitespace. */ +var reTrimStart = /^\s+/; + +/** + * The base implementation of `_.trim`. + * + * @private + * @param {string} string The string to trim. + * @returns {string} Returns the trimmed string. + */ +function baseTrim(string) { + return string + ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') + : string; +} + +module.exports = baseTrim; diff --git a/node_modules/lodash/_baseUnary.js b/node_modules/lodash/_baseUnary.js new file mode 100644 index 0000000..98639e9 --- /dev/null +++ b/node_modules/lodash/_baseUnary.js @@ -0,0 +1,14 @@ +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} + +module.exports = baseUnary; diff --git a/node_modules/lodash/_baseUniq.js b/node_modules/lodash/_baseUniq.js new file mode 100644 index 0000000..aea459d --- /dev/null +++ b/node_modules/lodash/_baseUniq.js @@ -0,0 +1,72 @@ +var SetCache = require('./_SetCache'), + arrayIncludes = require('./_arrayIncludes'), + arrayIncludesWith = require('./_arrayIncludesWith'), + cacheHas = require('./_cacheHas'), + createSet = require('./_createSet'), + setToArray = require('./_setToArray'); + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ +function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; +} + +module.exports = baseUniq; diff --git a/node_modules/lodash/_baseUnset.js b/node_modules/lodash/_baseUnset.js new file mode 100644 index 0000000..e4eccb0 --- /dev/null +++ b/node_modules/lodash/_baseUnset.js @@ -0,0 +1,52 @@ +var castPath = require('./_castPath'), + last = require('./last'), + parent = require('./_parent'), + toKey = require('./_toKey'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ +function baseUnset(object, path) { + path = castPath(path, object); + + // Prevent prototype pollution: + // https://github.com/lodash/lodash/security/advisories/GHSA-xxjr-mmjv-4gpg + // https://github.com/lodash/lodash/security/advisories/GHSA-f23m-r3pf-42rh + var index = -1, + length = path.length; + + if (!length) { + return true; + } + + while (++index < length) { + var key = toKey(path[index]); + + // Always block "__proto__" anywhere in the path if it's not expected + if (key === '__proto__' && !hasOwnProperty.call(object, '__proto__')) { + return false; + } + + // Block constructor/prototype as non-terminal traversal keys to prevent + // escaping the object graph into built-in constructors and prototypes. + if ((key === 'constructor' || key === 'prototype') && index < length - 1) { + return false; + } + } + + var obj = parent(object, path); + return obj == null || delete obj[toKey(last(path))]; +} + +module.exports = baseUnset; diff --git a/node_modules/lodash/_baseUpdate.js b/node_modules/lodash/_baseUpdate.js new file mode 100644 index 0000000..92a6237 --- /dev/null +++ b/node_modules/lodash/_baseUpdate.js @@ -0,0 +1,18 @@ +var baseGet = require('./_baseGet'), + baseSet = require('./_baseSet'); + +/** + * The base implementation of `_.update`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ +function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); +} + +module.exports = baseUpdate; diff --git a/node_modules/lodash/_baseValues.js b/node_modules/lodash/_baseValues.js new file mode 100644 index 0000000..b95faad --- /dev/null +++ b/node_modules/lodash/_baseValues.js @@ -0,0 +1,19 @@ +var arrayMap = require('./_arrayMap'); + +/** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ +function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); +} + +module.exports = baseValues; diff --git a/node_modules/lodash/_baseWhile.js b/node_modules/lodash/_baseWhile.js new file mode 100644 index 0000000..07eac61 --- /dev/null +++ b/node_modules/lodash/_baseWhile.js @@ -0,0 +1,26 @@ +var baseSlice = require('./_baseSlice'); + +/** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ +function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); +} + +module.exports = baseWhile; diff --git a/node_modules/lodash/_baseWrapperValue.js b/node_modules/lodash/_baseWrapperValue.js new file mode 100644 index 0000000..443e0df --- /dev/null +++ b/node_modules/lodash/_baseWrapperValue.js @@ -0,0 +1,25 @@ +var LazyWrapper = require('./_LazyWrapper'), + arrayPush = require('./_arrayPush'), + arrayReduce = require('./_arrayReduce'); + +/** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ +function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); +} + +module.exports = baseWrapperValue; diff --git a/node_modules/lodash/_baseXor.js b/node_modules/lodash/_baseXor.js new file mode 100644 index 0000000..8e69338 --- /dev/null +++ b/node_modules/lodash/_baseXor.js @@ -0,0 +1,36 @@ +var baseDifference = require('./_baseDifference'), + baseFlatten = require('./_baseFlatten'), + baseUniq = require('./_baseUniq'); + +/** + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. + */ +function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); + + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } + } + return baseUniq(baseFlatten(result, 1), iteratee, comparator); +} + +module.exports = baseXor; diff --git a/node_modules/lodash/_baseZipObject.js b/node_modules/lodash/_baseZipObject.js new file mode 100644 index 0000000..401f85b --- /dev/null +++ b/node_modules/lodash/_baseZipObject.js @@ -0,0 +1,23 @@ +/** + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. + */ +function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; + + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; +} + +module.exports = baseZipObject; diff --git a/node_modules/lodash/_cacheHas.js b/node_modules/lodash/_cacheHas.js new file mode 100644 index 0000000..2dec892 --- /dev/null +++ b/node_modules/lodash/_cacheHas.js @@ -0,0 +1,13 @@ +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} + +module.exports = cacheHas; diff --git a/node_modules/lodash/_castArrayLikeObject.js b/node_modules/lodash/_castArrayLikeObject.js new file mode 100644 index 0000000..92c75fa --- /dev/null +++ b/node_modules/lodash/_castArrayLikeObject.js @@ -0,0 +1,14 @@ +var isArrayLikeObject = require('./isArrayLikeObject'); + +/** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ +function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; +} + +module.exports = castArrayLikeObject; diff --git a/node_modules/lodash/_castFunction.js b/node_modules/lodash/_castFunction.js new file mode 100644 index 0000000..98c91ae --- /dev/null +++ b/node_modules/lodash/_castFunction.js @@ -0,0 +1,14 @@ +var identity = require('./identity'); + +/** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ +function castFunction(value) { + return typeof value == 'function' ? value : identity; +} + +module.exports = castFunction; diff --git a/node_modules/lodash/_castPath.js b/node_modules/lodash/_castPath.js new file mode 100644 index 0000000..017e4c1 --- /dev/null +++ b/node_modules/lodash/_castPath.js @@ -0,0 +1,21 @@ +var isArray = require('./isArray'), + isKey = require('./_isKey'), + stringToPath = require('./_stringToPath'), + toString = require('./toString'); + +/** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ +function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); +} + +module.exports = castPath; diff --git a/node_modules/lodash/_castRest.js b/node_modules/lodash/_castRest.js new file mode 100644 index 0000000..213c66f --- /dev/null +++ b/node_modules/lodash/_castRest.js @@ -0,0 +1,14 @@ +var baseRest = require('./_baseRest'); + +/** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ +var castRest = baseRest; + +module.exports = castRest; diff --git a/node_modules/lodash/_castSlice.js b/node_modules/lodash/_castSlice.js new file mode 100644 index 0000000..071faeb --- /dev/null +++ b/node_modules/lodash/_castSlice.js @@ -0,0 +1,18 @@ +var baseSlice = require('./_baseSlice'); + +/** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ +function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); +} + +module.exports = castSlice; diff --git a/node_modules/lodash/_charsEndIndex.js b/node_modules/lodash/_charsEndIndex.js new file mode 100644 index 0000000..07908ff --- /dev/null +++ b/node_modules/lodash/_charsEndIndex.js @@ -0,0 +1,19 @@ +var baseIndexOf = require('./_baseIndexOf'); + +/** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ +function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; +} + +module.exports = charsEndIndex; diff --git a/node_modules/lodash/_charsStartIndex.js b/node_modules/lodash/_charsStartIndex.js new file mode 100644 index 0000000..b17afd2 --- /dev/null +++ b/node_modules/lodash/_charsStartIndex.js @@ -0,0 +1,20 @@ +var baseIndexOf = require('./_baseIndexOf'); + +/** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ +function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; +} + +module.exports = charsStartIndex; diff --git a/node_modules/lodash/_cloneArrayBuffer.js b/node_modules/lodash/_cloneArrayBuffer.js new file mode 100644 index 0000000..c3d8f6e --- /dev/null +++ b/node_modules/lodash/_cloneArrayBuffer.js @@ -0,0 +1,16 @@ +var Uint8Array = require('./_Uint8Array'); + +/** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ +function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; +} + +module.exports = cloneArrayBuffer; diff --git a/node_modules/lodash/_cloneBuffer.js b/node_modules/lodash/_cloneBuffer.js new file mode 100644 index 0000000..27c4810 --- /dev/null +++ b/node_modules/lodash/_cloneBuffer.js @@ -0,0 +1,35 @@ +var root = require('./_root'); + +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; + +/** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ +function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; +} + +module.exports = cloneBuffer; diff --git a/node_modules/lodash/_cloneDataView.js b/node_modules/lodash/_cloneDataView.js new file mode 100644 index 0000000..9c9b7b0 --- /dev/null +++ b/node_modules/lodash/_cloneDataView.js @@ -0,0 +1,16 @@ +var cloneArrayBuffer = require('./_cloneArrayBuffer'); + +/** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ +function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); +} + +module.exports = cloneDataView; diff --git a/node_modules/lodash/_cloneRegExp.js b/node_modules/lodash/_cloneRegExp.js new file mode 100644 index 0000000..64a30df --- /dev/null +++ b/node_modules/lodash/_cloneRegExp.js @@ -0,0 +1,17 @@ +/** Used to match `RegExp` flags from their coerced string values. */ +var reFlags = /\w*$/; + +/** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ +function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; +} + +module.exports = cloneRegExp; diff --git a/node_modules/lodash/_cloneSymbol.js b/node_modules/lodash/_cloneSymbol.js new file mode 100644 index 0000000..bede39f --- /dev/null +++ b/node_modules/lodash/_cloneSymbol.js @@ -0,0 +1,18 @@ +var Symbol = require('./_Symbol'); + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + +/** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ +function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; +} + +module.exports = cloneSymbol; diff --git a/node_modules/lodash/_cloneTypedArray.js b/node_modules/lodash/_cloneTypedArray.js new file mode 100644 index 0000000..7aad84d --- /dev/null +++ b/node_modules/lodash/_cloneTypedArray.js @@ -0,0 +1,16 @@ +var cloneArrayBuffer = require('./_cloneArrayBuffer'); + +/** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ +function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); +} + +module.exports = cloneTypedArray; diff --git a/node_modules/lodash/_compareAscending.js b/node_modules/lodash/_compareAscending.js new file mode 100644 index 0000000..8dc2791 --- /dev/null +++ b/node_modules/lodash/_compareAscending.js @@ -0,0 +1,41 @@ +var isSymbol = require('./isSymbol'); + +/** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ +function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; +} + +module.exports = compareAscending; diff --git a/node_modules/lodash/_compareMultiple.js b/node_modules/lodash/_compareMultiple.js new file mode 100644 index 0000000..ad61f0f --- /dev/null +++ b/node_modules/lodash/_compareMultiple.js @@ -0,0 +1,44 @@ +var compareAscending = require('./_compareAscending'); + +/** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ +function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; +} + +module.exports = compareMultiple; diff --git a/node_modules/lodash/_composeArgs.js b/node_modules/lodash/_composeArgs.js new file mode 100644 index 0000000..1ce40f4 --- /dev/null +++ b/node_modules/lodash/_composeArgs.js @@ -0,0 +1,39 @@ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ +function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; +} + +module.exports = composeArgs; diff --git a/node_modules/lodash/_composeArgsRight.js b/node_modules/lodash/_composeArgsRight.js new file mode 100644 index 0000000..8dc588d --- /dev/null +++ b/node_modules/lodash/_composeArgsRight.js @@ -0,0 +1,41 @@ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ +function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; +} + +module.exports = composeArgsRight; diff --git a/node_modules/lodash/_copyArray.js b/node_modules/lodash/_copyArray.js new file mode 100644 index 0000000..cd94d5d --- /dev/null +++ b/node_modules/lodash/_copyArray.js @@ -0,0 +1,20 @@ +/** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ +function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; +} + +module.exports = copyArray; diff --git a/node_modules/lodash/_copyObject.js b/node_modules/lodash/_copyObject.js new file mode 100644 index 0000000..2f2a5c2 --- /dev/null +++ b/node_modules/lodash/_copyObject.js @@ -0,0 +1,40 @@ +var assignValue = require('./_assignValue'), + baseAssignValue = require('./_baseAssignValue'); + +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; +} + +module.exports = copyObject; diff --git a/node_modules/lodash/_copySymbols.js b/node_modules/lodash/_copySymbols.js new file mode 100644 index 0000000..c35944a --- /dev/null +++ b/node_modules/lodash/_copySymbols.js @@ -0,0 +1,16 @@ +var copyObject = require('./_copyObject'), + getSymbols = require('./_getSymbols'); + +/** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ +function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); +} + +module.exports = copySymbols; diff --git a/node_modules/lodash/_copySymbolsIn.js b/node_modules/lodash/_copySymbolsIn.js new file mode 100644 index 0000000..fdf20a7 --- /dev/null +++ b/node_modules/lodash/_copySymbolsIn.js @@ -0,0 +1,16 @@ +var copyObject = require('./_copyObject'), + getSymbolsIn = require('./_getSymbolsIn'); + +/** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ +function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); +} + +module.exports = copySymbolsIn; diff --git a/node_modules/lodash/_coreJsData.js b/node_modules/lodash/_coreJsData.js new file mode 100644 index 0000000..f8e5b4e --- /dev/null +++ b/node_modules/lodash/_coreJsData.js @@ -0,0 +1,6 @@ +var root = require('./_root'); + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +module.exports = coreJsData; diff --git a/node_modules/lodash/_countHolders.js b/node_modules/lodash/_countHolders.js new file mode 100644 index 0000000..718fcda --- /dev/null +++ b/node_modules/lodash/_countHolders.js @@ -0,0 +1,21 @@ +/** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ +function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; +} + +module.exports = countHolders; diff --git a/node_modules/lodash/_createAggregator.js b/node_modules/lodash/_createAggregator.js new file mode 100644 index 0000000..0be42c4 --- /dev/null +++ b/node_modules/lodash/_createAggregator.js @@ -0,0 +1,23 @@ +var arrayAggregator = require('./_arrayAggregator'), + baseAggregator = require('./_baseAggregator'), + baseIteratee = require('./_baseIteratee'), + isArray = require('./isArray'); + +/** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ +function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, baseIteratee(iteratee, 2), accumulator); + }; +} + +module.exports = createAggregator; diff --git a/node_modules/lodash/_createAssigner.js b/node_modules/lodash/_createAssigner.js new file mode 100644 index 0000000..1f904c5 --- /dev/null +++ b/node_modules/lodash/_createAssigner.js @@ -0,0 +1,37 @@ +var baseRest = require('./_baseRest'), + isIterateeCall = require('./_isIterateeCall'); + +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); +} + +module.exports = createAssigner; diff --git a/node_modules/lodash/_createBaseEach.js b/node_modules/lodash/_createBaseEach.js new file mode 100644 index 0000000..d24fdd1 --- /dev/null +++ b/node_modules/lodash/_createBaseEach.js @@ -0,0 +1,32 @@ +var isArrayLike = require('./isArrayLike'); + +/** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; +} + +module.exports = createBaseEach; diff --git a/node_modules/lodash/_createBaseFor.js b/node_modules/lodash/_createBaseFor.js new file mode 100644 index 0000000..94cbf29 --- /dev/null +++ b/node_modules/lodash/_createBaseFor.js @@ -0,0 +1,25 @@ +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; +} + +module.exports = createBaseFor; diff --git a/node_modules/lodash/_createBind.js b/node_modules/lodash/_createBind.js new file mode 100644 index 0000000..07cb99f --- /dev/null +++ b/node_modules/lodash/_createBind.js @@ -0,0 +1,28 @@ +var createCtor = require('./_createCtor'), + root = require('./_root'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1; + +/** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; +} + +module.exports = createBind; diff --git a/node_modules/lodash/_createCaseFirst.js b/node_modules/lodash/_createCaseFirst.js new file mode 100644 index 0000000..fe8ea48 --- /dev/null +++ b/node_modules/lodash/_createCaseFirst.js @@ -0,0 +1,33 @@ +var castSlice = require('./_castSlice'), + hasUnicode = require('./_hasUnicode'), + stringToArray = require('./_stringToArray'), + toString = require('./toString'); + +/** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ +function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; +} + +module.exports = createCaseFirst; diff --git a/node_modules/lodash/_createCompounder.js b/node_modules/lodash/_createCompounder.js new file mode 100644 index 0000000..8d4cee2 --- /dev/null +++ b/node_modules/lodash/_createCompounder.js @@ -0,0 +1,24 @@ +var arrayReduce = require('./_arrayReduce'), + deburr = require('./deburr'), + words = require('./words'); + +/** Used to compose unicode capture groups. */ +var rsApos = "['\u2019]"; + +/** Used to match apostrophes. */ +var reApos = RegExp(rsApos, 'g'); + +/** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ +function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; +} + +module.exports = createCompounder; diff --git a/node_modules/lodash/_createCtor.js b/node_modules/lodash/_createCtor.js new file mode 100644 index 0000000..9047aa5 --- /dev/null +++ b/node_modules/lodash/_createCtor.js @@ -0,0 +1,37 @@ +var baseCreate = require('./_baseCreate'), + isObject = require('./isObject'); + +/** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ +function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; +} + +module.exports = createCtor; diff --git a/node_modules/lodash/_createCurry.js b/node_modules/lodash/_createCurry.js new file mode 100644 index 0000000..f06c2cd --- /dev/null +++ b/node_modules/lodash/_createCurry.js @@ -0,0 +1,46 @@ +var apply = require('./_apply'), + createCtor = require('./_createCtor'), + createHybrid = require('./_createHybrid'), + createRecurry = require('./_createRecurry'), + getHolder = require('./_getHolder'), + replaceHolders = require('./_replaceHolders'), + root = require('./_root'); + +/** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; +} + +module.exports = createCurry; diff --git a/node_modules/lodash/_createFind.js b/node_modules/lodash/_createFind.js new file mode 100644 index 0000000..8859ff8 --- /dev/null +++ b/node_modules/lodash/_createFind.js @@ -0,0 +1,25 @@ +var baseIteratee = require('./_baseIteratee'), + isArrayLike = require('./isArrayLike'), + keys = require('./keys'); + +/** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ +function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = baseIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; +} + +module.exports = createFind; diff --git a/node_modules/lodash/_createFlow.js b/node_modules/lodash/_createFlow.js new file mode 100644 index 0000000..baaddbf --- /dev/null +++ b/node_modules/lodash/_createFlow.js @@ -0,0 +1,78 @@ +var LodashWrapper = require('./_LodashWrapper'), + flatRest = require('./_flatRest'), + getData = require('./_getData'), + getFuncName = require('./_getFuncName'), + isArray = require('./isArray'), + isLaziable = require('./_isLaziable'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used to compose bitmasks for function metadata. */ +var WRAP_CURRY_FLAG = 8, + WRAP_PARTIAL_FLAG = 32, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256; + +/** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ +function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); +} + +module.exports = createFlow; diff --git a/node_modules/lodash/_createHybrid.js b/node_modules/lodash/_createHybrid.js new file mode 100644 index 0000000..b671bd1 --- /dev/null +++ b/node_modules/lodash/_createHybrid.js @@ -0,0 +1,92 @@ +var composeArgs = require('./_composeArgs'), + composeArgsRight = require('./_composeArgsRight'), + countHolders = require('./_countHolders'), + createCtor = require('./_createCtor'), + createRecurry = require('./_createRecurry'), + getHolder = require('./_getHolder'), + reorder = require('./_reorder'), + replaceHolders = require('./_replaceHolders'), + root = require('./_root'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_ARY_FLAG = 128, + WRAP_FLIP_FLAG = 512; + +/** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; +} + +module.exports = createHybrid; diff --git a/node_modules/lodash/_createInverter.js b/node_modules/lodash/_createInverter.js new file mode 100644 index 0000000..6c0c562 --- /dev/null +++ b/node_modules/lodash/_createInverter.js @@ -0,0 +1,17 @@ +var baseInverter = require('./_baseInverter'); + +/** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ +function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; +} + +module.exports = createInverter; diff --git a/node_modules/lodash/_createMathOperation.js b/node_modules/lodash/_createMathOperation.js new file mode 100644 index 0000000..f1e238a --- /dev/null +++ b/node_modules/lodash/_createMathOperation.js @@ -0,0 +1,38 @@ +var baseToNumber = require('./_baseToNumber'), + baseToString = require('./_baseToString'); + +/** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ +function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; +} + +module.exports = createMathOperation; diff --git a/node_modules/lodash/_createOver.js b/node_modules/lodash/_createOver.js new file mode 100644 index 0000000..3b94551 --- /dev/null +++ b/node_modules/lodash/_createOver.js @@ -0,0 +1,27 @@ +var apply = require('./_apply'), + arrayMap = require('./_arrayMap'), + baseIteratee = require('./_baseIteratee'), + baseRest = require('./_baseRest'), + baseUnary = require('./_baseUnary'), + flatRest = require('./_flatRest'); + +/** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ +function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(baseIteratee)); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); +} + +module.exports = createOver; diff --git a/node_modules/lodash/_createPadding.js b/node_modules/lodash/_createPadding.js new file mode 100644 index 0000000..2124612 --- /dev/null +++ b/node_modules/lodash/_createPadding.js @@ -0,0 +1,33 @@ +var baseRepeat = require('./_baseRepeat'), + baseToString = require('./_baseToString'), + castSlice = require('./_castSlice'), + hasUnicode = require('./_hasUnicode'), + stringSize = require('./_stringSize'), + stringToArray = require('./_stringToArray'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeCeil = Math.ceil; + +/** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ +function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); +} + +module.exports = createPadding; diff --git a/node_modules/lodash/_createPartial.js b/node_modules/lodash/_createPartial.js new file mode 100644 index 0000000..e16c248 --- /dev/null +++ b/node_modules/lodash/_createPartial.js @@ -0,0 +1,43 @@ +var apply = require('./_apply'), + createCtor = require('./_createCtor'), + root = require('./_root'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1; + +/** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ +function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; +} + +module.exports = createPartial; diff --git a/node_modules/lodash/_createRange.js b/node_modules/lodash/_createRange.js new file mode 100644 index 0000000..9f52c77 --- /dev/null +++ b/node_modules/lodash/_createRange.js @@ -0,0 +1,30 @@ +var baseRange = require('./_baseRange'), + isIterateeCall = require('./_isIterateeCall'), + toFinite = require('./toFinite'); + +/** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ +function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; +} + +module.exports = createRange; diff --git a/node_modules/lodash/_createRecurry.js b/node_modules/lodash/_createRecurry.js new file mode 100644 index 0000000..eb29fb2 --- /dev/null +++ b/node_modules/lodash/_createRecurry.js @@ -0,0 +1,56 @@ +var isLaziable = require('./_isLaziable'), + setData = require('./_setData'), + setWrapToString = require('./_setWrapToString'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64; + +/** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); +} + +module.exports = createRecurry; diff --git a/node_modules/lodash/_createRelationalOperation.js b/node_modules/lodash/_createRelationalOperation.js new file mode 100644 index 0000000..a17c6b5 --- /dev/null +++ b/node_modules/lodash/_createRelationalOperation.js @@ -0,0 +1,20 @@ +var toNumber = require('./toNumber'); + +/** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ +function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; +} + +module.exports = createRelationalOperation; diff --git a/node_modules/lodash/_createRound.js b/node_modules/lodash/_createRound.js new file mode 100644 index 0000000..88be5df --- /dev/null +++ b/node_modules/lodash/_createRound.js @@ -0,0 +1,35 @@ +var root = require('./_root'), + toInteger = require('./toInteger'), + toNumber = require('./toNumber'), + toString = require('./toString'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = root.isFinite, + nativeMin = Math.min; + +/** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ +function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision && nativeIsFinite(number)) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; +} + +module.exports = createRound; diff --git a/node_modules/lodash/_createSet.js b/node_modules/lodash/_createSet.js new file mode 100644 index 0000000..0f644ee --- /dev/null +++ b/node_modules/lodash/_createSet.js @@ -0,0 +1,19 @@ +var Set = require('./_Set'), + noop = require('./noop'), + setToArray = require('./_setToArray'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ +var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); +}; + +module.exports = createSet; diff --git a/node_modules/lodash/_createToPairs.js b/node_modules/lodash/_createToPairs.js new file mode 100644 index 0000000..568417a --- /dev/null +++ b/node_modules/lodash/_createToPairs.js @@ -0,0 +1,30 @@ +var baseToPairs = require('./_baseToPairs'), + getTag = require('./_getTag'), + mapToArray = require('./_mapToArray'), + setToPairs = require('./_setToPairs'); + +/** `Object#toString` result references. */ +var mapTag = '[object Map]', + setTag = '[object Set]'; + +/** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ +function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; +} + +module.exports = createToPairs; diff --git a/node_modules/lodash/_createWrap.js b/node_modules/lodash/_createWrap.js new file mode 100644 index 0000000..33f0633 --- /dev/null +++ b/node_modules/lodash/_createWrap.js @@ -0,0 +1,106 @@ +var baseSetData = require('./_baseSetData'), + createBind = require('./_createBind'), + createCurry = require('./_createCurry'), + createHybrid = require('./_createHybrid'), + createPartial = require('./_createPartial'), + getData = require('./_getData'), + mergeData = require('./_mergeData'), + setData = require('./_setData'), + setWrapToString = require('./_setWrapToString'), + toInteger = require('./toInteger'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); +} + +module.exports = createWrap; diff --git a/node_modules/lodash/_customDefaultsAssignIn.js b/node_modules/lodash/_customDefaultsAssignIn.js new file mode 100644 index 0000000..1f49e6f --- /dev/null +++ b/node_modules/lodash/_customDefaultsAssignIn.js @@ -0,0 +1,29 @@ +var eq = require('./eq'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ +function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; +} + +module.exports = customDefaultsAssignIn; diff --git a/node_modules/lodash/_customDefaultsMerge.js b/node_modules/lodash/_customDefaultsMerge.js new file mode 100644 index 0000000..4cab317 --- /dev/null +++ b/node_modules/lodash/_customDefaultsMerge.js @@ -0,0 +1,28 @@ +var baseMerge = require('./_baseMerge'), + isObject = require('./isObject'); + +/** + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ +function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; +} + +module.exports = customDefaultsMerge; diff --git a/node_modules/lodash/_customOmitClone.js b/node_modules/lodash/_customOmitClone.js new file mode 100644 index 0000000..968db2e --- /dev/null +++ b/node_modules/lodash/_customOmitClone.js @@ -0,0 +1,16 @@ +var isPlainObject = require('./isPlainObject'); + +/** + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. + * + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ +function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; +} + +module.exports = customOmitClone; diff --git a/node_modules/lodash/_deburrLetter.js b/node_modules/lodash/_deburrLetter.js new file mode 100644 index 0000000..3e531ed --- /dev/null +++ b/node_modules/lodash/_deburrLetter.js @@ -0,0 +1,71 @@ +var basePropertyOf = require('./_basePropertyOf'); + +/** Used to map Latin Unicode letters to basic Latin letters. */ +var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' +}; + +/** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ +var deburrLetter = basePropertyOf(deburredLetters); + +module.exports = deburrLetter; diff --git a/node_modules/lodash/_defineProperty.js b/node_modules/lodash/_defineProperty.js new file mode 100644 index 0000000..b6116d9 --- /dev/null +++ b/node_modules/lodash/_defineProperty.js @@ -0,0 +1,11 @@ +var getNative = require('./_getNative'); + +var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} +}()); + +module.exports = defineProperty; diff --git a/node_modules/lodash/_equalArrays.js b/node_modules/lodash/_equalArrays.js new file mode 100644 index 0000000..824228c --- /dev/null +++ b/node_modules/lodash/_equalArrays.js @@ -0,0 +1,84 @@ +var SetCache = require('./_SetCache'), + arraySome = require('./_arraySome'), + cacheHas = require('./_cacheHas'); + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ +function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; +} + +module.exports = equalArrays; diff --git a/node_modules/lodash/_equalByTag.js b/node_modules/lodash/_equalByTag.js new file mode 100644 index 0000000..71919e8 --- /dev/null +++ b/node_modules/lodash/_equalByTag.js @@ -0,0 +1,112 @@ +var Symbol = require('./_Symbol'), + Uint8Array = require('./_Uint8Array'), + eq = require('./eq'), + equalArrays = require('./_equalArrays'), + mapToArray = require('./_mapToArray'), + setToArray = require('./_setToArray'); + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + mapTag = '[object Map]', + numberTag = '[object Number]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]'; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; +} + +module.exports = equalByTag; diff --git a/node_modules/lodash/_equalObjects.js b/node_modules/lodash/_equalObjects.js new file mode 100644 index 0000000..cdaacd2 --- /dev/null +++ b/node_modules/lodash/_equalObjects.js @@ -0,0 +1,90 @@ +var getAllKeys = require('./_getAllKeys'); + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; +} + +module.exports = equalObjects; diff --git a/node_modules/lodash/_escapeHtmlChar.js b/node_modules/lodash/_escapeHtmlChar.js new file mode 100644 index 0000000..7ca68ee --- /dev/null +++ b/node_modules/lodash/_escapeHtmlChar.js @@ -0,0 +1,21 @@ +var basePropertyOf = require('./_basePropertyOf'); + +/** Used to map characters to HTML entities. */ +var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; + +/** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ +var escapeHtmlChar = basePropertyOf(htmlEscapes); + +module.exports = escapeHtmlChar; diff --git a/node_modules/lodash/_escapeStringChar.js b/node_modules/lodash/_escapeStringChar.js new file mode 100644 index 0000000..44eca96 --- /dev/null +++ b/node_modules/lodash/_escapeStringChar.js @@ -0,0 +1,22 @@ +/** Used to escape characters for inclusion in compiled string literals. */ +var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' +}; + +/** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ +function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; +} + +module.exports = escapeStringChar; diff --git a/node_modules/lodash/_flatRest.js b/node_modules/lodash/_flatRest.js new file mode 100644 index 0000000..94ab6cc --- /dev/null +++ b/node_modules/lodash/_flatRest.js @@ -0,0 +1,16 @@ +var flatten = require('./flatten'), + overRest = require('./_overRest'), + setToString = require('./_setToString'); + +/** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ +function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); +} + +module.exports = flatRest; diff --git a/node_modules/lodash/_freeGlobal.js b/node_modules/lodash/_freeGlobal.js new file mode 100644 index 0000000..bbec998 --- /dev/null +++ b/node_modules/lodash/_freeGlobal.js @@ -0,0 +1,4 @@ +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +module.exports = freeGlobal; diff --git a/node_modules/lodash/_getAllKeys.js b/node_modules/lodash/_getAllKeys.js new file mode 100644 index 0000000..a9ce699 --- /dev/null +++ b/node_modules/lodash/_getAllKeys.js @@ -0,0 +1,16 @@ +var baseGetAllKeys = require('./_baseGetAllKeys'), + getSymbols = require('./_getSymbols'), + keys = require('./keys'); + +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); +} + +module.exports = getAllKeys; diff --git a/node_modules/lodash/_getAllKeysIn.js b/node_modules/lodash/_getAllKeysIn.js new file mode 100644 index 0000000..1b46678 --- /dev/null +++ b/node_modules/lodash/_getAllKeysIn.js @@ -0,0 +1,17 @@ +var baseGetAllKeys = require('./_baseGetAllKeys'), + getSymbolsIn = require('./_getSymbolsIn'), + keysIn = require('./keysIn'); + +/** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); +} + +module.exports = getAllKeysIn; diff --git a/node_modules/lodash/_getData.js b/node_modules/lodash/_getData.js new file mode 100644 index 0000000..a1fe7b7 --- /dev/null +++ b/node_modules/lodash/_getData.js @@ -0,0 +1,15 @@ +var metaMap = require('./_metaMap'), + noop = require('./noop'); + +/** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ +var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); +}; + +module.exports = getData; diff --git a/node_modules/lodash/_getFuncName.js b/node_modules/lodash/_getFuncName.js new file mode 100644 index 0000000..21e15b3 --- /dev/null +++ b/node_modules/lodash/_getFuncName.js @@ -0,0 +1,31 @@ +var realNames = require('./_realNames'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ +function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; +} + +module.exports = getFuncName; diff --git a/node_modules/lodash/_getHolder.js b/node_modules/lodash/_getHolder.js new file mode 100644 index 0000000..65e94b5 --- /dev/null +++ b/node_modules/lodash/_getHolder.js @@ -0,0 +1,13 @@ +/** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ +function getHolder(func) { + var object = func; + return object.placeholder; +} + +module.exports = getHolder; diff --git a/node_modules/lodash/_getMapData.js b/node_modules/lodash/_getMapData.js new file mode 100644 index 0000000..17f6303 --- /dev/null +++ b/node_modules/lodash/_getMapData.js @@ -0,0 +1,18 @@ +var isKeyable = require('./_isKeyable'); + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +module.exports = getMapData; diff --git a/node_modules/lodash/_getMatchData.js b/node_modules/lodash/_getMatchData.js new file mode 100644 index 0000000..2cc70f9 --- /dev/null +++ b/node_modules/lodash/_getMatchData.js @@ -0,0 +1,24 @@ +var isStrictComparable = require('./_isStrictComparable'), + keys = require('./keys'); + +/** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ +function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; +} + +module.exports = getMatchData; diff --git a/node_modules/lodash/_getNative.js b/node_modules/lodash/_getNative.js new file mode 100644 index 0000000..97a622b --- /dev/null +++ b/node_modules/lodash/_getNative.js @@ -0,0 +1,17 @@ +var baseIsNative = require('./_baseIsNative'), + getValue = require('./_getValue'); + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +module.exports = getNative; diff --git a/node_modules/lodash/_getPrototype.js b/node_modules/lodash/_getPrototype.js new file mode 100644 index 0000000..e808612 --- /dev/null +++ b/node_modules/lodash/_getPrototype.js @@ -0,0 +1,6 @@ +var overArg = require('./_overArg'); + +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); + +module.exports = getPrototype; diff --git a/node_modules/lodash/_getRawTag.js b/node_modules/lodash/_getRawTag.js new file mode 100644 index 0000000..49a95c9 --- /dev/null +++ b/node_modules/lodash/_getRawTag.js @@ -0,0 +1,46 @@ +var Symbol = require('./_Symbol'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; +} + +module.exports = getRawTag; diff --git a/node_modules/lodash/_getSymbols.js b/node_modules/lodash/_getSymbols.js new file mode 100644 index 0000000..7d6eafe --- /dev/null +++ b/node_modules/lodash/_getSymbols.js @@ -0,0 +1,30 @@ +var arrayFilter = require('./_arrayFilter'), + stubArray = require('./stubArray'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols; + +/** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); +}; + +module.exports = getSymbols; diff --git a/node_modules/lodash/_getSymbolsIn.js b/node_modules/lodash/_getSymbolsIn.js new file mode 100644 index 0000000..cec0855 --- /dev/null +++ b/node_modules/lodash/_getSymbolsIn.js @@ -0,0 +1,25 @@ +var arrayPush = require('./_arrayPush'), + getPrototype = require('./_getPrototype'), + getSymbols = require('./_getSymbols'), + stubArray = require('./stubArray'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols; + +/** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; +}; + +module.exports = getSymbolsIn; diff --git a/node_modules/lodash/_getTag.js b/node_modules/lodash/_getTag.js new file mode 100644 index 0000000..deaf89d --- /dev/null +++ b/node_modules/lodash/_getTag.js @@ -0,0 +1,58 @@ +var DataView = require('./_DataView'), + Map = require('./_Map'), + Promise = require('./_Promise'), + Set = require('./_Set'), + WeakMap = require('./_WeakMap'), + baseGetTag = require('./_baseGetTag'), + toSource = require('./_toSource'); + +/** `Object#toString` result references. */ +var mapTag = '[object Map]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + setTag = '[object Set]', + weakMapTag = '[object WeakMap]'; + +var dataViewTag = '[object DataView]'; + +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag = baseGetTag; + +// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. +if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; +} + +module.exports = getTag; diff --git a/node_modules/lodash/_getValue.js b/node_modules/lodash/_getValue.js new file mode 100644 index 0000000..5f7d773 --- /dev/null +++ b/node_modules/lodash/_getValue.js @@ -0,0 +1,13 @@ +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +module.exports = getValue; diff --git a/node_modules/lodash/_getView.js b/node_modules/lodash/_getView.js new file mode 100644 index 0000000..df1e5d4 --- /dev/null +++ b/node_modules/lodash/_getView.js @@ -0,0 +1,33 @@ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ +function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; +} + +module.exports = getView; diff --git a/node_modules/lodash/_getWrapDetails.js b/node_modules/lodash/_getWrapDetails.js new file mode 100644 index 0000000..3bcc6e4 --- /dev/null +++ b/node_modules/lodash/_getWrapDetails.js @@ -0,0 +1,17 @@ +/** Used to match wrap detail comments. */ +var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + +/** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ +function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; +} + +module.exports = getWrapDetails; diff --git a/node_modules/lodash/_hasPath.js b/node_modules/lodash/_hasPath.js new file mode 100644 index 0000000..93dbde1 --- /dev/null +++ b/node_modules/lodash/_hasPath.js @@ -0,0 +1,39 @@ +var castPath = require('./_castPath'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isIndex = require('./_isIndex'), + isLength = require('./isLength'), + toKey = require('./_toKey'); + +/** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ +function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); +} + +module.exports = hasPath; diff --git a/node_modules/lodash/_hasUnicode.js b/node_modules/lodash/_hasUnicode.js new file mode 100644 index 0000000..cb6ca15 --- /dev/null +++ b/node_modules/lodash/_hasUnicode.js @@ -0,0 +1,26 @@ +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsVarRange = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsZWJ = '\\u200d'; + +/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ +var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + +/** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ +function hasUnicode(string) { + return reHasUnicode.test(string); +} + +module.exports = hasUnicode; diff --git a/node_modules/lodash/_hasUnicodeWord.js b/node_modules/lodash/_hasUnicodeWord.js new file mode 100644 index 0000000..95d52c4 --- /dev/null +++ b/node_modules/lodash/_hasUnicodeWord.js @@ -0,0 +1,15 @@ +/** Used to detect strings that need a more robust regexp to match words. */ +var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + +/** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ +function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); +} + +module.exports = hasUnicodeWord; diff --git a/node_modules/lodash/_hashClear.js b/node_modules/lodash/_hashClear.js new file mode 100644 index 0000000..5d4b70c --- /dev/null +++ b/node_modules/lodash/_hashClear.js @@ -0,0 +1,15 @@ +var nativeCreate = require('./_nativeCreate'); + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; +} + +module.exports = hashClear; diff --git a/node_modules/lodash/_hashDelete.js b/node_modules/lodash/_hashDelete.js new file mode 100644 index 0000000..ea9dabf --- /dev/null +++ b/node_modules/lodash/_hashDelete.js @@ -0,0 +1,17 @@ +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} + +module.exports = hashDelete; diff --git a/node_modules/lodash/_hashGet.js b/node_modules/lodash/_hashGet.js new file mode 100644 index 0000000..1fc2f34 --- /dev/null +++ b/node_modules/lodash/_hashGet.js @@ -0,0 +1,30 @@ +var nativeCreate = require('./_nativeCreate'); + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} + +module.exports = hashGet; diff --git a/node_modules/lodash/_hashHas.js b/node_modules/lodash/_hashHas.js new file mode 100644 index 0000000..281a551 --- /dev/null +++ b/node_modules/lodash/_hashHas.js @@ -0,0 +1,23 @@ +var nativeCreate = require('./_nativeCreate'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); +} + +module.exports = hashHas; diff --git a/node_modules/lodash/_hashSet.js b/node_modules/lodash/_hashSet.js new file mode 100644 index 0000000..e105528 --- /dev/null +++ b/node_modules/lodash/_hashSet.js @@ -0,0 +1,23 @@ +var nativeCreate = require('./_nativeCreate'); + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} + +module.exports = hashSet; diff --git a/node_modules/lodash/_initCloneArray.js b/node_modules/lodash/_initCloneArray.js new file mode 100644 index 0000000..078c15a --- /dev/null +++ b/node_modules/lodash/_initCloneArray.js @@ -0,0 +1,26 @@ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ +function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; +} + +module.exports = initCloneArray; diff --git a/node_modules/lodash/_initCloneByTag.js b/node_modules/lodash/_initCloneByTag.js new file mode 100644 index 0000000..f69a008 --- /dev/null +++ b/node_modules/lodash/_initCloneByTag.js @@ -0,0 +1,77 @@ +var cloneArrayBuffer = require('./_cloneArrayBuffer'), + cloneDataView = require('./_cloneDataView'), + cloneRegExp = require('./_cloneRegExp'), + cloneSymbol = require('./_cloneSymbol'), + cloneTypedArray = require('./_cloneTypedArray'); + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]', + dateTag = '[object Date]', + mapTag = '[object Map]', + numberTag = '[object Number]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return new Ctor; + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return new Ctor; + + case symbolTag: + return cloneSymbol(object); + } +} + +module.exports = initCloneByTag; diff --git a/node_modules/lodash/_initCloneObject.js b/node_modules/lodash/_initCloneObject.js new file mode 100644 index 0000000..5a13e64 --- /dev/null +++ b/node_modules/lodash/_initCloneObject.js @@ -0,0 +1,18 @@ +var baseCreate = require('./_baseCreate'), + getPrototype = require('./_getPrototype'), + isPrototype = require('./_isPrototype'); + +/** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; +} + +module.exports = initCloneObject; diff --git a/node_modules/lodash/_insertWrapDetails.js b/node_modules/lodash/_insertWrapDetails.js new file mode 100644 index 0000000..e790808 --- /dev/null +++ b/node_modules/lodash/_insertWrapDetails.js @@ -0,0 +1,23 @@ +/** Used to match wrap detail comments. */ +var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; + +/** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ +function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); +} + +module.exports = insertWrapDetails; diff --git a/node_modules/lodash/_isFlattenable.js b/node_modules/lodash/_isFlattenable.js new file mode 100644 index 0000000..4cc2c24 --- /dev/null +++ b/node_modules/lodash/_isFlattenable.js @@ -0,0 +1,20 @@ +var Symbol = require('./_Symbol'), + isArguments = require('./isArguments'), + isArray = require('./isArray'); + +/** Built-in value references. */ +var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); +} + +module.exports = isFlattenable; diff --git a/node_modules/lodash/_isIndex.js b/node_modules/lodash/_isIndex.js new file mode 100644 index 0000000..061cd39 --- /dev/null +++ b/node_modules/lodash/_isIndex.js @@ -0,0 +1,25 @@ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); +} + +module.exports = isIndex; diff --git a/node_modules/lodash/_isIterateeCall.js b/node_modules/lodash/_isIterateeCall.js new file mode 100644 index 0000000..a0bb5a9 --- /dev/null +++ b/node_modules/lodash/_isIterateeCall.js @@ -0,0 +1,30 @@ +var eq = require('./eq'), + isArrayLike = require('./isArrayLike'), + isIndex = require('./_isIndex'), + isObject = require('./isObject'); + +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; +} + +module.exports = isIterateeCall; diff --git a/node_modules/lodash/_isKey.js b/node_modules/lodash/_isKey.js new file mode 100644 index 0000000..ff08b06 --- /dev/null +++ b/node_modules/lodash/_isKey.js @@ -0,0 +1,29 @@ +var isArray = require('./isArray'), + isSymbol = require('./isSymbol'); + +/** Used to match property names within property paths. */ +var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; + +/** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ +function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +} + +module.exports = isKey; diff --git a/node_modules/lodash/_isKeyable.js b/node_modules/lodash/_isKeyable.js new file mode 100644 index 0000000..39f1828 --- /dev/null +++ b/node_modules/lodash/_isKeyable.js @@ -0,0 +1,15 @@ +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +module.exports = isKeyable; diff --git a/node_modules/lodash/_isLaziable.js b/node_modules/lodash/_isLaziable.js new file mode 100644 index 0000000..a57c4f2 --- /dev/null +++ b/node_modules/lodash/_isLaziable.js @@ -0,0 +1,28 @@ +var LazyWrapper = require('./_LazyWrapper'), + getData = require('./_getData'), + getFuncName = require('./_getFuncName'), + lodash = require('./wrapperLodash'); + +/** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ +function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; +} + +module.exports = isLaziable; diff --git a/node_modules/lodash/_isMaskable.js b/node_modules/lodash/_isMaskable.js new file mode 100644 index 0000000..eb98d09 --- /dev/null +++ b/node_modules/lodash/_isMaskable.js @@ -0,0 +1,14 @@ +var coreJsData = require('./_coreJsData'), + isFunction = require('./isFunction'), + stubFalse = require('./stubFalse'); + +/** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ +var isMaskable = coreJsData ? isFunction : stubFalse; + +module.exports = isMaskable; diff --git a/node_modules/lodash/_isMasked.js b/node_modules/lodash/_isMasked.js new file mode 100644 index 0000000..4b0f21b --- /dev/null +++ b/node_modules/lodash/_isMasked.js @@ -0,0 +1,20 @@ +var coreJsData = require('./_coreJsData'); + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +module.exports = isMasked; diff --git a/node_modules/lodash/_isPrototype.js b/node_modules/lodash/_isPrototype.js new file mode 100644 index 0000000..0f29498 --- /dev/null +++ b/node_modules/lodash/_isPrototype.js @@ -0,0 +1,18 @@ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +module.exports = isPrototype; diff --git a/node_modules/lodash/_isStrictComparable.js b/node_modules/lodash/_isStrictComparable.js new file mode 100644 index 0000000..b59f40b --- /dev/null +++ b/node_modules/lodash/_isStrictComparable.js @@ -0,0 +1,15 @@ +var isObject = require('./isObject'); + +/** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ +function isStrictComparable(value) { + return value === value && !isObject(value); +} + +module.exports = isStrictComparable; diff --git a/node_modules/lodash/_iteratorToArray.js b/node_modules/lodash/_iteratorToArray.js new file mode 100644 index 0000000..4768566 --- /dev/null +++ b/node_modules/lodash/_iteratorToArray.js @@ -0,0 +1,18 @@ +/** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ +function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; +} + +module.exports = iteratorToArray; diff --git a/node_modules/lodash/_lazyClone.js b/node_modules/lodash/_lazyClone.js new file mode 100644 index 0000000..d8a51f8 --- /dev/null +++ b/node_modules/lodash/_lazyClone.js @@ -0,0 +1,23 @@ +var LazyWrapper = require('./_LazyWrapper'), + copyArray = require('./_copyArray'); + +/** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ +function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; +} + +module.exports = lazyClone; diff --git a/node_modules/lodash/_lazyReverse.js b/node_modules/lodash/_lazyReverse.js new file mode 100644 index 0000000..c5b5219 --- /dev/null +++ b/node_modules/lodash/_lazyReverse.js @@ -0,0 +1,23 @@ +var LazyWrapper = require('./_LazyWrapper'); + +/** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ +function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; +} + +module.exports = lazyReverse; diff --git a/node_modules/lodash/_lazyValue.js b/node_modules/lodash/_lazyValue.js new file mode 100644 index 0000000..371ca8d --- /dev/null +++ b/node_modules/lodash/_lazyValue.js @@ -0,0 +1,69 @@ +var baseWrapperValue = require('./_baseWrapperValue'), + getView = require('./_getView'), + isArray = require('./isArray'); + +/** Used to indicate the type of lazy iteratees. */ +var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin = Math.min; + +/** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ +function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; +} + +module.exports = lazyValue; diff --git a/node_modules/lodash/_listCacheClear.js b/node_modules/lodash/_listCacheClear.js new file mode 100644 index 0000000..acbe39a --- /dev/null +++ b/node_modules/lodash/_listCacheClear.js @@ -0,0 +1,13 @@ +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} + +module.exports = listCacheClear; diff --git a/node_modules/lodash/_listCacheDelete.js b/node_modules/lodash/_listCacheDelete.js new file mode 100644 index 0000000..b1384ad --- /dev/null +++ b/node_modules/lodash/_listCacheDelete.js @@ -0,0 +1,35 @@ +var assocIndexOf = require('./_assocIndexOf'); + +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/** Built-in value references. */ +var splice = arrayProto.splice; + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; +} + +module.exports = listCacheDelete; diff --git a/node_modules/lodash/_listCacheGet.js b/node_modules/lodash/_listCacheGet.js new file mode 100644 index 0000000..f8192fc --- /dev/null +++ b/node_modules/lodash/_listCacheGet.js @@ -0,0 +1,19 @@ +var assocIndexOf = require('./_assocIndexOf'); + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +module.exports = listCacheGet; diff --git a/node_modules/lodash/_listCacheHas.js b/node_modules/lodash/_listCacheHas.js new file mode 100644 index 0000000..2adf671 --- /dev/null +++ b/node_modules/lodash/_listCacheHas.js @@ -0,0 +1,16 @@ +var assocIndexOf = require('./_assocIndexOf'); + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} + +module.exports = listCacheHas; diff --git a/node_modules/lodash/_listCacheSet.js b/node_modules/lodash/_listCacheSet.js new file mode 100644 index 0000000..5855c95 --- /dev/null +++ b/node_modules/lodash/_listCacheSet.js @@ -0,0 +1,26 @@ +var assocIndexOf = require('./_assocIndexOf'); + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +module.exports = listCacheSet; diff --git a/node_modules/lodash/_mapCacheClear.js b/node_modules/lodash/_mapCacheClear.js new file mode 100644 index 0000000..bc9ca20 --- /dev/null +++ b/node_modules/lodash/_mapCacheClear.js @@ -0,0 +1,21 @@ +var Hash = require('./_Hash'), + ListCache = require('./_ListCache'), + Map = require('./_Map'); + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; +} + +module.exports = mapCacheClear; diff --git a/node_modules/lodash/_mapCacheDelete.js b/node_modules/lodash/_mapCacheDelete.js new file mode 100644 index 0000000..946ca3c --- /dev/null +++ b/node_modules/lodash/_mapCacheDelete.js @@ -0,0 +1,18 @@ +var getMapData = require('./_getMapData'); + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} + +module.exports = mapCacheDelete; diff --git a/node_modules/lodash/_mapCacheGet.js b/node_modules/lodash/_mapCacheGet.js new file mode 100644 index 0000000..f29f55c --- /dev/null +++ b/node_modules/lodash/_mapCacheGet.js @@ -0,0 +1,16 @@ +var getMapData = require('./_getMapData'); + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +module.exports = mapCacheGet; diff --git a/node_modules/lodash/_mapCacheHas.js b/node_modules/lodash/_mapCacheHas.js new file mode 100644 index 0000000..a1214c0 --- /dev/null +++ b/node_modules/lodash/_mapCacheHas.js @@ -0,0 +1,16 @@ +var getMapData = require('./_getMapData'); + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +module.exports = mapCacheHas; diff --git a/node_modules/lodash/_mapCacheSet.js b/node_modules/lodash/_mapCacheSet.js new file mode 100644 index 0000000..7346849 --- /dev/null +++ b/node_modules/lodash/_mapCacheSet.js @@ -0,0 +1,22 @@ +var getMapData = require('./_getMapData'); + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} + +module.exports = mapCacheSet; diff --git a/node_modules/lodash/_mapToArray.js b/node_modules/lodash/_mapToArray.js new file mode 100644 index 0000000..fe3dd53 --- /dev/null +++ b/node_modules/lodash/_mapToArray.js @@ -0,0 +1,18 @@ +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} + +module.exports = mapToArray; diff --git a/node_modules/lodash/_matchesStrictComparable.js b/node_modules/lodash/_matchesStrictComparable.js new file mode 100644 index 0000000..f608af9 --- /dev/null +++ b/node_modules/lodash/_matchesStrictComparable.js @@ -0,0 +1,20 @@ +/** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; +} + +module.exports = matchesStrictComparable; diff --git a/node_modules/lodash/_memoizeCapped.js b/node_modules/lodash/_memoizeCapped.js new file mode 100644 index 0000000..7f71c8f --- /dev/null +++ b/node_modules/lodash/_memoizeCapped.js @@ -0,0 +1,26 @@ +var memoize = require('./memoize'); + +/** Used as the maximum memoize cache size. */ +var MAX_MEMOIZE_SIZE = 500; + +/** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ +function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; +} + +module.exports = memoizeCapped; diff --git a/node_modules/lodash/_mergeData.js b/node_modules/lodash/_mergeData.js new file mode 100644 index 0000000..cb570f9 --- /dev/null +++ b/node_modules/lodash/_mergeData.js @@ -0,0 +1,90 @@ +var composeArgs = require('./_composeArgs'), + composeArgsRight = require('./_composeArgsRight'), + replaceHolders = require('./_replaceHolders'); + +/** Used as the internal argument placeholder. */ +var PLACEHOLDER = '__lodash_placeholder__'; + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin = Math.min; + +/** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ +function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; +} + +module.exports = mergeData; diff --git a/node_modules/lodash/_metaMap.js b/node_modules/lodash/_metaMap.js new file mode 100644 index 0000000..0157a0b --- /dev/null +++ b/node_modules/lodash/_metaMap.js @@ -0,0 +1,6 @@ +var WeakMap = require('./_WeakMap'); + +/** Used to store function metadata. */ +var metaMap = WeakMap && new WeakMap; + +module.exports = metaMap; diff --git a/node_modules/lodash/_nativeCreate.js b/node_modules/lodash/_nativeCreate.js new file mode 100644 index 0000000..c7aede8 --- /dev/null +++ b/node_modules/lodash/_nativeCreate.js @@ -0,0 +1,6 @@ +var getNative = require('./_getNative'); + +/* Built-in method references that are verified to be native. */ +var nativeCreate = getNative(Object, 'create'); + +module.exports = nativeCreate; diff --git a/node_modules/lodash/_nativeKeys.js b/node_modules/lodash/_nativeKeys.js new file mode 100644 index 0000000..479a104 --- /dev/null +++ b/node_modules/lodash/_nativeKeys.js @@ -0,0 +1,6 @@ +var overArg = require('./_overArg'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object); + +module.exports = nativeKeys; diff --git a/node_modules/lodash/_nativeKeysIn.js b/node_modules/lodash/_nativeKeysIn.js new file mode 100644 index 0000000..00ee505 --- /dev/null +++ b/node_modules/lodash/_nativeKeysIn.js @@ -0,0 +1,20 @@ +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; +} + +module.exports = nativeKeysIn; diff --git a/node_modules/lodash/_nodeUtil.js b/node_modules/lodash/_nodeUtil.js new file mode 100644 index 0000000..983d78f --- /dev/null +++ b/node_modules/lodash/_nodeUtil.js @@ -0,0 +1,30 @@ +var freeGlobal = require('./_freeGlobal'); + +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports && freeGlobal.process; + +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); + +module.exports = nodeUtil; diff --git a/node_modules/lodash/_objectToString.js b/node_modules/lodash/_objectToString.js new file mode 100644 index 0000000..c614ec0 --- /dev/null +++ b/node_modules/lodash/_objectToString.js @@ -0,0 +1,22 @@ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString.call(value); +} + +module.exports = objectToString; diff --git a/node_modules/lodash/_overArg.js b/node_modules/lodash/_overArg.js new file mode 100644 index 0000000..651c5c5 --- /dev/null +++ b/node_modules/lodash/_overArg.js @@ -0,0 +1,15 @@ +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +module.exports = overArg; diff --git a/node_modules/lodash/_overRest.js b/node_modules/lodash/_overRest.js new file mode 100644 index 0000000..c7cdef3 --- /dev/null +++ b/node_modules/lodash/_overRest.js @@ -0,0 +1,36 @@ +var apply = require('./_apply'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ +function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; +} + +module.exports = overRest; diff --git a/node_modules/lodash/_parent.js b/node_modules/lodash/_parent.js new file mode 100644 index 0000000..f174328 --- /dev/null +++ b/node_modules/lodash/_parent.js @@ -0,0 +1,16 @@ +var baseGet = require('./_baseGet'), + baseSlice = require('./_baseSlice'); + +/** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ +function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); +} + +module.exports = parent; diff --git a/node_modules/lodash/_reEscape.js b/node_modules/lodash/_reEscape.js new file mode 100644 index 0000000..7f47eda --- /dev/null +++ b/node_modules/lodash/_reEscape.js @@ -0,0 +1,4 @@ +/** Used to match template delimiters. */ +var reEscape = /<%-([\s\S]+?)%>/g; + +module.exports = reEscape; diff --git a/node_modules/lodash/_reEvaluate.js b/node_modules/lodash/_reEvaluate.js new file mode 100644 index 0000000..6adfc31 --- /dev/null +++ b/node_modules/lodash/_reEvaluate.js @@ -0,0 +1,4 @@ +/** Used to match template delimiters. */ +var reEvaluate = /<%([\s\S]+?)%>/g; + +module.exports = reEvaluate; diff --git a/node_modules/lodash/_reInterpolate.js b/node_modules/lodash/_reInterpolate.js new file mode 100644 index 0000000..d02ff0b --- /dev/null +++ b/node_modules/lodash/_reInterpolate.js @@ -0,0 +1,4 @@ +/** Used to match template delimiters. */ +var reInterpolate = /<%=([\s\S]+?)%>/g; + +module.exports = reInterpolate; diff --git a/node_modules/lodash/_realNames.js b/node_modules/lodash/_realNames.js new file mode 100644 index 0000000..aa0d529 --- /dev/null +++ b/node_modules/lodash/_realNames.js @@ -0,0 +1,4 @@ +/** Used to lookup unminified function names. */ +var realNames = {}; + +module.exports = realNames; diff --git a/node_modules/lodash/_reorder.js b/node_modules/lodash/_reorder.js new file mode 100644 index 0000000..a3502b0 --- /dev/null +++ b/node_modules/lodash/_reorder.js @@ -0,0 +1,29 @@ +var copyArray = require('./_copyArray'), + isIndex = require('./_isIndex'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin = Math.min; + +/** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ +function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; +} + +module.exports = reorder; diff --git a/node_modules/lodash/_replaceHolders.js b/node_modules/lodash/_replaceHolders.js new file mode 100644 index 0000000..74360ec --- /dev/null +++ b/node_modules/lodash/_replaceHolders.js @@ -0,0 +1,29 @@ +/** Used as the internal argument placeholder. */ +var PLACEHOLDER = '__lodash_placeholder__'; + +/** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ +function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; +} + +module.exports = replaceHolders; diff --git a/node_modules/lodash/_root.js b/node_modules/lodash/_root.js new file mode 100644 index 0000000..d2852be --- /dev/null +++ b/node_modules/lodash/_root.js @@ -0,0 +1,9 @@ +var freeGlobal = require('./_freeGlobal'); + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +module.exports = root; diff --git a/node_modules/lodash/_safeGet.js b/node_modules/lodash/_safeGet.js new file mode 100644 index 0000000..b070897 --- /dev/null +++ b/node_modules/lodash/_safeGet.js @@ -0,0 +1,21 @@ +/** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; +} + +module.exports = safeGet; diff --git a/node_modules/lodash/_setCacheAdd.js b/node_modules/lodash/_setCacheAdd.js new file mode 100644 index 0000000..1081a74 --- /dev/null +++ b/node_modules/lodash/_setCacheAdd.js @@ -0,0 +1,19 @@ +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} + +module.exports = setCacheAdd; diff --git a/node_modules/lodash/_setCacheHas.js b/node_modules/lodash/_setCacheHas.js new file mode 100644 index 0000000..2062af8 --- /dev/null +++ b/node_modules/lodash/_setCacheHas.js @@ -0,0 +1,14 @@ +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} + +module.exports = setCacheHas; diff --git a/node_modules/lodash/_setData.js b/node_modules/lodash/_setData.js new file mode 100644 index 0000000..e5cf3eb --- /dev/null +++ b/node_modules/lodash/_setData.js @@ -0,0 +1,20 @@ +var baseSetData = require('./_baseSetData'), + shortOut = require('./_shortOut'); + +/** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ +var setData = shortOut(baseSetData); + +module.exports = setData; diff --git a/node_modules/lodash/_setToArray.js b/node_modules/lodash/_setToArray.js new file mode 100644 index 0000000..b87f074 --- /dev/null +++ b/node_modules/lodash/_setToArray.js @@ -0,0 +1,18 @@ +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} + +module.exports = setToArray; diff --git a/node_modules/lodash/_setToPairs.js b/node_modules/lodash/_setToPairs.js new file mode 100644 index 0000000..36ad37a --- /dev/null +++ b/node_modules/lodash/_setToPairs.js @@ -0,0 +1,18 @@ +/** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ +function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; +} + +module.exports = setToPairs; diff --git a/node_modules/lodash/_setToString.js b/node_modules/lodash/_setToString.js new file mode 100644 index 0000000..6ca8419 --- /dev/null +++ b/node_modules/lodash/_setToString.js @@ -0,0 +1,14 @@ +var baseSetToString = require('./_baseSetToString'), + shortOut = require('./_shortOut'); + +/** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var setToString = shortOut(baseSetToString); + +module.exports = setToString; diff --git a/node_modules/lodash/_setWrapToString.js b/node_modules/lodash/_setWrapToString.js new file mode 100644 index 0000000..decdc44 --- /dev/null +++ b/node_modules/lodash/_setWrapToString.js @@ -0,0 +1,21 @@ +var getWrapDetails = require('./_getWrapDetails'), + insertWrapDetails = require('./_insertWrapDetails'), + setToString = require('./_setToString'), + updateWrapDetails = require('./_updateWrapDetails'); + +/** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ +function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); +} + +module.exports = setWrapToString; diff --git a/node_modules/lodash/_shortOut.js b/node_modules/lodash/_shortOut.js new file mode 100644 index 0000000..3300a07 --- /dev/null +++ b/node_modules/lodash/_shortOut.js @@ -0,0 +1,37 @@ +/** Used to detect hot functions by number of calls within a span of milliseconds. */ +var HOT_COUNT = 800, + HOT_SPAN = 16; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeNow = Date.now; + +/** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ +function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; +} + +module.exports = shortOut; diff --git a/node_modules/lodash/_shuffleSelf.js b/node_modules/lodash/_shuffleSelf.js new file mode 100644 index 0000000..8bcc4f5 --- /dev/null +++ b/node_modules/lodash/_shuffleSelf.js @@ -0,0 +1,28 @@ +var baseRandom = require('./_baseRandom'); + +/** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */ +function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; +} + +module.exports = shuffleSelf; diff --git a/node_modules/lodash/_stackClear.js b/node_modules/lodash/_stackClear.js new file mode 100644 index 0000000..ce8e5a9 --- /dev/null +++ b/node_modules/lodash/_stackClear.js @@ -0,0 +1,15 @@ +var ListCache = require('./_ListCache'); + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; + this.size = 0; +} + +module.exports = stackClear; diff --git a/node_modules/lodash/_stackDelete.js b/node_modules/lodash/_stackDelete.js new file mode 100644 index 0000000..ff9887a --- /dev/null +++ b/node_modules/lodash/_stackDelete.js @@ -0,0 +1,18 @@ +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; +} + +module.exports = stackDelete; diff --git a/node_modules/lodash/_stackGet.js b/node_modules/lodash/_stackGet.js new file mode 100644 index 0000000..1cdf004 --- /dev/null +++ b/node_modules/lodash/_stackGet.js @@ -0,0 +1,14 @@ +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +module.exports = stackGet; diff --git a/node_modules/lodash/_stackHas.js b/node_modules/lodash/_stackHas.js new file mode 100644 index 0000000..16a3ad1 --- /dev/null +++ b/node_modules/lodash/_stackHas.js @@ -0,0 +1,14 @@ +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +module.exports = stackHas; diff --git a/node_modules/lodash/_stackSet.js b/node_modules/lodash/_stackSet.js new file mode 100644 index 0000000..b790ac5 --- /dev/null +++ b/node_modules/lodash/_stackSet.js @@ -0,0 +1,34 @@ +var ListCache = require('./_ListCache'), + Map = require('./_Map'), + MapCache = require('./_MapCache'); + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; +} + +module.exports = stackSet; diff --git a/node_modules/lodash/_strictIndexOf.js b/node_modules/lodash/_strictIndexOf.js new file mode 100644 index 0000000..0486a49 --- /dev/null +++ b/node_modules/lodash/_strictIndexOf.js @@ -0,0 +1,23 @@ +/** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +module.exports = strictIndexOf; diff --git a/node_modules/lodash/_strictLastIndexOf.js b/node_modules/lodash/_strictLastIndexOf.js new file mode 100644 index 0000000..d7310dc --- /dev/null +++ b/node_modules/lodash/_strictLastIndexOf.js @@ -0,0 +1,21 @@ +/** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; +} + +module.exports = strictLastIndexOf; diff --git a/node_modules/lodash/_stringSize.js b/node_modules/lodash/_stringSize.js new file mode 100644 index 0000000..17ef462 --- /dev/null +++ b/node_modules/lodash/_stringSize.js @@ -0,0 +1,18 @@ +var asciiSize = require('./_asciiSize'), + hasUnicode = require('./_hasUnicode'), + unicodeSize = require('./_unicodeSize'); + +/** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ +function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); +} + +module.exports = stringSize; diff --git a/node_modules/lodash/_stringToArray.js b/node_modules/lodash/_stringToArray.js new file mode 100644 index 0000000..d161158 --- /dev/null +++ b/node_modules/lodash/_stringToArray.js @@ -0,0 +1,18 @@ +var asciiToArray = require('./_asciiToArray'), + hasUnicode = require('./_hasUnicode'), + unicodeToArray = require('./_unicodeToArray'); + +/** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); +} + +module.exports = stringToArray; diff --git a/node_modules/lodash/_stringToPath.js b/node_modules/lodash/_stringToPath.js new file mode 100644 index 0000000..8f39f8a --- /dev/null +++ b/node_modules/lodash/_stringToPath.js @@ -0,0 +1,27 @@ +var memoizeCapped = require('./_memoizeCapped'); + +/** Used to match property names within property paths. */ +var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + +/** Used to match backslashes in property paths. */ +var reEscapeChar = /\\(\\)?/g; + +/** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ +var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; +}); + +module.exports = stringToPath; diff --git a/node_modules/lodash/_toKey.js b/node_modules/lodash/_toKey.js new file mode 100644 index 0000000..c6d645c --- /dev/null +++ b/node_modules/lodash/_toKey.js @@ -0,0 +1,21 @@ +var isSymbol = require('./isSymbol'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ +function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +module.exports = toKey; diff --git a/node_modules/lodash/_toSource.js b/node_modules/lodash/_toSource.js new file mode 100644 index 0000000..a020b38 --- /dev/null +++ b/node_modules/lodash/_toSource.js @@ -0,0 +1,26 @@ +/** Used for built-in method references. */ +var funcProto = Function.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +module.exports = toSource; diff --git a/node_modules/lodash/_trimmedEndIndex.js b/node_modules/lodash/_trimmedEndIndex.js new file mode 100644 index 0000000..139439a --- /dev/null +++ b/node_modules/lodash/_trimmedEndIndex.js @@ -0,0 +1,19 @@ +/** Used to match a single whitespace character. */ +var reWhitespace = /\s/; + +/** + * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the last non-whitespace character. + */ +function trimmedEndIndex(string) { + var index = string.length; + + while (index-- && reWhitespace.test(string.charAt(index))) {} + return index; +} + +module.exports = trimmedEndIndex; diff --git a/node_modules/lodash/_unescapeHtmlChar.js b/node_modules/lodash/_unescapeHtmlChar.js new file mode 100644 index 0000000..a71fecb --- /dev/null +++ b/node_modules/lodash/_unescapeHtmlChar.js @@ -0,0 +1,21 @@ +var basePropertyOf = require('./_basePropertyOf'); + +/** Used to map HTML entities to characters. */ +var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" +}; + +/** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ +var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + +module.exports = unescapeHtmlChar; diff --git a/node_modules/lodash/_unicodeSize.js b/node_modules/lodash/_unicodeSize.js new file mode 100644 index 0000000..68137ec --- /dev/null +++ b/node_modules/lodash/_unicodeSize.js @@ -0,0 +1,44 @@ +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsVarRange = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsAstral = '[' + rsAstralRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsZWJ = '\\u200d'; + +/** Used to compose unicode regexes. */ +var reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + +/** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ +function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; +} + +module.exports = unicodeSize; diff --git a/node_modules/lodash/_unicodeToArray.js b/node_modules/lodash/_unicodeToArray.js new file mode 100644 index 0000000..2a725c0 --- /dev/null +++ b/node_modules/lodash/_unicodeToArray.js @@ -0,0 +1,40 @@ +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsVarRange = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsAstral = '[' + rsAstralRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsZWJ = '\\u200d'; + +/** Used to compose unicode regexes. */ +var reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + +/** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function unicodeToArray(string) { + return string.match(reUnicode) || []; +} + +module.exports = unicodeToArray; diff --git a/node_modules/lodash/_unicodeWords.js b/node_modules/lodash/_unicodeWords.js new file mode 100644 index 0000000..e72e6e0 --- /dev/null +++ b/node_modules/lodash/_unicodeWords.js @@ -0,0 +1,69 @@ +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + +/** Used to compose unicode capture groups. */ +var rsApos = "['\u2019]", + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + +/** Used to compose unicode regexes. */ +var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq; + +/** Used to match complex or compound words. */ +var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji +].join('|'), 'g'); + +/** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function unicodeWords(string) { + return string.match(reUnicodeWord) || []; +} + +module.exports = unicodeWords; diff --git a/node_modules/lodash/_updateWrapDetails.js b/node_modules/lodash/_updateWrapDetails.js new file mode 100644 index 0000000..8759fbd --- /dev/null +++ b/node_modules/lodash/_updateWrapDetails.js @@ -0,0 +1,46 @@ +var arrayEach = require('./_arrayEach'), + arrayIncludes = require('./_arrayIncludes'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; + +/** Used to associate wrap methods with their bit flags. */ +var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] +]; + +/** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ +function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); +} + +module.exports = updateWrapDetails; diff --git a/node_modules/lodash/_wrapperClone.js b/node_modules/lodash/_wrapperClone.js new file mode 100644 index 0000000..7bb58a2 --- /dev/null +++ b/node_modules/lodash/_wrapperClone.js @@ -0,0 +1,23 @@ +var LazyWrapper = require('./_LazyWrapper'), + LodashWrapper = require('./_LodashWrapper'), + copyArray = require('./_copyArray'); + +/** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ +function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; +} + +module.exports = wrapperClone; diff --git a/node_modules/lodash/add.js b/node_modules/lodash/add.js new file mode 100644 index 0000000..f069515 --- /dev/null +++ b/node_modules/lodash/add.js @@ -0,0 +1,22 @@ +var createMathOperation = require('./_createMathOperation'); + +/** + * Adds two numbers. + * + * @static + * @memberOf _ + * @since 3.4.0 + * @category Math + * @param {number} augend The first number in an addition. + * @param {number} addend The second number in an addition. + * @returns {number} Returns the total. + * @example + * + * _.add(6, 4); + * // => 10 + */ +var add = createMathOperation(function(augend, addend) { + return augend + addend; +}, 0); + +module.exports = add; diff --git a/node_modules/lodash/after.js b/node_modules/lodash/after.js new file mode 100644 index 0000000..3900c97 --- /dev/null +++ b/node_modules/lodash/after.js @@ -0,0 +1,42 @@ +var toInteger = require('./toInteger'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ +function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; +} + +module.exports = after; diff --git a/node_modules/lodash/array.js b/node_modules/lodash/array.js new file mode 100644 index 0000000..af688d3 --- /dev/null +++ b/node_modules/lodash/array.js @@ -0,0 +1,67 @@ +module.exports = { + 'chunk': require('./chunk'), + 'compact': require('./compact'), + 'concat': require('./concat'), + 'difference': require('./difference'), + 'differenceBy': require('./differenceBy'), + 'differenceWith': require('./differenceWith'), + 'drop': require('./drop'), + 'dropRight': require('./dropRight'), + 'dropRightWhile': require('./dropRightWhile'), + 'dropWhile': require('./dropWhile'), + 'fill': require('./fill'), + 'findIndex': require('./findIndex'), + 'findLastIndex': require('./findLastIndex'), + 'first': require('./first'), + 'flatten': require('./flatten'), + 'flattenDeep': require('./flattenDeep'), + 'flattenDepth': require('./flattenDepth'), + 'fromPairs': require('./fromPairs'), + 'head': require('./head'), + 'indexOf': require('./indexOf'), + 'initial': require('./initial'), + 'intersection': require('./intersection'), + 'intersectionBy': require('./intersectionBy'), + 'intersectionWith': require('./intersectionWith'), + 'join': require('./join'), + 'last': require('./last'), + 'lastIndexOf': require('./lastIndexOf'), + 'nth': require('./nth'), + 'pull': require('./pull'), + 'pullAll': require('./pullAll'), + 'pullAllBy': require('./pullAllBy'), + 'pullAllWith': require('./pullAllWith'), + 'pullAt': require('./pullAt'), + 'remove': require('./remove'), + 'reverse': require('./reverse'), + 'slice': require('./slice'), + 'sortedIndex': require('./sortedIndex'), + 'sortedIndexBy': require('./sortedIndexBy'), + 'sortedIndexOf': require('./sortedIndexOf'), + 'sortedLastIndex': require('./sortedLastIndex'), + 'sortedLastIndexBy': require('./sortedLastIndexBy'), + 'sortedLastIndexOf': require('./sortedLastIndexOf'), + 'sortedUniq': require('./sortedUniq'), + 'sortedUniqBy': require('./sortedUniqBy'), + 'tail': require('./tail'), + 'take': require('./take'), + 'takeRight': require('./takeRight'), + 'takeRightWhile': require('./takeRightWhile'), + 'takeWhile': require('./takeWhile'), + 'union': require('./union'), + 'unionBy': require('./unionBy'), + 'unionWith': require('./unionWith'), + 'uniq': require('./uniq'), + 'uniqBy': require('./uniqBy'), + 'uniqWith': require('./uniqWith'), + 'unzip': require('./unzip'), + 'unzipWith': require('./unzipWith'), + 'without': require('./without'), + 'xor': require('./xor'), + 'xorBy': require('./xorBy'), + 'xorWith': require('./xorWith'), + 'zip': require('./zip'), + 'zipObject': require('./zipObject'), + 'zipObjectDeep': require('./zipObjectDeep'), + 'zipWith': require('./zipWith') +}; diff --git a/node_modules/lodash/ary.js b/node_modules/lodash/ary.js new file mode 100644 index 0000000..70c87d0 --- /dev/null +++ b/node_modules/lodash/ary.js @@ -0,0 +1,29 @@ +var createWrap = require('./_createWrap'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_ARY_FLAG = 128; + +/** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ +function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); +} + +module.exports = ary; diff --git a/node_modules/lodash/assign.js b/node_modules/lodash/assign.js new file mode 100644 index 0000000..909db26 --- /dev/null +++ b/node_modules/lodash/assign.js @@ -0,0 +1,58 @@ +var assignValue = require('./_assignValue'), + copyObject = require('./_copyObject'), + createAssigner = require('./_createAssigner'), + isArrayLike = require('./isArrayLike'), + isPrototype = require('./_isPrototype'), + keys = require('./keys'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ +var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } +}); + +module.exports = assign; diff --git a/node_modules/lodash/assignIn.js b/node_modules/lodash/assignIn.js new file mode 100644 index 0000000..e663473 --- /dev/null +++ b/node_modules/lodash/assignIn.js @@ -0,0 +1,40 @@ +var copyObject = require('./_copyObject'), + createAssigner = require('./_createAssigner'), + keysIn = require('./keysIn'); + +/** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ +var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); +}); + +module.exports = assignIn; diff --git a/node_modules/lodash/assignInWith.js b/node_modules/lodash/assignInWith.js new file mode 100644 index 0000000..68fcc0b --- /dev/null +++ b/node_modules/lodash/assignInWith.js @@ -0,0 +1,38 @@ +var copyObject = require('./_copyObject'), + createAssigner = require('./_createAssigner'), + keysIn = require('./keysIn'); + +/** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); +}); + +module.exports = assignInWith; diff --git a/node_modules/lodash/assignWith.js b/node_modules/lodash/assignWith.js new file mode 100644 index 0000000..7dc6c76 --- /dev/null +++ b/node_modules/lodash/assignWith.js @@ -0,0 +1,37 @@ +var copyObject = require('./_copyObject'), + createAssigner = require('./_createAssigner'), + keys = require('./keys'); + +/** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); +}); + +module.exports = assignWith; diff --git a/node_modules/lodash/at.js b/node_modules/lodash/at.js new file mode 100644 index 0000000..781ee9e --- /dev/null +++ b/node_modules/lodash/at.js @@ -0,0 +1,23 @@ +var baseAt = require('./_baseAt'), + flatRest = require('./_flatRest'); + +/** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ +var at = flatRest(baseAt); + +module.exports = at; diff --git a/node_modules/lodash/attempt.js b/node_modules/lodash/attempt.js new file mode 100644 index 0000000..624d015 --- /dev/null +++ b/node_modules/lodash/attempt.js @@ -0,0 +1,35 @@ +var apply = require('./_apply'), + baseRest = require('./_baseRest'), + isError = require('./isError'); + +/** + * Attempts to invoke `func`, returning either the result or the caught error + * object. Any additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Function} func The function to attempt. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {*} Returns the `func` result or error object. + * @example + * + * // Avoid throwing errors for invalid selectors. + * var elements = _.attempt(function(selector) { + * return document.querySelectorAll(selector); + * }, '>_>'); + * + * if (_.isError(elements)) { + * elements = []; + * } + */ +var attempt = baseRest(function(func, args) { + try { + return apply(func, undefined, args); + } catch (e) { + return isError(e) ? e : new Error(e); + } +}); + +module.exports = attempt; diff --git a/node_modules/lodash/before.js b/node_modules/lodash/before.js new file mode 100644 index 0000000..a3e0a16 --- /dev/null +++ b/node_modules/lodash/before.js @@ -0,0 +1,40 @@ +var toInteger = require('./toInteger'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ +function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; +} + +module.exports = before; diff --git a/node_modules/lodash/bind.js b/node_modules/lodash/bind.js new file mode 100644 index 0000000..b1076e9 --- /dev/null +++ b/node_modules/lodash/bind.js @@ -0,0 +1,57 @@ +var baseRest = require('./_baseRest'), + createWrap = require('./_createWrap'), + getHolder = require('./_getHolder'), + replaceHolders = require('./_replaceHolders'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_PARTIAL_FLAG = 32; + +/** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ +var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); +}); + +// Assign default placeholders. +bind.placeholder = {}; + +module.exports = bind; diff --git a/node_modules/lodash/bindAll.js b/node_modules/lodash/bindAll.js new file mode 100644 index 0000000..a35706d --- /dev/null +++ b/node_modules/lodash/bindAll.js @@ -0,0 +1,41 @@ +var arrayEach = require('./_arrayEach'), + baseAssignValue = require('./_baseAssignValue'), + bind = require('./bind'), + flatRest = require('./_flatRest'), + toKey = require('./_toKey'); + +/** + * Binds methods of an object to the object itself, overwriting the existing + * method. + * + * **Note:** This method doesn't set the "length" property of bound functions. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...(string|string[])} methodNames The object method names to bind. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'click': function() { + * console.log('clicked ' + this.label); + * } + * }; + * + * _.bindAll(view, ['click']); + * jQuery(element).on('click', view.click); + * // => Logs 'clicked docs' when clicked. + */ +var bindAll = flatRest(function(object, methodNames) { + arrayEach(methodNames, function(key) { + key = toKey(key); + baseAssignValue(object, key, bind(object[key], object)); + }); + return object; +}); + +module.exports = bindAll; diff --git a/node_modules/lodash/bindKey.js b/node_modules/lodash/bindKey.js new file mode 100644 index 0000000..f7fd64c --- /dev/null +++ b/node_modules/lodash/bindKey.js @@ -0,0 +1,68 @@ +var baseRest = require('./_baseRest'), + createWrap = require('./_createWrap'), + getHolder = require('./_getHolder'), + replaceHolders = require('./_replaceHolders'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_PARTIAL_FLAG = 32; + +/** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ +var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); +}); + +// Assign default placeholders. +bindKey.placeholder = {}; + +module.exports = bindKey; diff --git a/node_modules/lodash/camelCase.js b/node_modules/lodash/camelCase.js new file mode 100644 index 0000000..d7390de --- /dev/null +++ b/node_modules/lodash/camelCase.js @@ -0,0 +1,29 @@ +var capitalize = require('./capitalize'), + createCompounder = require('./_createCompounder'); + +/** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ +var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); +}); + +module.exports = camelCase; diff --git a/node_modules/lodash/capitalize.js b/node_modules/lodash/capitalize.js new file mode 100644 index 0000000..3e1600e --- /dev/null +++ b/node_modules/lodash/capitalize.js @@ -0,0 +1,23 @@ +var toString = require('./toString'), + upperFirst = require('./upperFirst'); + +/** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ +function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); +} + +module.exports = capitalize; diff --git a/node_modules/lodash/castArray.js b/node_modules/lodash/castArray.js new file mode 100644 index 0000000..e470bdb --- /dev/null +++ b/node_modules/lodash/castArray.js @@ -0,0 +1,44 @@ +var isArray = require('./isArray'); + +/** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ +function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; +} + +module.exports = castArray; diff --git a/node_modules/lodash/ceil.js b/node_modules/lodash/ceil.js new file mode 100644 index 0000000..56c8722 --- /dev/null +++ b/node_modules/lodash/ceil.js @@ -0,0 +1,26 @@ +var createRound = require('./_createRound'); + +/** + * Computes `number` rounded up to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round up. + * @param {number} [precision=0] The precision to round up to. + * @returns {number} Returns the rounded up number. + * @example + * + * _.ceil(4.006); + * // => 5 + * + * _.ceil(6.004, 2); + * // => 6.01 + * + * _.ceil(6040, -2); + * // => 6100 + */ +var ceil = createRound('ceil'); + +module.exports = ceil; diff --git a/node_modules/lodash/chain.js b/node_modules/lodash/chain.js new file mode 100644 index 0000000..f6cd647 --- /dev/null +++ b/node_modules/lodash/chain.js @@ -0,0 +1,38 @@ +var lodash = require('./wrapperLodash'); + +/** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ +function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; +} + +module.exports = chain; diff --git a/node_modules/lodash/chunk.js b/node_modules/lodash/chunk.js new file mode 100644 index 0000000..5b562fe --- /dev/null +++ b/node_modules/lodash/chunk.js @@ -0,0 +1,50 @@ +var baseSlice = require('./_baseSlice'), + isIterateeCall = require('./_isIterateeCall'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeCeil = Math.ceil, + nativeMax = Math.max; + +/** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ +function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; +} + +module.exports = chunk; diff --git a/node_modules/lodash/clamp.js b/node_modules/lodash/clamp.js new file mode 100644 index 0000000..91a72c9 --- /dev/null +++ b/node_modules/lodash/clamp.js @@ -0,0 +1,39 @@ +var baseClamp = require('./_baseClamp'), + toNumber = require('./toNumber'); + +/** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ +function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); +} + +module.exports = clamp; diff --git a/node_modules/lodash/clone.js b/node_modules/lodash/clone.js new file mode 100644 index 0000000..dd439d6 --- /dev/null +++ b/node_modules/lodash/clone.js @@ -0,0 +1,36 @@ +var baseClone = require('./_baseClone'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_SYMBOLS_FLAG = 4; + +/** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ +function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); +} + +module.exports = clone; diff --git a/node_modules/lodash/cloneDeep.js b/node_modules/lodash/cloneDeep.js new file mode 100644 index 0000000..4425fbe --- /dev/null +++ b/node_modules/lodash/cloneDeep.js @@ -0,0 +1,29 @@ +var baseClone = require('./_baseClone'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1, + CLONE_SYMBOLS_FLAG = 4; + +/** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ +function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); +} + +module.exports = cloneDeep; diff --git a/node_modules/lodash/cloneDeepWith.js b/node_modules/lodash/cloneDeepWith.js new file mode 100644 index 0000000..fd9c6c0 --- /dev/null +++ b/node_modules/lodash/cloneDeepWith.js @@ -0,0 +1,40 @@ +var baseClone = require('./_baseClone'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1, + CLONE_SYMBOLS_FLAG = 4; + +/** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ +function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); +} + +module.exports = cloneDeepWith; diff --git a/node_modules/lodash/cloneWith.js b/node_modules/lodash/cloneWith.js new file mode 100644 index 0000000..d2f4e75 --- /dev/null +++ b/node_modules/lodash/cloneWith.js @@ -0,0 +1,42 @@ +var baseClone = require('./_baseClone'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_SYMBOLS_FLAG = 4; + +/** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ +function cloneWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); +} + +module.exports = cloneWith; diff --git a/node_modules/lodash/collection.js b/node_modules/lodash/collection.js new file mode 100644 index 0000000..77fe837 --- /dev/null +++ b/node_modules/lodash/collection.js @@ -0,0 +1,30 @@ +module.exports = { + 'countBy': require('./countBy'), + 'each': require('./each'), + 'eachRight': require('./eachRight'), + 'every': require('./every'), + 'filter': require('./filter'), + 'find': require('./find'), + 'findLast': require('./findLast'), + 'flatMap': require('./flatMap'), + 'flatMapDeep': require('./flatMapDeep'), + 'flatMapDepth': require('./flatMapDepth'), + 'forEach': require('./forEach'), + 'forEachRight': require('./forEachRight'), + 'groupBy': require('./groupBy'), + 'includes': require('./includes'), + 'invokeMap': require('./invokeMap'), + 'keyBy': require('./keyBy'), + 'map': require('./map'), + 'orderBy': require('./orderBy'), + 'partition': require('./partition'), + 'reduce': require('./reduce'), + 'reduceRight': require('./reduceRight'), + 'reject': require('./reject'), + 'sample': require('./sample'), + 'sampleSize': require('./sampleSize'), + 'shuffle': require('./shuffle'), + 'size': require('./size'), + 'some': require('./some'), + 'sortBy': require('./sortBy') +}; diff --git a/node_modules/lodash/commit.js b/node_modules/lodash/commit.js new file mode 100644 index 0000000..fe4db71 --- /dev/null +++ b/node_modules/lodash/commit.js @@ -0,0 +1,33 @@ +var LodashWrapper = require('./_LodashWrapper'); + +/** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ +function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); +} + +module.exports = wrapperCommit; diff --git a/node_modules/lodash/compact.js b/node_modules/lodash/compact.js new file mode 100644 index 0000000..623b05d --- /dev/null +++ b/node_modules/lodash/compact.js @@ -0,0 +1,31 @@ +/** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `-0`, `0n`, `""`, `undefined`, and `NaN` are falsy. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ +function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; +} + +module.exports = compact; diff --git a/node_modules/lodash/concat.js b/node_modules/lodash/concat.js new file mode 100644 index 0000000..1da48a4 --- /dev/null +++ b/node_modules/lodash/concat.js @@ -0,0 +1,43 @@ +var arrayPush = require('./_arrayPush'), + baseFlatten = require('./_baseFlatten'), + copyArray = require('./_copyArray'), + isArray = require('./isArray'); + +/** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ +function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); +} + +module.exports = concat; diff --git a/node_modules/lodash/cond.js b/node_modules/lodash/cond.js new file mode 100644 index 0000000..6455598 --- /dev/null +++ b/node_modules/lodash/cond.js @@ -0,0 +1,60 @@ +var apply = require('./_apply'), + arrayMap = require('./_arrayMap'), + baseIteratee = require('./_baseIteratee'), + baseRest = require('./_baseRest'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that iterates over `pairs` and invokes the corresponding + * function of the first predicate to return truthy. The predicate-function + * pairs are invoked with the `this` binding and arguments of the created + * function. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {Array} pairs The predicate-function pairs. + * @returns {Function} Returns the new composite function. + * @example + * + * var func = _.cond([ + * [_.matches({ 'a': 1 }), _.constant('matches A')], + * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], + * [_.stubTrue, _.constant('no match')] + * ]); + * + * func({ 'a': 1, 'b': 2 }); + * // => 'matches A' + * + * func({ 'a': 0, 'b': 1 }); + * // => 'matches B' + * + * func({ 'a': '1', 'b': '2' }); + * // => 'no match' + */ +function cond(pairs) { + var length = pairs == null ? 0 : pairs.length, + toIteratee = baseIteratee; + + pairs = !length ? [] : arrayMap(pairs, function(pair) { + if (typeof pair[1] != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return [toIteratee(pair[0]), pair[1]]; + }); + + return baseRest(function(args) { + var index = -1; + while (++index < length) { + var pair = pairs[index]; + if (apply(pair[0], this, args)) { + return apply(pair[1], this, args); + } + } + }); +} + +module.exports = cond; diff --git a/node_modules/lodash/conforms.js b/node_modules/lodash/conforms.js new file mode 100644 index 0000000..5501a94 --- /dev/null +++ b/node_modules/lodash/conforms.js @@ -0,0 +1,35 @@ +var baseClone = require('./_baseClone'), + baseConforms = require('./_baseConforms'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1; + +/** + * Creates a function that invokes the predicate properties of `source` with + * the corresponding property values of a given object, returning `true` if + * all predicates return truthy, else `false`. + * + * **Note:** The created function is equivalent to `_.conformsTo` with + * `source` partially applied. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + * @example + * + * var objects = [ + * { 'a': 2, 'b': 1 }, + * { 'a': 1, 'b': 2 } + * ]; + * + * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); + * // => [{ 'a': 1, 'b': 2 }] + */ +function conforms(source) { + return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); +} + +module.exports = conforms; diff --git a/node_modules/lodash/conformsTo.js b/node_modules/lodash/conformsTo.js new file mode 100644 index 0000000..b8a93eb --- /dev/null +++ b/node_modules/lodash/conformsTo.js @@ -0,0 +1,32 @@ +var baseConformsTo = require('./_baseConformsTo'), + keys = require('./keys'); + +/** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ +function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); +} + +module.exports = conformsTo; diff --git a/node_modules/lodash/constant.js b/node_modules/lodash/constant.js new file mode 100644 index 0000000..655ece3 --- /dev/null +++ b/node_modules/lodash/constant.js @@ -0,0 +1,26 @@ +/** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ +function constant(value) { + return function() { + return value; + }; +} + +module.exports = constant; diff --git a/node_modules/lodash/core.js b/node_modules/lodash/core.js new file mode 100644 index 0000000..694ed51 --- /dev/null +++ b/node_modules/lodash/core.js @@ -0,0 +1,3877 @@ +/** + * @license + * Lodash (Custom Build) + * Build: `lodash core --repo lodash/lodash#4.18.1 -o ./core.js` + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.18.1'; + + /** Error message constants. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_PARTIAL_FLAG = 32; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + numberTag = '[object Number]', + objectTag = '[object Object]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + stringTag = '[object String]'; + + /** Used to match HTML entities and HTML characters. */ + var reUnescapedHtml = /[&<>"']/g, + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /*--------------------------------------------------------------------------*/ + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + array.push.apply(array, values); + return array; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return baseMap(props, function(key) { + return object[key]; + }); + } + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /*--------------------------------------------------------------------------*/ + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Built-in value references. */ + var objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeIsFinite = root.isFinite, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + return value instanceof LodashWrapper + ? value + : new LodashWrapper(value); + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + } + + LodashWrapper.prototype = baseCreate(lodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + object[key] = value; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !false) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return baseFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + return objectToString(value); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + var baseIsArguments = noop; + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : baseGetTag(object), + othTag = othIsArr ? arrayTag : baseGetTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + stack || (stack = []); + var objStack = find(stack, function(entry) { + return entry[0] == object; + }); + var othStack = find(stack, function(entry) { + return entry[0] == other; + }); + if (objStack && othStack) { + return objStack[1] == other; + } + stack.push([object, other]); + stack.push([other, object]); + if (isSameTag && !objIsObj) { + var result = (objIsArr) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + stack.pop(); + return result; + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + var result = equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + stack.pop(); + return result; + } + } + if (!isSameTag) { + return false; + } + var result = equalObjects(object, other, bitmask, customizer, equalFunc, stack); + stack.pop(); + return result; + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(func) { + if (typeof func == 'function') { + return func; + } + if (func == null) { + return identity; + } + return (typeof func == 'object' ? baseMatches : baseProperty)(func); + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var props = nativeKeys(source); + return function(object) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length]; + if (!(key in object && + baseIsEqual(source[key], object[key], COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG) + )) { + return false; + } + } + return true; + }; + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, props) { + object = Object(object); + return reduce(props, function(result, key) { + if (key in object) { + result[key] = object[key]; + } + return result; + }, {}); + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source) { + return baseSlice(source, 0, source.length); + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + return reduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = false; + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = false; + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = baseIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return fn.apply(isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? [] : undefined; + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + var compared; + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!baseSome(other, function(othValue, othIndex) { + if (!indexOf(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = keys(object), + objLength = objProps.length, + othProps = keys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + var compared; + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return func.apply(this, otherArgs); + }; + } + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = identity; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `-0`, `0n`, `""`, `undefined`, and `NaN` are falsy. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + return baseFilter(array, Boolean); + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, baseIteratee(predicate, 3), index); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (typeof fromIndex == 'number') { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; + } else { + fromIndex = 0; + } + var index = (fromIndex || 0) - 1, + isReflexive = value === value; + + while (++index < length) { + var other = array[index]; + if ((isReflexive ? other === value : other !== other)) { + return index; + } + } + return -1; + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + start = start == null ? 0 : +start; + end = end === undefined ? length : +end; + return length ? baseSlice(array, start, end) : []; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + predicate = guard ? undefined : predicate; + return baseEvery(collection, baseIteratee(predicate)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + * + * // Combining several predicates using `_.overEvery` or `_.overSome`. + * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); + * // => objects for ['fred', 'barney'] + */ + function filter(collection, predicate) { + return baseFilter(collection, baseIteratee(predicate)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + return baseEach(collection, baseIteratee(iteratee)); + } + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + return baseMap(collection, baseIteratee(iteratee)); + } + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + return baseReduce(collection, baseIteratee(iteratee), accumulator, arguments.length < 3, baseEach); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + collection = isArrayLike(collection) ? collection : nativeKeys(collection); + return collection.length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + predicate = guard ? undefined : predicate; + return baseSome(collection, baseIteratee(predicate)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 30 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + */ + function sortBy(collection, iteratee) { + var index = 0; + iteratee = baseIteratee(iteratee); + + return baseMap(baseMap(collection, function(value, key, collection) { + return { 'value': value, 'index': index++, 'criteria': iteratee(value, key, collection) }; + }).sort(function(object, other) { + return compareAscending(object.criteria, other.criteria) || (object.index - other.index); + }), baseProperty('value')); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + return createPartial(func, WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG, thisArg, partials); + }); + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + if (!isObject(value)) { + return value; + } + return isArray(value) ? copyArray(value) : copyObject(value, nativeKeys(value)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); + } + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = baseIsDate; + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (isArrayLike(value) && + (isArray(value) || isString(value) || + isFunction(value.splice) || isArguments(value))) { + return !value.length; + } + return !nativeKeys(value).length; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = baseIsRegExp; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + } + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!isArrayLike(value)) { + return values(value); + } + return value.length ? copyArray(value) : []; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + var toInteger = Number; + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + var toNumber = Number; + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + if (typeof value == 'string') { + return value; + } + return value == null ? '' : (value + ''); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + copyObject(source, nativeKeys(source), object); + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, nativeKeysIn(source), object); + }); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : assign(result, properties); + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; + }); + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasOwnProperty.call(object, path); + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + var keys = nativeKeys; + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + var keysIn = nativeKeysIn; + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + var value = object == null ? undefined : object[path]; + if (value === undefined) { + value = defaultValue; + } + return isFunction(value) ? value.call(object) : value; + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object == null ? [] : baseValues(object, keys(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /*------------------------------------------------------------------------*/ + + /** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ + function identity(value) { + return value; + } + + /** + * Creates a function that invokes `func` with the arguments of the created + * function. If `func` is a property name, the created function returns the + * property value for a given element. If `func` is an array or object, the + * created function returns `true` for elements that contain the equivalent + * source properties, otherwise it returns `false`. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Util + * @param {*} [func=_.identity] The value to convert to a callback. + * @returns {Function} Returns the callback. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); + * // => [{ 'user': 'barney', 'age': 36, 'active': true }] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, _.iteratee(['user', 'fred'])); + * // => [{ 'user': 'fred', 'age': 40 }] + * + * // The `_.property` iteratee shorthand. + * _.map(users, _.iteratee('user')); + * // => ['barney', 'fred'] + * + * // Create custom iteratee shorthands. + * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { + * return !_.isRegExp(func) ? iteratee(func) : function(string) { + * return func.test(string); + * }; + * }); + * + * _.filter(['abc', 'def'], /ef/); + * // => ['def'] + */ + var iteratee = baseIteratee; + + /** + * Creates a function that performs a partial deep comparison between a given + * object and `source`, returning `true` if the given object has equivalent + * property values, else `false`. + * + * **Note:** The created function is equivalent to `_.isMatch` with `source` + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * **Note:** Multiple values can be checked by combining several matchers + * using `_.overSome` + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + * @example + * + * var objects = [ + * { 'a': 1, 'b': 2, 'c': 3 }, + * { 'a': 4, 'b': 5, 'c': 6 } + * ]; + * + * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); + * // => [{ 'a': 4, 'b': 5, 'c': 6 }] + * + * // Checking for several possible values + * _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })])); + * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }] + */ + function matches(source) { + return baseMatches(assign({}, source)); + } + + /** + * Adds all own enumerable string keyed function properties of a source + * object to the destination object. If `object` is a function, then methods + * are added to its prototype as well. + * + * **Note:** Use `_.runInContext` to create a pristine `lodash` function to + * avoid conflicts caused by modifying the original. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {Function|Object} [object=lodash] The destination object. + * @param {Object} source The object of functions to add. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.chain=true] Specify whether mixins are chainable. + * @returns {Function|Object} Returns `object`. + * @example + * + * function vowels(string) { + * return _.filter(string, function(v) { + * return /[aeiou]/i.test(v); + * }); + * } + * + * _.mixin({ 'vowels': vowels }); + * _.vowels('fred'); + * // => ['e'] + * + * _('fred').vowels().value(); + * // => ['e'] + * + * _.mixin({ 'vowels': vowels }, { 'chain': false }); + * _('fred').vowels(); + * // => ['e'] + */ + function mixin(object, source, options) { + var props = keys(source), + methodNames = baseFunctions(source, props); + + if (options == null && + !(isObject(source) && (methodNames.length || !props.length))) { + options = source; + source = object; + object = this; + methodNames = baseFunctions(source, keys(source)); + } + var chain = !(isObject(options) && 'chain' in options) || !!options.chain, + isFunc = isFunction(object); + + baseEach(methodNames, function(methodName) { + var func = source[methodName]; + object[methodName] = func; + if (isFunc) { + object.prototype[methodName] = function() { + var chainAll = this.__chain__; + if (chain || chainAll) { + var result = object(this.__wrapped__), + actions = result.__actions__ = copyArray(this.__actions__); + + actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); + result.__chain__ = chainAll; + return result; + } + return func.apply(object, arrayPush([this.value()], arguments)); + }; + } + }); + + return object; + } + + /** + * Reverts the `_` variable to its previous value and returns a reference to + * the `lodash` function. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @returns {Function} Returns the `lodash` function. + * @example + * + * var lodash = _.noConflict(); + */ + function noConflict() { + if (root._ === this) { + root._ = oldDash; + } + return this; + } + + /** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ + function noop() { + // No operation performed. + } + + /** + * Generates a unique ID. If `prefix` is given, the ID is appended to it. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {string} [prefix=''] The value to prefix the ID with. + * @returns {string} Returns the unique ID. + * @example + * + * _.uniqueId('contact_'); + * // => 'contact_104' + * + * _.uniqueId(); + * // => '105' + */ + function uniqueId(prefix) { + var id = ++idCounter; + return toString(prefix) + id; + } + + /*------------------------------------------------------------------------*/ + + /** + * Computes the maximum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * _.max([]); + * // => undefined + */ + function max(array) { + return (array && array.length) + ? baseExtremum(array, identity, baseGt) + : undefined; + } + + /** + * Computes the minimum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * _.min([]); + * // => undefined + */ + function min(array) { + return (array && array.length) + ? baseExtremum(array, identity, baseLt) + : undefined; + } + + /*------------------------------------------------------------------------*/ + + // Add methods that return wrapped values in chain sequences. + lodash.assignIn = assignIn; + lodash.before = before; + lodash.bind = bind; + lodash.chain = chain; + lodash.compact = compact; + lodash.concat = concat; + lodash.create = create; + lodash.defaults = defaults; + lodash.defer = defer; + lodash.delay = delay; + lodash.filter = filter; + lodash.flatten = flatten; + lodash.flattenDeep = flattenDeep; + lodash.iteratee = iteratee; + lodash.keys = keys; + lodash.map = map; + lodash.matches = matches; + lodash.mixin = mixin; + lodash.negate = negate; + lodash.once = once; + lodash.pick = pick; + lodash.slice = slice; + lodash.sortBy = sortBy; + lodash.tap = tap; + lodash.thru = thru; + lodash.toArray = toArray; + lodash.values = values; + + // Add aliases. + lodash.extend = assignIn; + + // Add methods to `lodash.prototype`. + mixin(lodash, lodash); + + /*------------------------------------------------------------------------*/ + + // Add methods that return unwrapped values in chain sequences. + lodash.clone = clone; + lodash.escape = escape; + lodash.every = every; + lodash.find = find; + lodash.forEach = forEach; + lodash.has = has; + lodash.head = head; + lodash.identity = identity; + lodash.indexOf = indexOf; + lodash.isArguments = isArguments; + lodash.isArray = isArray; + lodash.isBoolean = isBoolean; + lodash.isDate = isDate; + lodash.isEmpty = isEmpty; + lodash.isEqual = isEqual; + lodash.isFinite = isFinite; + lodash.isFunction = isFunction; + lodash.isNaN = isNaN; + lodash.isNull = isNull; + lodash.isNumber = isNumber; + lodash.isObject = isObject; + lodash.isRegExp = isRegExp; + lodash.isString = isString; + lodash.isUndefined = isUndefined; + lodash.last = last; + lodash.max = max; + lodash.min = min; + lodash.noConflict = noConflict; + lodash.noop = noop; + lodash.reduce = reduce; + lodash.result = result; + lodash.size = size; + lodash.some = some; + lodash.uniqueId = uniqueId; + + // Add aliases. + lodash.each = forEach; + lodash.first = head; + + mixin(lodash, (function() { + var source = {}; + baseForOwn(lodash, function(func, methodName) { + if (!hasOwnProperty.call(lodash.prototype, methodName)) { + source[methodName] = func; + } + }); + return source; + }()), { 'chain': false }); + + /*------------------------------------------------------------------------*/ + + /** + * The semantic version number. + * + * @static + * @memberOf _ + * @type {string} + */ + lodash.VERSION = VERSION; + + // Add `Array` methods to `lodash.prototype`. + baseEach(['pop', 'join', 'replace', 'reverse', 'split', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { + var func = (/^(?:replace|split)$/.test(methodName) ? String.prototype : arrayProto)[methodName], + chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', + retUnwrapped = /^(?:pop|join|replace|shift)$/.test(methodName); + + lodash.prototype[methodName] = function() { + var args = arguments; + if (retUnwrapped && !this.__chain__) { + var value = this.value(); + return func.apply(isArray(value) ? value : [], args); + } + return this[chainName](function(value) { + return func.apply(isArray(value) ? value : [], args); + }); + }; + }); + + // Add chain sequence methods to the `lodash` wrapper. + lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; + + /*--------------------------------------------------------------------------*/ + + // Some AMD build optimizers, like r.js, check for condition patterns like: + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + // Expose Lodash on the global object to prevent errors when Lodash is + // loaded by a script tag in the presence of an AMD loader. + // See http://requirejs.org/docs/errors.html#mismatch for more details. + // Use `_.noConflict` to remove Lodash from the global object. + root._ = lodash; + + // Define as an anonymous module so, through path mapping, it can be + // referenced as the "underscore" module. + define(function() { + return lodash; + }); + } + // Check for `exports` after `define` in case a build optimizer adds it. + else if (freeModule) { + // Export for Node.js. + (freeModule.exports = lodash)._ = lodash; + // Export for CommonJS support. + freeExports._ = lodash; + } + else { + // Export to the global object. + root._ = lodash; + } +}.call(this)); diff --git a/node_modules/lodash/core.min.js b/node_modules/lodash/core.min.js new file mode 100644 index 0000000..579b754 --- /dev/null +++ b/node_modules/lodash/core.min.js @@ -0,0 +1,30 @@ +/** + * @license + * Lodash (Custom Build) lodash.com/license | Underscore.js 1.8.3 underscorejs.org/LICENSE + * Build: `lodash core --repo lodash/lodash#4.18.1 -o ./core.js` + */ +;(function(){function n(n,t){return n.push.apply(n,t),n}function t(n,t,r,e){for(var u=n.length,o=r+(e?1:-1);e?o--:++o0&&e(f)?r>1?y(f,r-1,e,u,o):n(o,f):u||(o[o.length]=f)}return o}function g(n,t){return n&&Vt(n,t,cr)}function _(n,t){return v(t,function(t){return Tn(n[t])})}function b(n){return W(n)}function j(n,t){return n>t}function d(n){return In(n)&&b(n)==ht}function m(n,t,r,e,u){return n===t||(null==n||null==t||!In(n)&&!In(t)?n!==n&&t!==t:O(n,t,r,e,m,u))}function O(n,t,r,e,u,o){ +var i=Zt(n),c=Zt(t),f=i?lt:b(n),a=c?lt:b(t);f=f==at?bt:f,a=a==at?bt:a;var l=f==bt,p=a==bt,s=f==a;o||(o=[]);var h=Lt(o,function(t){return t[0]==n}),v=Lt(o,function(n){return n[0]==t});if(h&&v)return h[1]==t;if(o.push([n,t]),o.push([t,n]),s&&!l){var y=i?J(n,t,r,e,u,o):M(n,t,f,r,e,u,o);return o.pop(),y}if(!(r&et)){var g=l&&Rt.call(n,"__wrapped__"),_=p&&Rt.call(t,"__wrapped__");if(g||_){var j=g?n.value():n,d=_?t.value():t,y=u(j,d,r,e,o);return o.pop(),y}}if(!s)return false;var y=U(n,t,r,e,u,o);return o.pop(), +y}function x(n){return In(n)&&b(n)==dt}function w(n){return typeof n=="function"?n:null==n?Hn:(typeof n=="object"?N:r)(n)}function A(n,t){return nu?0:u+t),r=r>u?u:r,r<0&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0;for(var o=Array(u);++et||o&&i&&f&&!c&&!a||e&&i&&f||!r&&f||!u)return 1; +if(!e&&!o&&!a&&n1?r[u-1]:nt;for(o=n.length>3&&typeof o=="function"?(u--,o):nt,t=Object(t);++e-1?u[o?t[i]:i]:nt}}function G(n,t,r,e){function u(){for(var t=-1,c=arguments.length,f=-1,a=e.length,l=Array(a+c),p=this&&this!==kt&&this instanceof u?i:n;++fc))return false;var a=o.get(n),l=o.get(t);if(a&&l)return a==t&&l==n;for(var p=-1,s=true,h=r&ut?[]:nt;++p-1&&n%1==0&&n0&&(r=t.apply(this,arguments)),n<=1&&(t=nt),r}}function mn(n){if(typeof n!="function")throw new TypeError(rt);return function(){return!n.apply(this,arguments)}; +}function On(n){return dn(2,n)}function xn(n){return Bn(n)?Zt(n)?S(n):$(n,Gt(n)):n}function wn(n,t){return n===t||n!==n&&t!==t}function An(n){return null!=n&&Sn(n.length)&&!Tn(n)}function En(n){return n===true||n===false||In(n)&&b(n)==st}function Nn(n){return An(n)&&(Zt(n)||Dn(n)||Tn(n.splice)||Yt(n))?!n.length:!Gt(n).length}function kn(n,t){return m(n,t)}function Fn(n){return typeof n=="number"&&Ct(n)}function Tn(n){if(!Bn(n))return false;var t=b(n);return t==yt||t==gt||t==pt||t==jt}function Sn(n){return typeof n=="number"&&n>-1&&n%1==0&&n<=ft; +}function Bn(n){var t=typeof n;return null!=n&&("object"==t||"function"==t)}function In(n){return null!=n&&typeof n=="object"}function Rn(n){return qn(n)&&n!=+n}function $n(n){return null===n}function qn(n){return typeof n=="number"||In(n)&&b(n)==_t}function Dn(n){return typeof n=="string"||!Zt(n)&&In(n)&&b(n)==mt}function Pn(n){return n===nt}function zn(n){return An(n)?n.length?S(n):[]:Un(n)}function Cn(n){return typeof n=="string"?n:null==n?"":n+""}function Gn(n,t){var r=Mt(n);return null==t?r:ur(r,t); +}function Jn(n,t){return null!=n&&Rt.call(n,t)}function Mn(n,t,r){var e=null==n?nt:n[t];return e===nt&&(e=r),Tn(e)?e.call(n):e}function Un(n){return null==n?[]:o(n,cr(n))}function Vn(n){return n=Cn(n),n&&xt.test(n)?n.replace(Ot,St):n}function Hn(n){return n}function Kn(n){return N(ur({},n))}function Ln(t,r,e){var u=cr(r),o=_(r,u);null!=e||Bn(r)&&(o.length||!u.length)||(e=r,r=t,t=this,o=_(r,cr(r)));var i=!(Bn(e)&&"chain"in e&&!e.chain),c=Tn(t);return Ut(o,function(e){var u=r[e];t[e]=u,c&&(t.prototype[e]=function(){ +var r=this.__chain__;if(i||r){var e=t(this.__wrapped__);return(e.__actions__=S(this.__actions__)).push({func:u,args:arguments,thisArg:t}),e.__chain__=r,e}return u.apply(t,n([this.value()],arguments))})}),t}function Qn(){return kt._===this&&(kt._=Dt),this}function Wn(){}function Xn(n){var t=++$t;return Cn(n)+t}function Yn(n){return n&&n.length?h(n,Hn,j):nt}function Zn(n){return n&&n.length?h(n,Hn,A):nt}var nt,tt="4.18.1",rt="Expected a function",et=1,ut=2,ot=1,it=32,ct=1/0,ft=9007199254740991,at="[object Arguments]",lt="[object Array]",pt="[object AsyncFunction]",st="[object Boolean]",ht="[object Date]",vt="[object Error]",yt="[object Function]",gt="[object GeneratorFunction]",_t="[object Number]",bt="[object Object]",jt="[object Proxy]",dt="[object RegExp]",mt="[object String]",Ot=/[&<>"']/g,xt=RegExp(Ot.source),wt=/^(?:0|[1-9]\d*)$/,At={ +"&":"&","<":"<",">":">",'"':""","'":"'"},Et=typeof global=="object"&&global&&global.Object===Object&&global,Nt=typeof self=="object"&&self&&self.Object===Object&&self,kt=Et||Nt||Function("return this")(),Ft=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Tt=Ft&&typeof module=="object"&&module&&!module.nodeType&&module,St=e(At),Bt=Array.prototype,It=Object.prototype,Rt=It.hasOwnProperty,$t=0,qt=It.toString,Dt=kt._,Pt=Object.create,zt=It.propertyIsEnumerable,Ct=kt.isFinite,Gt=i(Object.keys,Object),Jt=Math.max,Mt=function(){ +function n(){}return function(t){if(!Bn(t))return{};if(Pt)return Pt(t);n.prototype=t;var r=new n;return n.prototype=nt,r}}();f.prototype=Mt(c.prototype),f.prototype.constructor=f;var Ut=D(g),Vt=P(),Ht=Wn,Kt=Hn,Lt=C(nn),Qt=F(function(n,t,r){return G(n,ot|it,t,r)}),Wt=F(function(n,t){return p(n,1,t)}),Xt=F(function(n,t,r){return p(n,er(t)||0,r)}),Yt=Ht(function(){return arguments}())?Ht:function(n){return In(n)&&Rt.call(n,"callee")&&!zt.call(n,"callee")},Zt=Array.isArray,nr=d,tr=x,rr=Number,er=Number,ur=q(function(n,t){ +$(t,Gt(t),n)}),or=q(function(n,t){$(t,Q(t),n)}),ir=F(function(n,t){n=Object(n);var r=-1,e=t.length,u=e>2?t[2]:nt;for(u&&L(t[0],t[1],u)&&(e=1);++r { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ +var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } +}); + +module.exports = countBy; diff --git a/node_modules/lodash/create.js b/node_modules/lodash/create.js new file mode 100644 index 0000000..919edb8 --- /dev/null +++ b/node_modules/lodash/create.js @@ -0,0 +1,43 @@ +var baseAssign = require('./_baseAssign'), + baseCreate = require('./_baseCreate'); + +/** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ +function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : baseAssign(result, properties); +} + +module.exports = create; diff --git a/node_modules/lodash/curry.js b/node_modules/lodash/curry.js new file mode 100644 index 0000000..918db1a --- /dev/null +++ b/node_modules/lodash/curry.js @@ -0,0 +1,57 @@ +var createWrap = require('./_createWrap'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_CURRY_FLAG = 8; + +/** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ +function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; +} + +// Assign default placeholders. +curry.placeholder = {}; + +module.exports = curry; diff --git a/node_modules/lodash/curryRight.js b/node_modules/lodash/curryRight.js new file mode 100644 index 0000000..c85b6f3 --- /dev/null +++ b/node_modules/lodash/curryRight.js @@ -0,0 +1,54 @@ +var createWrap = require('./_createWrap'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_CURRY_RIGHT_FLAG = 16; + +/** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ +function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; +} + +// Assign default placeholders. +curryRight.placeholder = {}; + +module.exports = curryRight; diff --git a/node_modules/lodash/date.js b/node_modules/lodash/date.js new file mode 100644 index 0000000..cbf5b41 --- /dev/null +++ b/node_modules/lodash/date.js @@ -0,0 +1,3 @@ +module.exports = { + 'now': require('./now') +}; diff --git a/node_modules/lodash/debounce.js b/node_modules/lodash/debounce.js new file mode 100644 index 0000000..8f751d5 --- /dev/null +++ b/node_modules/lodash/debounce.js @@ -0,0 +1,191 @@ +var isObject = require('./isObject'), + now = require('./now'), + toNumber = require('./toNumber'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ +function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + timeWaiting = wait - timeSinceLastCall; + + return maxing + ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + clearTimeout(timerId); + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; +} + +module.exports = debounce; diff --git a/node_modules/lodash/deburr.js b/node_modules/lodash/deburr.js new file mode 100644 index 0000000..f85e314 --- /dev/null +++ b/node_modules/lodash/deburr.js @@ -0,0 +1,45 @@ +var deburrLetter = require('./_deburrLetter'), + toString = require('./toString'); + +/** Used to match Latin Unicode letters (excluding mathematical operators). */ +var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + +/** Used to compose unicode character classes. */ +var rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; + +/** Used to compose unicode capture groups. */ +var rsCombo = '[' + rsComboRange + ']'; + +/** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ +var reComboMark = RegExp(rsCombo, 'g'); + +/** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ +function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); +} + +module.exports = deburr; diff --git a/node_modules/lodash/defaultTo.js b/node_modules/lodash/defaultTo.js new file mode 100644 index 0000000..5b33359 --- /dev/null +++ b/node_modules/lodash/defaultTo.js @@ -0,0 +1,25 @@ +/** + * Checks `value` to determine whether a default value should be returned in + * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, + * or `undefined`. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Util + * @param {*} value The value to check. + * @param {*} defaultValue The default value. + * @returns {*} Returns the resolved value. + * @example + * + * _.defaultTo(1, 10); + * // => 1 + * + * _.defaultTo(undefined, 10); + * // => 10 + */ +function defaultTo(value, defaultValue) { + return (value == null || value !== value) ? defaultValue : value; +} + +module.exports = defaultTo; diff --git a/node_modules/lodash/defaults.js b/node_modules/lodash/defaults.js new file mode 100644 index 0000000..c74df04 --- /dev/null +++ b/node_modules/lodash/defaults.js @@ -0,0 +1,64 @@ +var baseRest = require('./_baseRest'), + eq = require('./eq'), + isIterateeCall = require('./_isIterateeCall'), + keysIn = require('./keysIn'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var defaults = baseRest(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; +}); + +module.exports = defaults; diff --git a/node_modules/lodash/defaultsDeep.js b/node_modules/lodash/defaultsDeep.js new file mode 100644 index 0000000..9b5fa3e --- /dev/null +++ b/node_modules/lodash/defaultsDeep.js @@ -0,0 +1,30 @@ +var apply = require('./_apply'), + baseRest = require('./_baseRest'), + customDefaultsMerge = require('./_customDefaultsMerge'), + mergeWith = require('./mergeWith'); + +/** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ +var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); +}); + +module.exports = defaultsDeep; diff --git a/node_modules/lodash/defer.js b/node_modules/lodash/defer.js new file mode 100644 index 0000000..f6d6c6f --- /dev/null +++ b/node_modules/lodash/defer.js @@ -0,0 +1,26 @@ +var baseDelay = require('./_baseDelay'), + baseRest = require('./_baseRest'); + +/** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ +var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); +}); + +module.exports = defer; diff --git a/node_modules/lodash/delay.js b/node_modules/lodash/delay.js new file mode 100644 index 0000000..bd55479 --- /dev/null +++ b/node_modules/lodash/delay.js @@ -0,0 +1,28 @@ +var baseDelay = require('./_baseDelay'), + baseRest = require('./_baseRest'), + toNumber = require('./toNumber'); + +/** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ +var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); +}); + +module.exports = delay; diff --git a/node_modules/lodash/difference.js b/node_modules/lodash/difference.js new file mode 100644 index 0000000..fa28bb3 --- /dev/null +++ b/node_modules/lodash/difference.js @@ -0,0 +1,33 @@ +var baseDifference = require('./_baseDifference'), + baseFlatten = require('./_baseFlatten'), + baseRest = require('./_baseRest'), + isArrayLikeObject = require('./isArrayLikeObject'); + +/** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ +var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; +}); + +module.exports = difference; diff --git a/node_modules/lodash/differenceBy.js b/node_modules/lodash/differenceBy.js new file mode 100644 index 0000000..2cd63e7 --- /dev/null +++ b/node_modules/lodash/differenceBy.js @@ -0,0 +1,44 @@ +var baseDifference = require('./_baseDifference'), + baseFlatten = require('./_baseFlatten'), + baseIteratee = require('./_baseIteratee'), + baseRest = require('./_baseRest'), + isArrayLikeObject = require('./isArrayLikeObject'), + last = require('./last'); + +/** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ +var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), baseIteratee(iteratee, 2)) + : []; +}); + +module.exports = differenceBy; diff --git a/node_modules/lodash/differenceWith.js b/node_modules/lodash/differenceWith.js new file mode 100644 index 0000000..c0233f4 --- /dev/null +++ b/node_modules/lodash/differenceWith.js @@ -0,0 +1,40 @@ +var baseDifference = require('./_baseDifference'), + baseFlatten = require('./_baseFlatten'), + baseRest = require('./_baseRest'), + isArrayLikeObject = require('./isArrayLikeObject'), + last = require('./last'); + +/** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ +var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; +}); + +module.exports = differenceWith; diff --git a/node_modules/lodash/divide.js b/node_modules/lodash/divide.js new file mode 100644 index 0000000..8cae0cd --- /dev/null +++ b/node_modules/lodash/divide.js @@ -0,0 +1,22 @@ +var createMathOperation = require('./_createMathOperation'); + +/** + * Divide two numbers. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Math + * @param {number} dividend The first number in a division. + * @param {number} divisor The second number in a division. + * @returns {number} Returns the quotient. + * @example + * + * _.divide(6, 4); + * // => 1.5 + */ +var divide = createMathOperation(function(dividend, divisor) { + return dividend / divisor; +}, 1); + +module.exports = divide; diff --git a/node_modules/lodash/drop.js b/node_modules/lodash/drop.js new file mode 100644 index 0000000..d5c3cba --- /dev/null +++ b/node_modules/lodash/drop.js @@ -0,0 +1,38 @@ +var baseSlice = require('./_baseSlice'), + toInteger = require('./toInteger'); + +/** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ +function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); +} + +module.exports = drop; diff --git a/node_modules/lodash/dropRight.js b/node_modules/lodash/dropRight.js new file mode 100644 index 0000000..441fe99 --- /dev/null +++ b/node_modules/lodash/dropRight.js @@ -0,0 +1,39 @@ +var baseSlice = require('./_baseSlice'), + toInteger = require('./toInteger'); + +/** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ +function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); +} + +module.exports = dropRight; diff --git a/node_modules/lodash/dropRightWhile.js b/node_modules/lodash/dropRightWhile.js new file mode 100644 index 0000000..9ad36a0 --- /dev/null +++ b/node_modules/lodash/dropRightWhile.js @@ -0,0 +1,45 @@ +var baseIteratee = require('./_baseIteratee'), + baseWhile = require('./_baseWhile'); + +/** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ +function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, baseIteratee(predicate, 3), true, true) + : []; +} + +module.exports = dropRightWhile; diff --git a/node_modules/lodash/dropWhile.js b/node_modules/lodash/dropWhile.js new file mode 100644 index 0000000..903ef56 --- /dev/null +++ b/node_modules/lodash/dropWhile.js @@ -0,0 +1,45 @@ +var baseIteratee = require('./_baseIteratee'), + baseWhile = require('./_baseWhile'); + +/** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ +function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, baseIteratee(predicate, 3), true) + : []; +} + +module.exports = dropWhile; diff --git a/node_modules/lodash/each.js b/node_modules/lodash/each.js new file mode 100644 index 0000000..8800f42 --- /dev/null +++ b/node_modules/lodash/each.js @@ -0,0 +1 @@ +module.exports = require('./forEach'); diff --git a/node_modules/lodash/eachRight.js b/node_modules/lodash/eachRight.js new file mode 100644 index 0000000..3252b2a --- /dev/null +++ b/node_modules/lodash/eachRight.js @@ -0,0 +1 @@ +module.exports = require('./forEachRight'); diff --git a/node_modules/lodash/endsWith.js b/node_modules/lodash/endsWith.js new file mode 100644 index 0000000..76fc866 --- /dev/null +++ b/node_modules/lodash/endsWith.js @@ -0,0 +1,43 @@ +var baseClamp = require('./_baseClamp'), + baseToString = require('./_baseToString'), + toInteger = require('./toInteger'), + toString = require('./toString'); + +/** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ +function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; +} + +module.exports = endsWith; diff --git a/node_modules/lodash/entries.js b/node_modules/lodash/entries.js new file mode 100644 index 0000000..7a88df2 --- /dev/null +++ b/node_modules/lodash/entries.js @@ -0,0 +1 @@ +module.exports = require('./toPairs'); diff --git a/node_modules/lodash/entriesIn.js b/node_modules/lodash/entriesIn.js new file mode 100644 index 0000000..f6c6331 --- /dev/null +++ b/node_modules/lodash/entriesIn.js @@ -0,0 +1 @@ +module.exports = require('./toPairsIn'); diff --git a/node_modules/lodash/eq.js b/node_modules/lodash/eq.js new file mode 100644 index 0000000..a940688 --- /dev/null +++ b/node_modules/lodash/eq.js @@ -0,0 +1,37 @@ +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +module.exports = eq; diff --git a/node_modules/lodash/escape.js b/node_modules/lodash/escape.js new file mode 100644 index 0000000..9247e00 --- /dev/null +++ b/node_modules/lodash/escape.js @@ -0,0 +1,43 @@ +var escapeHtmlChar = require('./_escapeHtmlChar'), + toString = require('./toString'); + +/** Used to match HTML entities and HTML characters. */ +var reUnescapedHtml = /[&<>"']/g, + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + +/** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ +function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; +} + +module.exports = escape; diff --git a/node_modules/lodash/escapeRegExp.js b/node_modules/lodash/escapeRegExp.js new file mode 100644 index 0000000..0a58c69 --- /dev/null +++ b/node_modules/lodash/escapeRegExp.js @@ -0,0 +1,32 @@ +var toString = require('./toString'); + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + +/** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ +function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; +} + +module.exports = escapeRegExp; diff --git a/node_modules/lodash/every.js b/node_modules/lodash/every.js new file mode 100644 index 0000000..25080da --- /dev/null +++ b/node_modules/lodash/every.js @@ -0,0 +1,56 @@ +var arrayEvery = require('./_arrayEvery'), + baseEvery = require('./_baseEvery'), + baseIteratee = require('./_baseIteratee'), + isArray = require('./isArray'), + isIterateeCall = require('./_isIterateeCall'); + +/** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ +function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, baseIteratee(predicate, 3)); +} + +module.exports = every; diff --git a/node_modules/lodash/extend.js b/node_modules/lodash/extend.js new file mode 100644 index 0000000..e00166c --- /dev/null +++ b/node_modules/lodash/extend.js @@ -0,0 +1 @@ +module.exports = require('./assignIn'); diff --git a/node_modules/lodash/extendWith.js b/node_modules/lodash/extendWith.js new file mode 100644 index 0000000..dbdcb3b --- /dev/null +++ b/node_modules/lodash/extendWith.js @@ -0,0 +1 @@ +module.exports = require('./assignInWith'); diff --git a/node_modules/lodash/fill.js b/node_modules/lodash/fill.js new file mode 100644 index 0000000..ae13aa1 --- /dev/null +++ b/node_modules/lodash/fill.js @@ -0,0 +1,45 @@ +var baseFill = require('./_baseFill'), + isIterateeCall = require('./_isIterateeCall'); + +/** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ +function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); +} + +module.exports = fill; diff --git a/node_modules/lodash/filter.js b/node_modules/lodash/filter.js new file mode 100644 index 0000000..89e0c8c --- /dev/null +++ b/node_modules/lodash/filter.js @@ -0,0 +1,52 @@ +var arrayFilter = require('./_arrayFilter'), + baseFilter = require('./_baseFilter'), + baseIteratee = require('./_baseIteratee'), + isArray = require('./isArray'); + +/** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + * + * // Combining several predicates using `_.overEvery` or `_.overSome`. + * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); + * // => objects for ['fred', 'barney'] + */ +function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, baseIteratee(predicate, 3)); +} + +module.exports = filter; diff --git a/node_modules/lodash/find.js b/node_modules/lodash/find.js new file mode 100644 index 0000000..de732cc --- /dev/null +++ b/node_modules/lodash/find.js @@ -0,0 +1,42 @@ +var createFind = require('./_createFind'), + findIndex = require('./findIndex'); + +/** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ +var find = createFind(findIndex); + +module.exports = find; diff --git a/node_modules/lodash/findIndex.js b/node_modules/lodash/findIndex.js new file mode 100644 index 0000000..4689069 --- /dev/null +++ b/node_modules/lodash/findIndex.js @@ -0,0 +1,55 @@ +var baseFindIndex = require('./_baseFindIndex'), + baseIteratee = require('./_baseIteratee'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ +function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, baseIteratee(predicate, 3), index); +} + +module.exports = findIndex; diff --git a/node_modules/lodash/findKey.js b/node_modules/lodash/findKey.js new file mode 100644 index 0000000..cac0248 --- /dev/null +++ b/node_modules/lodash/findKey.js @@ -0,0 +1,44 @@ +var baseFindKey = require('./_baseFindKey'), + baseForOwn = require('./_baseForOwn'), + baseIteratee = require('./_baseIteratee'); + +/** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ +function findKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate, 3), baseForOwn); +} + +module.exports = findKey; diff --git a/node_modules/lodash/findLast.js b/node_modules/lodash/findLast.js new file mode 100644 index 0000000..70b4271 --- /dev/null +++ b/node_modules/lodash/findLast.js @@ -0,0 +1,25 @@ +var createFind = require('./_createFind'), + findLastIndex = require('./findLastIndex'); + +/** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ +var findLast = createFind(findLastIndex); + +module.exports = findLast; diff --git a/node_modules/lodash/findLastIndex.js b/node_modules/lodash/findLastIndex.js new file mode 100644 index 0000000..7da3431 --- /dev/null +++ b/node_modules/lodash/findLastIndex.js @@ -0,0 +1,59 @@ +var baseFindIndex = require('./_baseFindIndex'), + baseIteratee = require('./_baseIteratee'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ +function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, baseIteratee(predicate, 3), index, true); +} + +module.exports = findLastIndex; diff --git a/node_modules/lodash/findLastKey.js b/node_modules/lodash/findLastKey.js new file mode 100644 index 0000000..66fb9fb --- /dev/null +++ b/node_modules/lodash/findLastKey.js @@ -0,0 +1,44 @@ +var baseFindKey = require('./_baseFindKey'), + baseForOwnRight = require('./_baseForOwnRight'), + baseIteratee = require('./_baseIteratee'); + +/** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ +function findLastKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate, 3), baseForOwnRight); +} + +module.exports = findLastKey; diff --git a/node_modules/lodash/first.js b/node_modules/lodash/first.js new file mode 100644 index 0000000..53f4ad1 --- /dev/null +++ b/node_modules/lodash/first.js @@ -0,0 +1 @@ +module.exports = require('./head'); diff --git a/node_modules/lodash/flatMap.js b/node_modules/lodash/flatMap.js new file mode 100644 index 0000000..e668506 --- /dev/null +++ b/node_modules/lodash/flatMap.js @@ -0,0 +1,29 @@ +var baseFlatten = require('./_baseFlatten'), + map = require('./map'); + +/** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ +function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); +} + +module.exports = flatMap; diff --git a/node_modules/lodash/flatMapDeep.js b/node_modules/lodash/flatMapDeep.js new file mode 100644 index 0000000..4653d60 --- /dev/null +++ b/node_modules/lodash/flatMapDeep.js @@ -0,0 +1,31 @@ +var baseFlatten = require('./_baseFlatten'), + map = require('./map'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ +function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); +} + +module.exports = flatMapDeep; diff --git a/node_modules/lodash/flatMapDepth.js b/node_modules/lodash/flatMapDepth.js new file mode 100644 index 0000000..6d72005 --- /dev/null +++ b/node_modules/lodash/flatMapDepth.js @@ -0,0 +1,31 @@ +var baseFlatten = require('./_baseFlatten'), + map = require('./map'), + toInteger = require('./toInteger'); + +/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ +function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); +} + +module.exports = flatMapDepth; diff --git a/node_modules/lodash/flatten.js b/node_modules/lodash/flatten.js new file mode 100644 index 0000000..3f09f7f --- /dev/null +++ b/node_modules/lodash/flatten.js @@ -0,0 +1,22 @@ +var baseFlatten = require('./_baseFlatten'); + +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ +function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; +} + +module.exports = flatten; diff --git a/node_modules/lodash/flattenDeep.js b/node_modules/lodash/flattenDeep.js new file mode 100644 index 0000000..8ad585c --- /dev/null +++ b/node_modules/lodash/flattenDeep.js @@ -0,0 +1,25 @@ +var baseFlatten = require('./_baseFlatten'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ +function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; +} + +module.exports = flattenDeep; diff --git a/node_modules/lodash/flattenDepth.js b/node_modules/lodash/flattenDepth.js new file mode 100644 index 0000000..441fdcc --- /dev/null +++ b/node_modules/lodash/flattenDepth.js @@ -0,0 +1,33 @@ +var baseFlatten = require('./_baseFlatten'), + toInteger = require('./toInteger'); + +/** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ +function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); +} + +module.exports = flattenDepth; diff --git a/node_modules/lodash/flip.js b/node_modules/lodash/flip.js new file mode 100644 index 0000000..c28dd78 --- /dev/null +++ b/node_modules/lodash/flip.js @@ -0,0 +1,28 @@ +var createWrap = require('./_createWrap'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_FLIP_FLAG = 512; + +/** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ +function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); +} + +module.exports = flip; diff --git a/node_modules/lodash/floor.js b/node_modules/lodash/floor.js new file mode 100644 index 0000000..ab6dfa2 --- /dev/null +++ b/node_modules/lodash/floor.js @@ -0,0 +1,26 @@ +var createRound = require('./_createRound'); + +/** + * Computes `number` rounded down to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round down. + * @param {number} [precision=0] The precision to round down to. + * @returns {number} Returns the rounded down number. + * @example + * + * _.floor(4.006); + * // => 4 + * + * _.floor(0.046, 2); + * // => 0.04 + * + * _.floor(4060, -2); + * // => 4000 + */ +var floor = createRound('floor'); + +module.exports = floor; diff --git a/node_modules/lodash/flow.js b/node_modules/lodash/flow.js new file mode 100644 index 0000000..74b6b62 --- /dev/null +++ b/node_modules/lodash/flow.js @@ -0,0 +1,27 @@ +var createFlow = require('./_createFlow'); + +/** + * Creates a function that returns the result of invoking the given functions + * with the `this` binding of the created function, where each successive + * invocation is supplied the return value of the previous. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {...(Function|Function[])} [funcs] The functions to invoke. + * @returns {Function} Returns the new composite function. + * @see _.flowRight + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flow([_.add, square]); + * addSquare(1, 2); + * // => 9 + */ +var flow = createFlow(); + +module.exports = flow; diff --git a/node_modules/lodash/flowRight.js b/node_modules/lodash/flowRight.js new file mode 100644 index 0000000..1146141 --- /dev/null +++ b/node_modules/lodash/flowRight.js @@ -0,0 +1,26 @@ +var createFlow = require('./_createFlow'); + +/** + * This method is like `_.flow` except that it creates a function that + * invokes the given functions from right to left. + * + * @static + * @since 3.0.0 + * @memberOf _ + * @category Util + * @param {...(Function|Function[])} [funcs] The functions to invoke. + * @returns {Function} Returns the new composite function. + * @see _.flow + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flowRight([square, _.add]); + * addSquare(1, 2); + * // => 9 + */ +var flowRight = createFlow(true); + +module.exports = flowRight; diff --git a/node_modules/lodash/forEach.js b/node_modules/lodash/forEach.js new file mode 100644 index 0000000..c64eaa7 --- /dev/null +++ b/node_modules/lodash/forEach.js @@ -0,0 +1,41 @@ +var arrayEach = require('./_arrayEach'), + baseEach = require('./_baseEach'), + castFunction = require('./_castFunction'), + isArray = require('./isArray'); + +/** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ +function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, castFunction(iteratee)); +} + +module.exports = forEach; diff --git a/node_modules/lodash/forEachRight.js b/node_modules/lodash/forEachRight.js new file mode 100644 index 0000000..7390eba --- /dev/null +++ b/node_modules/lodash/forEachRight.js @@ -0,0 +1,31 @@ +var arrayEachRight = require('./_arrayEachRight'), + baseEachRight = require('./_baseEachRight'), + castFunction = require('./_castFunction'), + isArray = require('./isArray'); + +/** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ +function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, castFunction(iteratee)); +} + +module.exports = forEachRight; diff --git a/node_modules/lodash/forIn.js b/node_modules/lodash/forIn.js new file mode 100644 index 0000000..583a596 --- /dev/null +++ b/node_modules/lodash/forIn.js @@ -0,0 +1,39 @@ +var baseFor = require('./_baseFor'), + castFunction = require('./_castFunction'), + keysIn = require('./keysIn'); + +/** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ +function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, castFunction(iteratee), keysIn); +} + +module.exports = forIn; diff --git a/node_modules/lodash/forInRight.js b/node_modules/lodash/forInRight.js new file mode 100644 index 0000000..4aedf58 --- /dev/null +++ b/node_modules/lodash/forInRight.js @@ -0,0 +1,37 @@ +var baseForRight = require('./_baseForRight'), + castFunction = require('./_castFunction'), + keysIn = require('./keysIn'); + +/** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ +function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, castFunction(iteratee), keysIn); +} + +module.exports = forInRight; diff --git a/node_modules/lodash/forOwn.js b/node_modules/lodash/forOwn.js new file mode 100644 index 0000000..94eed84 --- /dev/null +++ b/node_modules/lodash/forOwn.js @@ -0,0 +1,36 @@ +var baseForOwn = require('./_baseForOwn'), + castFunction = require('./_castFunction'); + +/** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ +function forOwn(object, iteratee) { + return object && baseForOwn(object, castFunction(iteratee)); +} + +module.exports = forOwn; diff --git a/node_modules/lodash/forOwnRight.js b/node_modules/lodash/forOwnRight.js new file mode 100644 index 0000000..86f338f --- /dev/null +++ b/node_modules/lodash/forOwnRight.js @@ -0,0 +1,34 @@ +var baseForOwnRight = require('./_baseForOwnRight'), + castFunction = require('./_castFunction'); + +/** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ +function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, castFunction(iteratee)); +} + +module.exports = forOwnRight; diff --git a/node_modules/lodash/fp.js b/node_modules/lodash/fp.js new file mode 100644 index 0000000..e372dbb --- /dev/null +++ b/node_modules/lodash/fp.js @@ -0,0 +1,2 @@ +var _ = require('./lodash.min').runInContext(); +module.exports = require('./fp/_baseConvert')(_, _); diff --git a/node_modules/lodash/fp/F.js b/node_modules/lodash/fp/F.js new file mode 100644 index 0000000..a05a63a --- /dev/null +++ b/node_modules/lodash/fp/F.js @@ -0,0 +1 @@ +module.exports = require('./stubFalse'); diff --git a/node_modules/lodash/fp/T.js b/node_modules/lodash/fp/T.js new file mode 100644 index 0000000..e2ba8ea --- /dev/null +++ b/node_modules/lodash/fp/T.js @@ -0,0 +1 @@ +module.exports = require('./stubTrue'); diff --git a/node_modules/lodash/fp/__.js b/node_modules/lodash/fp/__.js new file mode 100644 index 0000000..4af98de --- /dev/null +++ b/node_modules/lodash/fp/__.js @@ -0,0 +1 @@ +module.exports = require('./placeholder'); diff --git a/node_modules/lodash/fp/_baseConvert.js b/node_modules/lodash/fp/_baseConvert.js new file mode 100644 index 0000000..9baf8e1 --- /dev/null +++ b/node_modules/lodash/fp/_baseConvert.js @@ -0,0 +1,569 @@ +var mapping = require('./_mapping'), + fallbackHolder = require('./placeholder'); + +/** Built-in value reference. */ +var push = Array.prototype.push; + +/** + * Creates a function, with an arity of `n`, that invokes `func` with the + * arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} n The arity of the new function. + * @returns {Function} Returns the new function. + */ +function baseArity(func, n) { + return n == 2 + ? function(a, b) { return func.apply(undefined, arguments); } + : function(a) { return func.apply(undefined, arguments); }; +} + +/** + * Creates a function that invokes `func`, with up to `n` arguments, ignoring + * any additional arguments. + * + * @private + * @param {Function} func The function to cap arguments for. + * @param {number} n The arity cap. + * @returns {Function} Returns the new function. + */ +function baseAry(func, n) { + return n == 2 + ? function(a, b) { return func(a, b); } + : function(a) { return func(a); }; +} + +/** + * Creates a clone of `array`. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the cloned array. + */ +function cloneArray(array) { + var length = array ? array.length : 0, + result = Array(length); + + while (length--) { + result[length] = array[length]; + } + return result; +} + +/** + * Creates a function that clones a given object using the assignment `func`. + * + * @private + * @param {Function} func The assignment function. + * @returns {Function} Returns the new cloner function. + */ +function createCloner(func) { + return function(object) { + return func({}, object); + }; +} + +/** + * A specialized version of `_.spread` which flattens the spread array into + * the arguments of the invoked `func`. + * + * @private + * @param {Function} func The function to spread arguments over. + * @param {number} start The start position of the spread. + * @returns {Function} Returns the new function. + */ +function flatSpread(func, start) { + return function() { + var length = arguments.length, + lastIndex = length - 1, + args = Array(length); + + while (length--) { + args[length] = arguments[length]; + } + var array = args[start], + otherArgs = args.slice(0, start); + + if (array) { + push.apply(otherArgs, array); + } + if (start != lastIndex) { + push.apply(otherArgs, args.slice(start + 1)); + } + return func.apply(this, otherArgs); + }; +} + +/** + * Creates a function that wraps `func` and uses `cloner` to clone the first + * argument it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} cloner The function to clone arguments. + * @returns {Function} Returns the new immutable function. + */ +function wrapImmutable(func, cloner) { + return function() { + var length = arguments.length; + if (!length) { + return; + } + var args = Array(length); + while (length--) { + args[length] = arguments[length]; + } + var result = args[0] = cloner.apply(undefined, args); + func.apply(undefined, args); + return result; + }; +} + +/** + * The base implementation of `convert` which accepts a `util` object of methods + * required to perform conversions. + * + * @param {Object} util The util object. + * @param {string} name The name of the function to convert. + * @param {Function} func The function to convert. + * @param {Object} [options] The options object. + * @param {boolean} [options.cap=true] Specify capping iteratee arguments. + * @param {boolean} [options.curry=true] Specify currying. + * @param {boolean} [options.fixed=true] Specify fixed arity. + * @param {boolean} [options.immutable=true] Specify immutable operations. + * @param {boolean} [options.rearg=true] Specify rearranging arguments. + * @returns {Function|Object} Returns the converted function or object. + */ +function baseConvert(util, name, func, options) { + var isLib = typeof name == 'function', + isObj = name === Object(name); + + if (isObj) { + options = func; + func = name; + name = undefined; + } + if (func == null) { + throw new TypeError; + } + options || (options = {}); + + var config = { + 'cap': 'cap' in options ? options.cap : true, + 'curry': 'curry' in options ? options.curry : true, + 'fixed': 'fixed' in options ? options.fixed : true, + 'immutable': 'immutable' in options ? options.immutable : true, + 'rearg': 'rearg' in options ? options.rearg : true + }; + + var defaultHolder = isLib ? func : fallbackHolder, + forceCurry = ('curry' in options) && options.curry, + forceFixed = ('fixed' in options) && options.fixed, + forceRearg = ('rearg' in options) && options.rearg, + pristine = isLib ? func.runInContext() : undefined; + + var helpers = isLib ? func : { + 'ary': util.ary, + 'assign': util.assign, + 'clone': util.clone, + 'curry': util.curry, + 'forEach': util.forEach, + 'isArray': util.isArray, + 'isError': util.isError, + 'isFunction': util.isFunction, + 'isWeakMap': util.isWeakMap, + 'iteratee': util.iteratee, + 'keys': util.keys, + 'rearg': util.rearg, + 'toInteger': util.toInteger, + 'toPath': util.toPath + }; + + var ary = helpers.ary, + assign = helpers.assign, + clone = helpers.clone, + curry = helpers.curry, + each = helpers.forEach, + isArray = helpers.isArray, + isError = helpers.isError, + isFunction = helpers.isFunction, + isWeakMap = helpers.isWeakMap, + keys = helpers.keys, + rearg = helpers.rearg, + toInteger = helpers.toInteger, + toPath = helpers.toPath; + + var aryMethodKeys = keys(mapping.aryMethod); + + var wrappers = { + 'castArray': function(castArray) { + return function() { + var value = arguments[0]; + return isArray(value) + ? castArray(cloneArray(value)) + : castArray.apply(undefined, arguments); + }; + }, + 'iteratee': function(iteratee) { + return function() { + var func = arguments[0], + arity = arguments[1], + result = iteratee(func, arity), + length = result.length; + + if (config.cap && typeof arity == 'number') { + arity = arity > 2 ? (arity - 2) : 1; + return (length && length <= arity) ? result : baseAry(result, arity); + } + return result; + }; + }, + 'mixin': function(mixin) { + return function(source) { + var func = this; + if (!isFunction(func)) { + return mixin(func, Object(source)); + } + var pairs = []; + each(keys(source), function(key) { + if (isFunction(source[key])) { + pairs.push([key, func.prototype[key]]); + } + }); + + mixin(func, Object(source)); + + each(pairs, function(pair) { + var value = pair[1]; + if (isFunction(value)) { + func.prototype[pair[0]] = value; + } else { + delete func.prototype[pair[0]]; + } + }); + return func; + }; + }, + 'nthArg': function(nthArg) { + return function(n) { + var arity = n < 0 ? 1 : (toInteger(n) + 1); + return curry(nthArg(n), arity); + }; + }, + 'rearg': function(rearg) { + return function(func, indexes) { + var arity = indexes ? indexes.length : 0; + return curry(rearg(func, indexes), arity); + }; + }, + 'runInContext': function(runInContext) { + return function(context) { + return baseConvert(util, runInContext(context), options); + }; + } + }; + + /*--------------------------------------------------------------------------*/ + + /** + * Casts `func` to a function with an arity capped iteratee if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @returns {Function} Returns the cast function. + */ + function castCap(name, func) { + if (config.cap) { + var indexes = mapping.iterateeRearg[name]; + if (indexes) { + return iterateeRearg(func, indexes); + } + var n = !isLib && mapping.iterateeAry[name]; + if (n) { + return iterateeAry(func, n); + } + } + return func; + } + + /** + * Casts `func` to a curried function if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @param {number} n The arity of `func`. + * @returns {Function} Returns the cast function. + */ + function castCurry(name, func, n) { + return (forceCurry || (config.curry && n > 1)) + ? curry(func, n) + : func; + } + + /** + * Casts `func` to a fixed arity function if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @param {number} n The arity cap. + * @returns {Function} Returns the cast function. + */ + function castFixed(name, func, n) { + if (config.fixed && (forceFixed || !mapping.skipFixed[name])) { + var data = mapping.methodSpread[name], + start = data && data.start; + + return start === undefined ? ary(func, n) : flatSpread(func, start); + } + return func; + } + + /** + * Casts `func` to an rearged function if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @param {number} n The arity of `func`. + * @returns {Function} Returns the cast function. + */ + function castRearg(name, func, n) { + return (config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name])) + ? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n]) + : func; + } + + /** + * Creates a clone of `object` by `path`. + * + * @private + * @param {Object} object The object to clone. + * @param {Array|string} path The path to clone by. + * @returns {Object} Returns the cloned object. + */ + function cloneByPath(object, path) { + path = toPath(path); + + var index = -1, + length = path.length, + lastIndex = length - 1, + result = clone(Object(object)), + nested = result; + + while (nested != null && ++index < length) { + var key = path[index], + value = nested[key]; + + if (value != null && + !(isFunction(value) || isError(value) || isWeakMap(value))) { + nested[key] = clone(index == lastIndex ? value : Object(value)); + } + nested = nested[key]; + } + return result; + } + + /** + * Converts `lodash` to an immutable auto-curried iteratee-first data-last + * version with conversion `options` applied. + * + * @param {Object} [options] The options object. See `baseConvert` for more details. + * @returns {Function} Returns the converted `lodash`. + */ + function convertLib(options) { + return _.runInContext.convert(options)(undefined); + } + + /** + * Create a converter function for `func` of `name`. + * + * @param {string} name The name of the function to convert. + * @param {Function} func The function to convert. + * @returns {Function} Returns the new converter function. + */ + function createConverter(name, func) { + var realName = mapping.aliasToReal[name] || name, + methodName = mapping.remap[realName] || realName, + oldOptions = options; + + return function(options) { + var newUtil = isLib ? pristine : helpers, + newFunc = isLib ? pristine[methodName] : func, + newOptions = assign(assign({}, oldOptions), options); + + return baseConvert(newUtil, realName, newFunc, newOptions); + }; + } + + /** + * Creates a function that wraps `func` to invoke its iteratee, with up to `n` + * arguments, ignoring any additional arguments. + * + * @private + * @param {Function} func The function to cap iteratee arguments for. + * @param {number} n The arity cap. + * @returns {Function} Returns the new function. + */ + function iterateeAry(func, n) { + return overArg(func, function(func) { + return typeof func == 'function' ? baseAry(func, n) : func; + }); + } + + /** + * Creates a function that wraps `func` to invoke its iteratee with arguments + * arranged according to the specified `indexes` where the argument value at + * the first index is provided as the first argument, the argument value at + * the second index is provided as the second argument, and so on. + * + * @private + * @param {Function} func The function to rearrange iteratee arguments for. + * @param {number[]} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + */ + function iterateeRearg(func, indexes) { + return overArg(func, function(func) { + var n = indexes.length; + return baseArity(rearg(baseAry(func, n), indexes), n); + }); + } + + /** + * Creates a function that invokes `func` with its first argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function() { + var length = arguments.length; + if (!length) { + return func(); + } + var args = Array(length); + while (length--) { + args[length] = arguments[length]; + } + var index = config.rearg ? 0 : (length - 1); + args[index] = transform(args[index]); + return func.apply(undefined, args); + }; + } + + /** + * Creates a function that wraps `func` and applys the conversions + * rules by `name`. + * + * @private + * @param {string} name The name of the function to wrap. + * @param {Function} func The function to wrap. + * @returns {Function} Returns the converted function. + */ + function wrap(name, func, placeholder) { + var result, + realName = mapping.aliasToReal[name] || name, + wrapped = func, + wrapper = wrappers[realName]; + + if (wrapper) { + wrapped = wrapper(func); + } + else if (config.immutable) { + if (mapping.mutate.array[realName]) { + wrapped = wrapImmutable(func, cloneArray); + } + else if (mapping.mutate.object[realName]) { + wrapped = wrapImmutable(func, createCloner(func)); + } + else if (mapping.mutate.set[realName]) { + wrapped = wrapImmutable(func, cloneByPath); + } + } + each(aryMethodKeys, function(aryKey) { + each(mapping.aryMethod[aryKey], function(otherName) { + if (realName == otherName) { + var data = mapping.methodSpread[realName], + afterRearg = data && data.afterRearg; + + result = afterRearg + ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey) + : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey); + + result = castCap(realName, result); + result = castCurry(realName, result, aryKey); + return false; + } + }); + return !result; + }); + + result || (result = wrapped); + if (result == func) { + result = forceCurry ? curry(result, 1) : function() { + return func.apply(this, arguments); + }; + } + result.convert = createConverter(realName, func); + result.placeholder = func.placeholder = placeholder; + + return result; + } + + /*--------------------------------------------------------------------------*/ + + if (!isObj) { + return wrap(name, func, defaultHolder); + } + var _ = func; + + // Convert methods by ary cap. + var pairs = []; + each(aryMethodKeys, function(aryKey) { + each(mapping.aryMethod[aryKey], function(key) { + var func = _[mapping.remap[key] || key]; + if (func) { + pairs.push([key, wrap(key, func, _)]); + } + }); + }); + + // Convert remaining methods. + each(keys(_), function(key) { + var func = _[key]; + if (typeof func == 'function') { + var length = pairs.length; + while (length--) { + if (pairs[length][0] == key) { + return; + } + } + func.convert = createConverter(key, func); + pairs.push([key, func]); + } + }); + + // Assign to `_` leaving `_.prototype` unchanged to allow chaining. + each(pairs, function(pair) { + _[pair[0]] = pair[1]; + }); + + _.convert = convertLib; + _.placeholder = _; + + // Assign aliases. + each(keys(_), function(key) { + each(mapping.realToAlias[key] || [], function(alias) { + _[alias] = _[key]; + }); + }); + + return _; +} + +module.exports = baseConvert; diff --git a/node_modules/lodash/fp/_convertBrowser.js b/node_modules/lodash/fp/_convertBrowser.js new file mode 100644 index 0000000..bde030d --- /dev/null +++ b/node_modules/lodash/fp/_convertBrowser.js @@ -0,0 +1,18 @@ +var baseConvert = require('./_baseConvert'); + +/** + * Converts `lodash` to an immutable auto-curried iteratee-first data-last + * version with conversion `options` applied. + * + * @param {Function} lodash The lodash function to convert. + * @param {Object} [options] The options object. See `baseConvert` for more details. + * @returns {Function} Returns the converted `lodash`. + */ +function browserConvert(lodash, options) { + return baseConvert(lodash, lodash, options); +} + +if (typeof _ == 'function' && typeof _.runInContext == 'function') { + _ = browserConvert(_.runInContext()); +} +module.exports = browserConvert; diff --git a/node_modules/lodash/fp/_falseOptions.js b/node_modules/lodash/fp/_falseOptions.js new file mode 100644 index 0000000..773235e --- /dev/null +++ b/node_modules/lodash/fp/_falseOptions.js @@ -0,0 +1,7 @@ +module.exports = { + 'cap': false, + 'curry': false, + 'fixed': false, + 'immutable': false, + 'rearg': false +}; diff --git a/node_modules/lodash/fp/_mapping.js b/node_modules/lodash/fp/_mapping.js new file mode 100644 index 0000000..a642ec0 --- /dev/null +++ b/node_modules/lodash/fp/_mapping.js @@ -0,0 +1,358 @@ +/** Used to map aliases to their real names. */ +exports.aliasToReal = { + + // Lodash aliases. + 'each': 'forEach', + 'eachRight': 'forEachRight', + 'entries': 'toPairs', + 'entriesIn': 'toPairsIn', + 'extend': 'assignIn', + 'extendAll': 'assignInAll', + 'extendAllWith': 'assignInAllWith', + 'extendWith': 'assignInWith', + 'first': 'head', + + // Methods that are curried variants of others. + 'conforms': 'conformsTo', + 'matches': 'isMatch', + 'property': 'get', + + // Ramda aliases. + '__': 'placeholder', + 'F': 'stubFalse', + 'T': 'stubTrue', + 'all': 'every', + 'allPass': 'overEvery', + 'always': 'constant', + 'any': 'some', + 'anyPass': 'overSome', + 'apply': 'spread', + 'assoc': 'set', + 'assocPath': 'set', + 'complement': 'negate', + 'compose': 'flowRight', + 'contains': 'includes', + 'dissoc': 'unset', + 'dissocPath': 'unset', + 'dropLast': 'dropRight', + 'dropLastWhile': 'dropRightWhile', + 'equals': 'isEqual', + 'identical': 'eq', + 'indexBy': 'keyBy', + 'init': 'initial', + 'invertObj': 'invert', + 'juxt': 'over', + 'omitAll': 'omit', + 'nAry': 'ary', + 'path': 'get', + 'pathEq': 'matchesProperty', + 'pathOr': 'getOr', + 'paths': 'at', + 'pickAll': 'pick', + 'pipe': 'flow', + 'pluck': 'map', + 'prop': 'get', + 'propEq': 'matchesProperty', + 'propOr': 'getOr', + 'props': 'at', + 'symmetricDifference': 'xor', + 'symmetricDifferenceBy': 'xorBy', + 'symmetricDifferenceWith': 'xorWith', + 'takeLast': 'takeRight', + 'takeLastWhile': 'takeRightWhile', + 'unapply': 'rest', + 'unnest': 'flatten', + 'useWith': 'overArgs', + 'where': 'conformsTo', + 'whereEq': 'isMatch', + 'zipObj': 'zipObject' +}; + +/** Used to map ary to method names. */ +exports.aryMethod = { + '1': [ + 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create', + 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow', + 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll', + 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse', + 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart', + 'uniqueId', 'words', 'zipAll' + ], + '2': [ + 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith', + 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith', + 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN', + 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference', + 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq', + 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', + 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach', + 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get', + 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection', + 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy', + 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty', + 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit', + 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial', + 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll', + 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove', + 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex', + 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy', + 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight', + 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars', + 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith', + 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject', + 'zipObjectDeep' + ], + '3': [ + 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith', + 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr', + 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith', + 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth', + 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd', + 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight', + 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy', + 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy', + 'xorWith', 'zipWith' + ], + '4': [ + 'fill', 'setWith', 'updateWith' + ] +}; + +/** Used to map ary to rearg configs. */ +exports.aryRearg = { + '2': [1, 0], + '3': [2, 0, 1], + '4': [3, 2, 0, 1] +}; + +/** Used to map method names to their iteratee ary. */ +exports.iterateeAry = { + 'dropRightWhile': 1, + 'dropWhile': 1, + 'every': 1, + 'filter': 1, + 'find': 1, + 'findFrom': 1, + 'findIndex': 1, + 'findIndexFrom': 1, + 'findKey': 1, + 'findLast': 1, + 'findLastFrom': 1, + 'findLastIndex': 1, + 'findLastIndexFrom': 1, + 'findLastKey': 1, + 'flatMap': 1, + 'flatMapDeep': 1, + 'flatMapDepth': 1, + 'forEach': 1, + 'forEachRight': 1, + 'forIn': 1, + 'forInRight': 1, + 'forOwn': 1, + 'forOwnRight': 1, + 'map': 1, + 'mapKeys': 1, + 'mapValues': 1, + 'partition': 1, + 'reduce': 2, + 'reduceRight': 2, + 'reject': 1, + 'remove': 1, + 'some': 1, + 'takeRightWhile': 1, + 'takeWhile': 1, + 'times': 1, + 'transform': 2 +}; + +/** Used to map method names to iteratee rearg configs. */ +exports.iterateeRearg = { + 'mapKeys': [1], + 'reduceRight': [1, 0] +}; + +/** Used to map method names to rearg configs. */ +exports.methodRearg = { + 'assignInAllWith': [1, 0], + 'assignInWith': [1, 2, 0], + 'assignAllWith': [1, 0], + 'assignWith': [1, 2, 0], + 'differenceBy': [1, 2, 0], + 'differenceWith': [1, 2, 0], + 'getOr': [2, 1, 0], + 'intersectionBy': [1, 2, 0], + 'intersectionWith': [1, 2, 0], + 'isEqualWith': [1, 2, 0], + 'isMatchWith': [2, 1, 0], + 'mergeAllWith': [1, 0], + 'mergeWith': [1, 2, 0], + 'padChars': [2, 1, 0], + 'padCharsEnd': [2, 1, 0], + 'padCharsStart': [2, 1, 0], + 'pullAllBy': [2, 1, 0], + 'pullAllWith': [2, 1, 0], + 'rangeStep': [1, 2, 0], + 'rangeStepRight': [1, 2, 0], + 'setWith': [3, 1, 2, 0], + 'sortedIndexBy': [2, 1, 0], + 'sortedLastIndexBy': [2, 1, 0], + 'unionBy': [1, 2, 0], + 'unionWith': [1, 2, 0], + 'updateWith': [3, 1, 2, 0], + 'xorBy': [1, 2, 0], + 'xorWith': [1, 2, 0], + 'zipWith': [1, 2, 0] +}; + +/** Used to map method names to spread configs. */ +exports.methodSpread = { + 'assignAll': { 'start': 0 }, + 'assignAllWith': { 'start': 0 }, + 'assignInAll': { 'start': 0 }, + 'assignInAllWith': { 'start': 0 }, + 'defaultsAll': { 'start': 0 }, + 'defaultsDeepAll': { 'start': 0 }, + 'invokeArgs': { 'start': 2 }, + 'invokeArgsMap': { 'start': 2 }, + 'mergeAll': { 'start': 0 }, + 'mergeAllWith': { 'start': 0 }, + 'partial': { 'start': 1 }, + 'partialRight': { 'start': 1 }, + 'without': { 'start': 1 }, + 'zipAll': { 'start': 0 } +}; + +/** Used to identify methods which mutate arrays or objects. */ +exports.mutate = { + 'array': { + 'fill': true, + 'pull': true, + 'pullAll': true, + 'pullAllBy': true, + 'pullAllWith': true, + 'pullAt': true, + 'remove': true, + 'reverse': true + }, + 'object': { + 'assign': true, + 'assignAll': true, + 'assignAllWith': true, + 'assignIn': true, + 'assignInAll': true, + 'assignInAllWith': true, + 'assignInWith': true, + 'assignWith': true, + 'defaults': true, + 'defaultsAll': true, + 'defaultsDeep': true, + 'defaultsDeepAll': true, + 'merge': true, + 'mergeAll': true, + 'mergeAllWith': true, + 'mergeWith': true, + }, + 'set': { + 'set': true, + 'setWith': true, + 'unset': true, + 'update': true, + 'updateWith': true + } +}; + +/** Used to map real names to their aliases. */ +exports.realToAlias = (function() { + var hasOwnProperty = Object.prototype.hasOwnProperty, + object = exports.aliasToReal, + result = {}; + + for (var key in object) { + var value = object[key]; + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + } + return result; +}()); + +/** Used to map method names to other names. */ +exports.remap = { + 'assignAll': 'assign', + 'assignAllWith': 'assignWith', + 'assignInAll': 'assignIn', + 'assignInAllWith': 'assignInWith', + 'curryN': 'curry', + 'curryRightN': 'curryRight', + 'defaultsAll': 'defaults', + 'defaultsDeepAll': 'defaultsDeep', + 'findFrom': 'find', + 'findIndexFrom': 'findIndex', + 'findLastFrom': 'findLast', + 'findLastIndexFrom': 'findLastIndex', + 'getOr': 'get', + 'includesFrom': 'includes', + 'indexOfFrom': 'indexOf', + 'invokeArgs': 'invoke', + 'invokeArgsMap': 'invokeMap', + 'lastIndexOfFrom': 'lastIndexOf', + 'mergeAll': 'merge', + 'mergeAllWith': 'mergeWith', + 'padChars': 'pad', + 'padCharsEnd': 'padEnd', + 'padCharsStart': 'padStart', + 'propertyOf': 'get', + 'rangeStep': 'range', + 'rangeStepRight': 'rangeRight', + 'restFrom': 'rest', + 'spreadFrom': 'spread', + 'trimChars': 'trim', + 'trimCharsEnd': 'trimEnd', + 'trimCharsStart': 'trimStart', + 'zipAll': 'zip' +}; + +/** Used to track methods that skip fixing their arity. */ +exports.skipFixed = { + 'castArray': true, + 'flow': true, + 'flowRight': true, + 'iteratee': true, + 'mixin': true, + 'rearg': true, + 'runInContext': true +}; + +/** Used to track methods that skip rearranging arguments. */ +exports.skipRearg = { + 'add': true, + 'assign': true, + 'assignIn': true, + 'bind': true, + 'bindKey': true, + 'concat': true, + 'difference': true, + 'divide': true, + 'eq': true, + 'gt': true, + 'gte': true, + 'isEqual': true, + 'lt': true, + 'lte': true, + 'matchesProperty': true, + 'merge': true, + 'multiply': true, + 'overArgs': true, + 'partial': true, + 'partialRight': true, + 'propertyOf': true, + 'random': true, + 'range': true, + 'rangeRight': true, + 'subtract': true, + 'zip': true, + 'zipObject': true, + 'zipObjectDeep': true +}; diff --git a/node_modules/lodash/fp/_util.js b/node_modules/lodash/fp/_util.js new file mode 100644 index 0000000..1dbf36f --- /dev/null +++ b/node_modules/lodash/fp/_util.js @@ -0,0 +1,16 @@ +module.exports = { + 'ary': require('../ary'), + 'assign': require('../_baseAssign'), + 'clone': require('../clone'), + 'curry': require('../curry'), + 'forEach': require('../_arrayEach'), + 'isArray': require('../isArray'), + 'isError': require('../isError'), + 'isFunction': require('../isFunction'), + 'isWeakMap': require('../isWeakMap'), + 'iteratee': require('../iteratee'), + 'keys': require('../_baseKeys'), + 'rearg': require('../rearg'), + 'toInteger': require('../toInteger'), + 'toPath': require('../toPath') +}; diff --git a/node_modules/lodash/fp/add.js b/node_modules/lodash/fp/add.js new file mode 100644 index 0000000..816eeec --- /dev/null +++ b/node_modules/lodash/fp/add.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('add', require('../add')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/after.js b/node_modules/lodash/fp/after.js new file mode 100644 index 0000000..21a0167 --- /dev/null +++ b/node_modules/lodash/fp/after.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('after', require('../after')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/all.js b/node_modules/lodash/fp/all.js new file mode 100644 index 0000000..d0839f7 --- /dev/null +++ b/node_modules/lodash/fp/all.js @@ -0,0 +1 @@ +module.exports = require('./every'); diff --git a/node_modules/lodash/fp/allPass.js b/node_modules/lodash/fp/allPass.js new file mode 100644 index 0000000..79b73ef --- /dev/null +++ b/node_modules/lodash/fp/allPass.js @@ -0,0 +1 @@ +module.exports = require('./overEvery'); diff --git a/node_modules/lodash/fp/always.js b/node_modules/lodash/fp/always.js new file mode 100644 index 0000000..9887703 --- /dev/null +++ b/node_modules/lodash/fp/always.js @@ -0,0 +1 @@ +module.exports = require('./constant'); diff --git a/node_modules/lodash/fp/any.js b/node_modules/lodash/fp/any.js new file mode 100644 index 0000000..900ac25 --- /dev/null +++ b/node_modules/lodash/fp/any.js @@ -0,0 +1 @@ +module.exports = require('./some'); diff --git a/node_modules/lodash/fp/anyPass.js b/node_modules/lodash/fp/anyPass.js new file mode 100644 index 0000000..2774ab3 --- /dev/null +++ b/node_modules/lodash/fp/anyPass.js @@ -0,0 +1 @@ +module.exports = require('./overSome'); diff --git a/node_modules/lodash/fp/apply.js b/node_modules/lodash/fp/apply.js new file mode 100644 index 0000000..2b75712 --- /dev/null +++ b/node_modules/lodash/fp/apply.js @@ -0,0 +1 @@ +module.exports = require('./spread'); diff --git a/node_modules/lodash/fp/array.js b/node_modules/lodash/fp/array.js new file mode 100644 index 0000000..fe939c2 --- /dev/null +++ b/node_modules/lodash/fp/array.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../array')); diff --git a/node_modules/lodash/fp/ary.js b/node_modules/lodash/fp/ary.js new file mode 100644 index 0000000..8edf187 --- /dev/null +++ b/node_modules/lodash/fp/ary.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('ary', require('../ary')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assign.js b/node_modules/lodash/fp/assign.js new file mode 100644 index 0000000..23f47af --- /dev/null +++ b/node_modules/lodash/fp/assign.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assign', require('../assign')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignAll.js b/node_modules/lodash/fp/assignAll.js new file mode 100644 index 0000000..b1d36c7 --- /dev/null +++ b/node_modules/lodash/fp/assignAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignAll', require('../assign')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignAllWith.js b/node_modules/lodash/fp/assignAllWith.js new file mode 100644 index 0000000..21e836e --- /dev/null +++ b/node_modules/lodash/fp/assignAllWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignAllWith', require('../assignWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignIn.js b/node_modules/lodash/fp/assignIn.js new file mode 100644 index 0000000..6e7c65f --- /dev/null +++ b/node_modules/lodash/fp/assignIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignIn', require('../assignIn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignInAll.js b/node_modules/lodash/fp/assignInAll.js new file mode 100644 index 0000000..7ba75db --- /dev/null +++ b/node_modules/lodash/fp/assignInAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignInAll', require('../assignIn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignInAllWith.js b/node_modules/lodash/fp/assignInAllWith.js new file mode 100644 index 0000000..e766903 --- /dev/null +++ b/node_modules/lodash/fp/assignInAllWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignInAllWith', require('../assignInWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignInWith.js b/node_modules/lodash/fp/assignInWith.js new file mode 100644 index 0000000..acb5923 --- /dev/null +++ b/node_modules/lodash/fp/assignInWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignInWith', require('../assignInWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignWith.js b/node_modules/lodash/fp/assignWith.js new file mode 100644 index 0000000..eb92521 --- /dev/null +++ b/node_modules/lodash/fp/assignWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignWith', require('../assignWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assoc.js b/node_modules/lodash/fp/assoc.js new file mode 100644 index 0000000..7648820 --- /dev/null +++ b/node_modules/lodash/fp/assoc.js @@ -0,0 +1 @@ +module.exports = require('./set'); diff --git a/node_modules/lodash/fp/assocPath.js b/node_modules/lodash/fp/assocPath.js new file mode 100644 index 0000000..7648820 --- /dev/null +++ b/node_modules/lodash/fp/assocPath.js @@ -0,0 +1 @@ +module.exports = require('./set'); diff --git a/node_modules/lodash/fp/at.js b/node_modules/lodash/fp/at.js new file mode 100644 index 0000000..cc39d25 --- /dev/null +++ b/node_modules/lodash/fp/at.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('at', require('../at')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/attempt.js b/node_modules/lodash/fp/attempt.js new file mode 100644 index 0000000..26ca42e --- /dev/null +++ b/node_modules/lodash/fp/attempt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('attempt', require('../attempt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/before.js b/node_modules/lodash/fp/before.js new file mode 100644 index 0000000..7a2de65 --- /dev/null +++ b/node_modules/lodash/fp/before.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('before', require('../before')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/bind.js b/node_modules/lodash/fp/bind.js new file mode 100644 index 0000000..5cbe4f3 --- /dev/null +++ b/node_modules/lodash/fp/bind.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('bind', require('../bind')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/bindAll.js b/node_modules/lodash/fp/bindAll.js new file mode 100644 index 0000000..6b4a4a0 --- /dev/null +++ b/node_modules/lodash/fp/bindAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('bindAll', require('../bindAll')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/bindKey.js b/node_modules/lodash/fp/bindKey.js new file mode 100644 index 0000000..6a46c6b --- /dev/null +++ b/node_modules/lodash/fp/bindKey.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('bindKey', require('../bindKey')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/camelCase.js b/node_modules/lodash/fp/camelCase.js new file mode 100644 index 0000000..87b77b4 --- /dev/null +++ b/node_modules/lodash/fp/camelCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('camelCase', require('../camelCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/capitalize.js b/node_modules/lodash/fp/capitalize.js new file mode 100644 index 0000000..cac74e1 --- /dev/null +++ b/node_modules/lodash/fp/capitalize.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('capitalize', require('../capitalize'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/castArray.js b/node_modules/lodash/fp/castArray.js new file mode 100644 index 0000000..8681c09 --- /dev/null +++ b/node_modules/lodash/fp/castArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('castArray', require('../castArray')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/ceil.js b/node_modules/lodash/fp/ceil.js new file mode 100644 index 0000000..f416b72 --- /dev/null +++ b/node_modules/lodash/fp/ceil.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('ceil', require('../ceil')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/chain.js b/node_modules/lodash/fp/chain.js new file mode 100644 index 0000000..604fe39 --- /dev/null +++ b/node_modules/lodash/fp/chain.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('chain', require('../chain'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/chunk.js b/node_modules/lodash/fp/chunk.js new file mode 100644 index 0000000..871ab08 --- /dev/null +++ b/node_modules/lodash/fp/chunk.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('chunk', require('../chunk')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/clamp.js b/node_modules/lodash/fp/clamp.js new file mode 100644 index 0000000..3b06c01 --- /dev/null +++ b/node_modules/lodash/fp/clamp.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('clamp', require('../clamp')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/clone.js b/node_modules/lodash/fp/clone.js new file mode 100644 index 0000000..cadb59c --- /dev/null +++ b/node_modules/lodash/fp/clone.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('clone', require('../clone'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/cloneDeep.js b/node_modules/lodash/fp/cloneDeep.js new file mode 100644 index 0000000..a6107aa --- /dev/null +++ b/node_modules/lodash/fp/cloneDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('cloneDeep', require('../cloneDeep'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/cloneDeepWith.js b/node_modules/lodash/fp/cloneDeepWith.js new file mode 100644 index 0000000..6f01e44 --- /dev/null +++ b/node_modules/lodash/fp/cloneDeepWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('cloneDeepWith', require('../cloneDeepWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/cloneWith.js b/node_modules/lodash/fp/cloneWith.js new file mode 100644 index 0000000..aa88578 --- /dev/null +++ b/node_modules/lodash/fp/cloneWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('cloneWith', require('../cloneWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/collection.js b/node_modules/lodash/fp/collection.js new file mode 100644 index 0000000..fc8b328 --- /dev/null +++ b/node_modules/lodash/fp/collection.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../collection')); diff --git a/node_modules/lodash/fp/commit.js b/node_modules/lodash/fp/commit.js new file mode 100644 index 0000000..130a894 --- /dev/null +++ b/node_modules/lodash/fp/commit.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('commit', require('../commit'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/compact.js b/node_modules/lodash/fp/compact.js new file mode 100644 index 0000000..ce8f7a1 --- /dev/null +++ b/node_modules/lodash/fp/compact.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('compact', require('../compact'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/complement.js b/node_modules/lodash/fp/complement.js new file mode 100644 index 0000000..93eb462 --- /dev/null +++ b/node_modules/lodash/fp/complement.js @@ -0,0 +1 @@ +module.exports = require('./negate'); diff --git a/node_modules/lodash/fp/compose.js b/node_modules/lodash/fp/compose.js new file mode 100644 index 0000000..1954e94 --- /dev/null +++ b/node_modules/lodash/fp/compose.js @@ -0,0 +1 @@ +module.exports = require('./flowRight'); diff --git a/node_modules/lodash/fp/concat.js b/node_modules/lodash/fp/concat.js new file mode 100644 index 0000000..e59346a --- /dev/null +++ b/node_modules/lodash/fp/concat.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('concat', require('../concat')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/cond.js b/node_modules/lodash/fp/cond.js new file mode 100644 index 0000000..6a0120e --- /dev/null +++ b/node_modules/lodash/fp/cond.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('cond', require('../cond'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/conforms.js b/node_modules/lodash/fp/conforms.js new file mode 100644 index 0000000..3247f64 --- /dev/null +++ b/node_modules/lodash/fp/conforms.js @@ -0,0 +1 @@ +module.exports = require('./conformsTo'); diff --git a/node_modules/lodash/fp/conformsTo.js b/node_modules/lodash/fp/conformsTo.js new file mode 100644 index 0000000..aa7f41e --- /dev/null +++ b/node_modules/lodash/fp/conformsTo.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('conformsTo', require('../conformsTo')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/constant.js b/node_modules/lodash/fp/constant.js new file mode 100644 index 0000000..9e406fc --- /dev/null +++ b/node_modules/lodash/fp/constant.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('constant', require('../constant'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/contains.js b/node_modules/lodash/fp/contains.js new file mode 100644 index 0000000..594722a --- /dev/null +++ b/node_modules/lodash/fp/contains.js @@ -0,0 +1 @@ +module.exports = require('./includes'); diff --git a/node_modules/lodash/fp/convert.js b/node_modules/lodash/fp/convert.js new file mode 100644 index 0000000..4795dc4 --- /dev/null +++ b/node_modules/lodash/fp/convert.js @@ -0,0 +1,18 @@ +var baseConvert = require('./_baseConvert'), + util = require('./_util'); + +/** + * Converts `func` of `name` to an immutable auto-curried iteratee-first data-last + * version with conversion `options` applied. If `name` is an object its methods + * will be converted. + * + * @param {string} name The name of the function to wrap. + * @param {Function} [func] The function to wrap. + * @param {Object} [options] The options object. See `baseConvert` for more details. + * @returns {Function|Object} Returns the converted function or object. + */ +function convert(name, func, options) { + return baseConvert(util, name, func, options); +} + +module.exports = convert; diff --git a/node_modules/lodash/fp/countBy.js b/node_modules/lodash/fp/countBy.js new file mode 100644 index 0000000..dfa4643 --- /dev/null +++ b/node_modules/lodash/fp/countBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('countBy', require('../countBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/create.js b/node_modules/lodash/fp/create.js new file mode 100644 index 0000000..752025f --- /dev/null +++ b/node_modules/lodash/fp/create.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('create', require('../create')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/curry.js b/node_modules/lodash/fp/curry.js new file mode 100644 index 0000000..b0b4168 --- /dev/null +++ b/node_modules/lodash/fp/curry.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('curry', require('../curry')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/curryN.js b/node_modules/lodash/fp/curryN.js new file mode 100644 index 0000000..2ae7d00 --- /dev/null +++ b/node_modules/lodash/fp/curryN.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('curryN', require('../curry')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/curryRight.js b/node_modules/lodash/fp/curryRight.js new file mode 100644 index 0000000..cb619eb --- /dev/null +++ b/node_modules/lodash/fp/curryRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('curryRight', require('../curryRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/curryRightN.js b/node_modules/lodash/fp/curryRightN.js new file mode 100644 index 0000000..2495afc --- /dev/null +++ b/node_modules/lodash/fp/curryRightN.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('curryRightN', require('../curryRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/date.js b/node_modules/lodash/fp/date.js new file mode 100644 index 0000000..82cb952 --- /dev/null +++ b/node_modules/lodash/fp/date.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../date')); diff --git a/node_modules/lodash/fp/debounce.js b/node_modules/lodash/fp/debounce.js new file mode 100644 index 0000000..2612229 --- /dev/null +++ b/node_modules/lodash/fp/debounce.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('debounce', require('../debounce')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/deburr.js b/node_modules/lodash/fp/deburr.js new file mode 100644 index 0000000..96463ab --- /dev/null +++ b/node_modules/lodash/fp/deburr.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('deburr', require('../deburr'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/defaultTo.js b/node_modules/lodash/fp/defaultTo.js new file mode 100644 index 0000000..d6b52a4 --- /dev/null +++ b/node_modules/lodash/fp/defaultTo.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaultTo', require('../defaultTo')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/defaults.js b/node_modules/lodash/fp/defaults.js new file mode 100644 index 0000000..e1a8e6e --- /dev/null +++ b/node_modules/lodash/fp/defaults.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaults', require('../defaults')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/defaultsAll.js b/node_modules/lodash/fp/defaultsAll.js new file mode 100644 index 0000000..238fcc3 --- /dev/null +++ b/node_modules/lodash/fp/defaultsAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaultsAll', require('../defaults')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/defaultsDeep.js b/node_modules/lodash/fp/defaultsDeep.js new file mode 100644 index 0000000..1f172ff --- /dev/null +++ b/node_modules/lodash/fp/defaultsDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaultsDeep', require('../defaultsDeep')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/defaultsDeepAll.js b/node_modules/lodash/fp/defaultsDeepAll.js new file mode 100644 index 0000000..6835f2f --- /dev/null +++ b/node_modules/lodash/fp/defaultsDeepAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaultsDeepAll', require('../defaultsDeep')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/defer.js b/node_modules/lodash/fp/defer.js new file mode 100644 index 0000000..ec7990f --- /dev/null +++ b/node_modules/lodash/fp/defer.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defer', require('../defer'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/delay.js b/node_modules/lodash/fp/delay.js new file mode 100644 index 0000000..556dbd5 --- /dev/null +++ b/node_modules/lodash/fp/delay.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('delay', require('../delay')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/difference.js b/node_modules/lodash/fp/difference.js new file mode 100644 index 0000000..2d03765 --- /dev/null +++ b/node_modules/lodash/fp/difference.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('difference', require('../difference')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/differenceBy.js b/node_modules/lodash/fp/differenceBy.js new file mode 100644 index 0000000..2f91491 --- /dev/null +++ b/node_modules/lodash/fp/differenceBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('differenceBy', require('../differenceBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/differenceWith.js b/node_modules/lodash/fp/differenceWith.js new file mode 100644 index 0000000..bcf5ad2 --- /dev/null +++ b/node_modules/lodash/fp/differenceWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('differenceWith', require('../differenceWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/dissoc.js b/node_modules/lodash/fp/dissoc.js new file mode 100644 index 0000000..7ec7be1 --- /dev/null +++ b/node_modules/lodash/fp/dissoc.js @@ -0,0 +1 @@ +module.exports = require('./unset'); diff --git a/node_modules/lodash/fp/dissocPath.js b/node_modules/lodash/fp/dissocPath.js new file mode 100644 index 0000000..7ec7be1 --- /dev/null +++ b/node_modules/lodash/fp/dissocPath.js @@ -0,0 +1 @@ +module.exports = require('./unset'); diff --git a/node_modules/lodash/fp/divide.js b/node_modules/lodash/fp/divide.js new file mode 100644 index 0000000..82048c5 --- /dev/null +++ b/node_modules/lodash/fp/divide.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('divide', require('../divide')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/drop.js b/node_modules/lodash/fp/drop.js new file mode 100644 index 0000000..2fa9b4f --- /dev/null +++ b/node_modules/lodash/fp/drop.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('drop', require('../drop')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/dropLast.js b/node_modules/lodash/fp/dropLast.js new file mode 100644 index 0000000..174e525 --- /dev/null +++ b/node_modules/lodash/fp/dropLast.js @@ -0,0 +1 @@ +module.exports = require('./dropRight'); diff --git a/node_modules/lodash/fp/dropLastWhile.js b/node_modules/lodash/fp/dropLastWhile.js new file mode 100644 index 0000000..be2a9d2 --- /dev/null +++ b/node_modules/lodash/fp/dropLastWhile.js @@ -0,0 +1 @@ +module.exports = require('./dropRightWhile'); diff --git a/node_modules/lodash/fp/dropRight.js b/node_modules/lodash/fp/dropRight.js new file mode 100644 index 0000000..e98881f --- /dev/null +++ b/node_modules/lodash/fp/dropRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('dropRight', require('../dropRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/dropRightWhile.js b/node_modules/lodash/fp/dropRightWhile.js new file mode 100644 index 0000000..cacaa70 --- /dev/null +++ b/node_modules/lodash/fp/dropRightWhile.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('dropRightWhile', require('../dropRightWhile')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/dropWhile.js b/node_modules/lodash/fp/dropWhile.js new file mode 100644 index 0000000..285f864 --- /dev/null +++ b/node_modules/lodash/fp/dropWhile.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('dropWhile', require('../dropWhile')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/each.js b/node_modules/lodash/fp/each.js new file mode 100644 index 0000000..8800f42 --- /dev/null +++ b/node_modules/lodash/fp/each.js @@ -0,0 +1 @@ +module.exports = require('./forEach'); diff --git a/node_modules/lodash/fp/eachRight.js b/node_modules/lodash/fp/eachRight.js new file mode 100644 index 0000000..3252b2a --- /dev/null +++ b/node_modules/lodash/fp/eachRight.js @@ -0,0 +1 @@ +module.exports = require('./forEachRight'); diff --git a/node_modules/lodash/fp/endsWith.js b/node_modules/lodash/fp/endsWith.js new file mode 100644 index 0000000..17dc2a4 --- /dev/null +++ b/node_modules/lodash/fp/endsWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('endsWith', require('../endsWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/entries.js b/node_modules/lodash/fp/entries.js new file mode 100644 index 0000000..7a88df2 --- /dev/null +++ b/node_modules/lodash/fp/entries.js @@ -0,0 +1 @@ +module.exports = require('./toPairs'); diff --git a/node_modules/lodash/fp/entriesIn.js b/node_modules/lodash/fp/entriesIn.js new file mode 100644 index 0000000..f6c6331 --- /dev/null +++ b/node_modules/lodash/fp/entriesIn.js @@ -0,0 +1 @@ +module.exports = require('./toPairsIn'); diff --git a/node_modules/lodash/fp/eq.js b/node_modules/lodash/fp/eq.js new file mode 100644 index 0000000..9a3d21b --- /dev/null +++ b/node_modules/lodash/fp/eq.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('eq', require('../eq')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/equals.js b/node_modules/lodash/fp/equals.js new file mode 100644 index 0000000..e6a5ce0 --- /dev/null +++ b/node_modules/lodash/fp/equals.js @@ -0,0 +1 @@ +module.exports = require('./isEqual'); diff --git a/node_modules/lodash/fp/escape.js b/node_modules/lodash/fp/escape.js new file mode 100644 index 0000000..52c1fbb --- /dev/null +++ b/node_modules/lodash/fp/escape.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('escape', require('../escape'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/escapeRegExp.js b/node_modules/lodash/fp/escapeRegExp.js new file mode 100644 index 0000000..369b2ef --- /dev/null +++ b/node_modules/lodash/fp/escapeRegExp.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('escapeRegExp', require('../escapeRegExp'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/every.js b/node_modules/lodash/fp/every.js new file mode 100644 index 0000000..95c2776 --- /dev/null +++ b/node_modules/lodash/fp/every.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('every', require('../every')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/extend.js b/node_modules/lodash/fp/extend.js new file mode 100644 index 0000000..e00166c --- /dev/null +++ b/node_modules/lodash/fp/extend.js @@ -0,0 +1 @@ +module.exports = require('./assignIn'); diff --git a/node_modules/lodash/fp/extendAll.js b/node_modules/lodash/fp/extendAll.js new file mode 100644 index 0000000..cc55b64 --- /dev/null +++ b/node_modules/lodash/fp/extendAll.js @@ -0,0 +1 @@ +module.exports = require('./assignInAll'); diff --git a/node_modules/lodash/fp/extendAllWith.js b/node_modules/lodash/fp/extendAllWith.js new file mode 100644 index 0000000..6679d20 --- /dev/null +++ b/node_modules/lodash/fp/extendAllWith.js @@ -0,0 +1 @@ +module.exports = require('./assignInAllWith'); diff --git a/node_modules/lodash/fp/extendWith.js b/node_modules/lodash/fp/extendWith.js new file mode 100644 index 0000000..dbdcb3b --- /dev/null +++ b/node_modules/lodash/fp/extendWith.js @@ -0,0 +1 @@ +module.exports = require('./assignInWith'); diff --git a/node_modules/lodash/fp/fill.js b/node_modules/lodash/fp/fill.js new file mode 100644 index 0000000..b2d47e8 --- /dev/null +++ b/node_modules/lodash/fp/fill.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('fill', require('../fill')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/filter.js b/node_modules/lodash/fp/filter.js new file mode 100644 index 0000000..796d501 --- /dev/null +++ b/node_modules/lodash/fp/filter.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('filter', require('../filter')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/find.js b/node_modules/lodash/fp/find.js new file mode 100644 index 0000000..f805d33 --- /dev/null +++ b/node_modules/lodash/fp/find.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('find', require('../find')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findFrom.js b/node_modules/lodash/fp/findFrom.js new file mode 100644 index 0000000..da8275e --- /dev/null +++ b/node_modules/lodash/fp/findFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findFrom', require('../find')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findIndex.js b/node_modules/lodash/fp/findIndex.js new file mode 100644 index 0000000..8c15fd1 --- /dev/null +++ b/node_modules/lodash/fp/findIndex.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findIndex', require('../findIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findIndexFrom.js b/node_modules/lodash/fp/findIndexFrom.js new file mode 100644 index 0000000..32e98cb --- /dev/null +++ b/node_modules/lodash/fp/findIndexFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findIndexFrom', require('../findIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findKey.js b/node_modules/lodash/fp/findKey.js new file mode 100644 index 0000000..475bcfa --- /dev/null +++ b/node_modules/lodash/fp/findKey.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findKey', require('../findKey')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findLast.js b/node_modules/lodash/fp/findLast.js new file mode 100644 index 0000000..093fe94 --- /dev/null +++ b/node_modules/lodash/fp/findLast.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLast', require('../findLast')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findLastFrom.js b/node_modules/lodash/fp/findLastFrom.js new file mode 100644 index 0000000..76c38fb --- /dev/null +++ b/node_modules/lodash/fp/findLastFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLastFrom', require('../findLast')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findLastIndex.js b/node_modules/lodash/fp/findLastIndex.js new file mode 100644 index 0000000..36986df --- /dev/null +++ b/node_modules/lodash/fp/findLastIndex.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLastIndex', require('../findLastIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findLastIndexFrom.js b/node_modules/lodash/fp/findLastIndexFrom.js new file mode 100644 index 0000000..34c8176 --- /dev/null +++ b/node_modules/lodash/fp/findLastIndexFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLastIndexFrom', require('../findLastIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findLastKey.js b/node_modules/lodash/fp/findLastKey.js new file mode 100644 index 0000000..5f81b60 --- /dev/null +++ b/node_modules/lodash/fp/findLastKey.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLastKey', require('../findLastKey')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/first.js b/node_modules/lodash/fp/first.js new file mode 100644 index 0000000..53f4ad1 --- /dev/null +++ b/node_modules/lodash/fp/first.js @@ -0,0 +1 @@ +module.exports = require('./head'); diff --git a/node_modules/lodash/fp/flatMap.js b/node_modules/lodash/fp/flatMap.js new file mode 100644 index 0000000..d01dc4d --- /dev/null +++ b/node_modules/lodash/fp/flatMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flatMap', require('../flatMap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flatMapDeep.js b/node_modules/lodash/fp/flatMapDeep.js new file mode 100644 index 0000000..569c42e --- /dev/null +++ b/node_modules/lodash/fp/flatMapDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flatMapDeep', require('../flatMapDeep')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flatMapDepth.js b/node_modules/lodash/fp/flatMapDepth.js new file mode 100644 index 0000000..6eb68fd --- /dev/null +++ b/node_modules/lodash/fp/flatMapDepth.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flatMapDepth', require('../flatMapDepth')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flatten.js b/node_modules/lodash/fp/flatten.js new file mode 100644 index 0000000..30425d8 --- /dev/null +++ b/node_modules/lodash/fp/flatten.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flatten', require('../flatten'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flattenDeep.js b/node_modules/lodash/fp/flattenDeep.js new file mode 100644 index 0000000..aed5db2 --- /dev/null +++ b/node_modules/lodash/fp/flattenDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flattenDeep', require('../flattenDeep'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flattenDepth.js b/node_modules/lodash/fp/flattenDepth.js new file mode 100644 index 0000000..ad65e37 --- /dev/null +++ b/node_modules/lodash/fp/flattenDepth.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flattenDepth', require('../flattenDepth')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flip.js b/node_modules/lodash/fp/flip.js new file mode 100644 index 0000000..0547e7b --- /dev/null +++ b/node_modules/lodash/fp/flip.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flip', require('../flip'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/floor.js b/node_modules/lodash/fp/floor.js new file mode 100644 index 0000000..a6cf335 --- /dev/null +++ b/node_modules/lodash/fp/floor.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('floor', require('../floor')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flow.js b/node_modules/lodash/fp/flow.js new file mode 100644 index 0000000..cd83677 --- /dev/null +++ b/node_modules/lodash/fp/flow.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flow', require('../flow')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flowRight.js b/node_modules/lodash/fp/flowRight.js new file mode 100644 index 0000000..972a5b9 --- /dev/null +++ b/node_modules/lodash/fp/flowRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flowRight', require('../flowRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/forEach.js b/node_modules/lodash/fp/forEach.js new file mode 100644 index 0000000..2f49452 --- /dev/null +++ b/node_modules/lodash/fp/forEach.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forEach', require('../forEach')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/forEachRight.js b/node_modules/lodash/fp/forEachRight.js new file mode 100644 index 0000000..3ff9733 --- /dev/null +++ b/node_modules/lodash/fp/forEachRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forEachRight', require('../forEachRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/forIn.js b/node_modules/lodash/fp/forIn.js new file mode 100644 index 0000000..9341749 --- /dev/null +++ b/node_modules/lodash/fp/forIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forIn', require('../forIn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/forInRight.js b/node_modules/lodash/fp/forInRight.js new file mode 100644 index 0000000..cecf8bb --- /dev/null +++ b/node_modules/lodash/fp/forInRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forInRight', require('../forInRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/forOwn.js b/node_modules/lodash/fp/forOwn.js new file mode 100644 index 0000000..246449e --- /dev/null +++ b/node_modules/lodash/fp/forOwn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forOwn', require('../forOwn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/forOwnRight.js b/node_modules/lodash/fp/forOwnRight.js new file mode 100644 index 0000000..c5e826e --- /dev/null +++ b/node_modules/lodash/fp/forOwnRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forOwnRight', require('../forOwnRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/fromPairs.js b/node_modules/lodash/fp/fromPairs.js new file mode 100644 index 0000000..f8cc596 --- /dev/null +++ b/node_modules/lodash/fp/fromPairs.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('fromPairs', require('../fromPairs')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/function.js b/node_modules/lodash/fp/function.js new file mode 100644 index 0000000..dfe69b1 --- /dev/null +++ b/node_modules/lodash/fp/function.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../function')); diff --git a/node_modules/lodash/fp/functions.js b/node_modules/lodash/fp/functions.js new file mode 100644 index 0000000..09d1bb1 --- /dev/null +++ b/node_modules/lodash/fp/functions.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('functions', require('../functions'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/functionsIn.js b/node_modules/lodash/fp/functionsIn.js new file mode 100644 index 0000000..2cfeb83 --- /dev/null +++ b/node_modules/lodash/fp/functionsIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('functionsIn', require('../functionsIn'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/get.js b/node_modules/lodash/fp/get.js new file mode 100644 index 0000000..6d3a328 --- /dev/null +++ b/node_modules/lodash/fp/get.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('get', require('../get')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/getOr.js b/node_modules/lodash/fp/getOr.js new file mode 100644 index 0000000..7dbf771 --- /dev/null +++ b/node_modules/lodash/fp/getOr.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('getOr', require('../get')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/groupBy.js b/node_modules/lodash/fp/groupBy.js new file mode 100644 index 0000000..fc0bc78 --- /dev/null +++ b/node_modules/lodash/fp/groupBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('groupBy', require('../groupBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/gt.js b/node_modules/lodash/fp/gt.js new file mode 100644 index 0000000..9e57c80 --- /dev/null +++ b/node_modules/lodash/fp/gt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('gt', require('../gt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/gte.js b/node_modules/lodash/fp/gte.js new file mode 100644 index 0000000..4584786 --- /dev/null +++ b/node_modules/lodash/fp/gte.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('gte', require('../gte')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/has.js b/node_modules/lodash/fp/has.js new file mode 100644 index 0000000..b901298 --- /dev/null +++ b/node_modules/lodash/fp/has.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('has', require('../has')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/hasIn.js b/node_modules/lodash/fp/hasIn.js new file mode 100644 index 0000000..b3c3d1a --- /dev/null +++ b/node_modules/lodash/fp/hasIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('hasIn', require('../hasIn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/head.js b/node_modules/lodash/fp/head.js new file mode 100644 index 0000000..2694f0a --- /dev/null +++ b/node_modules/lodash/fp/head.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('head', require('../head'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/identical.js b/node_modules/lodash/fp/identical.js new file mode 100644 index 0000000..85563f4 --- /dev/null +++ b/node_modules/lodash/fp/identical.js @@ -0,0 +1 @@ +module.exports = require('./eq'); diff --git a/node_modules/lodash/fp/identity.js b/node_modules/lodash/fp/identity.js new file mode 100644 index 0000000..096415a --- /dev/null +++ b/node_modules/lodash/fp/identity.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('identity', require('../identity'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/inRange.js b/node_modules/lodash/fp/inRange.js new file mode 100644 index 0000000..202d940 --- /dev/null +++ b/node_modules/lodash/fp/inRange.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('inRange', require('../inRange')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/includes.js b/node_modules/lodash/fp/includes.js new file mode 100644 index 0000000..1146780 --- /dev/null +++ b/node_modules/lodash/fp/includes.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('includes', require('../includes')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/includesFrom.js b/node_modules/lodash/fp/includesFrom.js new file mode 100644 index 0000000..683afdb --- /dev/null +++ b/node_modules/lodash/fp/includesFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('includesFrom', require('../includes')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/indexBy.js b/node_modules/lodash/fp/indexBy.js new file mode 100644 index 0000000..7e64bc0 --- /dev/null +++ b/node_modules/lodash/fp/indexBy.js @@ -0,0 +1 @@ +module.exports = require('./keyBy'); diff --git a/node_modules/lodash/fp/indexOf.js b/node_modules/lodash/fp/indexOf.js new file mode 100644 index 0000000..524658e --- /dev/null +++ b/node_modules/lodash/fp/indexOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('indexOf', require('../indexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/indexOfFrom.js b/node_modules/lodash/fp/indexOfFrom.js new file mode 100644 index 0000000..d99c822 --- /dev/null +++ b/node_modules/lodash/fp/indexOfFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('indexOfFrom', require('../indexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/init.js b/node_modules/lodash/fp/init.js new file mode 100644 index 0000000..2f88d8b --- /dev/null +++ b/node_modules/lodash/fp/init.js @@ -0,0 +1 @@ +module.exports = require('./initial'); diff --git a/node_modules/lodash/fp/initial.js b/node_modules/lodash/fp/initial.js new file mode 100644 index 0000000..b732ba0 --- /dev/null +++ b/node_modules/lodash/fp/initial.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('initial', require('../initial'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/intersection.js b/node_modules/lodash/fp/intersection.js new file mode 100644 index 0000000..52936d5 --- /dev/null +++ b/node_modules/lodash/fp/intersection.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('intersection', require('../intersection')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/intersectionBy.js b/node_modules/lodash/fp/intersectionBy.js new file mode 100644 index 0000000..72629f2 --- /dev/null +++ b/node_modules/lodash/fp/intersectionBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('intersectionBy', require('../intersectionBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/intersectionWith.js b/node_modules/lodash/fp/intersectionWith.js new file mode 100644 index 0000000..e064f40 --- /dev/null +++ b/node_modules/lodash/fp/intersectionWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('intersectionWith', require('../intersectionWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/invert.js b/node_modules/lodash/fp/invert.js new file mode 100644 index 0000000..2d5d1f0 --- /dev/null +++ b/node_modules/lodash/fp/invert.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invert', require('../invert')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/invertBy.js b/node_modules/lodash/fp/invertBy.js new file mode 100644 index 0000000..63ca97e --- /dev/null +++ b/node_modules/lodash/fp/invertBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invertBy', require('../invertBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/invertObj.js b/node_modules/lodash/fp/invertObj.js new file mode 100644 index 0000000..f1d842e --- /dev/null +++ b/node_modules/lodash/fp/invertObj.js @@ -0,0 +1 @@ +module.exports = require('./invert'); diff --git a/node_modules/lodash/fp/invoke.js b/node_modules/lodash/fp/invoke.js new file mode 100644 index 0000000..fcf17f0 --- /dev/null +++ b/node_modules/lodash/fp/invoke.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invoke', require('../invoke')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/invokeArgs.js b/node_modules/lodash/fp/invokeArgs.js new file mode 100644 index 0000000..d3f2953 --- /dev/null +++ b/node_modules/lodash/fp/invokeArgs.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invokeArgs', require('../invoke')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/invokeArgsMap.js b/node_modules/lodash/fp/invokeArgsMap.js new file mode 100644 index 0000000..eaa9f84 --- /dev/null +++ b/node_modules/lodash/fp/invokeArgsMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invokeArgsMap', require('../invokeMap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/invokeMap.js b/node_modules/lodash/fp/invokeMap.js new file mode 100644 index 0000000..6515fd7 --- /dev/null +++ b/node_modules/lodash/fp/invokeMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invokeMap', require('../invokeMap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isArguments.js b/node_modules/lodash/fp/isArguments.js new file mode 100644 index 0000000..1d93c9e --- /dev/null +++ b/node_modules/lodash/fp/isArguments.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArguments', require('../isArguments'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isArray.js b/node_modules/lodash/fp/isArray.js new file mode 100644 index 0000000..ba7ade8 --- /dev/null +++ b/node_modules/lodash/fp/isArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArray', require('../isArray'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isArrayBuffer.js b/node_modules/lodash/fp/isArrayBuffer.js new file mode 100644 index 0000000..5088513 --- /dev/null +++ b/node_modules/lodash/fp/isArrayBuffer.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArrayBuffer', require('../isArrayBuffer'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isArrayLike.js b/node_modules/lodash/fp/isArrayLike.js new file mode 100644 index 0000000..8f1856b --- /dev/null +++ b/node_modules/lodash/fp/isArrayLike.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArrayLike', require('../isArrayLike'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isArrayLikeObject.js b/node_modules/lodash/fp/isArrayLikeObject.js new file mode 100644 index 0000000..2108498 --- /dev/null +++ b/node_modules/lodash/fp/isArrayLikeObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArrayLikeObject', require('../isArrayLikeObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isBoolean.js b/node_modules/lodash/fp/isBoolean.js new file mode 100644 index 0000000..9339f75 --- /dev/null +++ b/node_modules/lodash/fp/isBoolean.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isBoolean', require('../isBoolean'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isBuffer.js b/node_modules/lodash/fp/isBuffer.js new file mode 100644 index 0000000..e60b123 --- /dev/null +++ b/node_modules/lodash/fp/isBuffer.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isBuffer', require('../isBuffer'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isDate.js b/node_modules/lodash/fp/isDate.js new file mode 100644 index 0000000..dc41d08 --- /dev/null +++ b/node_modules/lodash/fp/isDate.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isDate', require('../isDate'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isElement.js b/node_modules/lodash/fp/isElement.js new file mode 100644 index 0000000..18ee039 --- /dev/null +++ b/node_modules/lodash/fp/isElement.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isElement', require('../isElement'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isEmpty.js b/node_modules/lodash/fp/isEmpty.js new file mode 100644 index 0000000..0f4ae84 --- /dev/null +++ b/node_modules/lodash/fp/isEmpty.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isEmpty', require('../isEmpty'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isEqual.js b/node_modules/lodash/fp/isEqual.js new file mode 100644 index 0000000..4138386 --- /dev/null +++ b/node_modules/lodash/fp/isEqual.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isEqual', require('../isEqual')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isEqualWith.js b/node_modules/lodash/fp/isEqualWith.js new file mode 100644 index 0000000..029ff5c --- /dev/null +++ b/node_modules/lodash/fp/isEqualWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isEqualWith', require('../isEqualWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isError.js b/node_modules/lodash/fp/isError.js new file mode 100644 index 0000000..3dfd81c --- /dev/null +++ b/node_modules/lodash/fp/isError.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isError', require('../isError'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isFinite.js b/node_modules/lodash/fp/isFinite.js new file mode 100644 index 0000000..0b647b8 --- /dev/null +++ b/node_modules/lodash/fp/isFinite.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isFinite', require('../isFinite'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isFunction.js b/node_modules/lodash/fp/isFunction.js new file mode 100644 index 0000000..ff8e5c4 --- /dev/null +++ b/node_modules/lodash/fp/isFunction.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isFunction', require('../isFunction'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isInteger.js b/node_modules/lodash/fp/isInteger.js new file mode 100644 index 0000000..67af4ff --- /dev/null +++ b/node_modules/lodash/fp/isInteger.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isInteger', require('../isInteger'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isLength.js b/node_modules/lodash/fp/isLength.js new file mode 100644 index 0000000..fc101c5 --- /dev/null +++ b/node_modules/lodash/fp/isLength.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isLength', require('../isLength'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isMap.js b/node_modules/lodash/fp/isMap.js new file mode 100644 index 0000000..a209aa6 --- /dev/null +++ b/node_modules/lodash/fp/isMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isMap', require('../isMap'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isMatch.js b/node_modules/lodash/fp/isMatch.js new file mode 100644 index 0000000..6264ca1 --- /dev/null +++ b/node_modules/lodash/fp/isMatch.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isMatch', require('../isMatch')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isMatchWith.js b/node_modules/lodash/fp/isMatchWith.js new file mode 100644 index 0000000..d95f319 --- /dev/null +++ b/node_modules/lodash/fp/isMatchWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isMatchWith', require('../isMatchWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isNaN.js b/node_modules/lodash/fp/isNaN.js new file mode 100644 index 0000000..66a978f --- /dev/null +++ b/node_modules/lodash/fp/isNaN.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNaN', require('../isNaN'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isNative.js b/node_modules/lodash/fp/isNative.js new file mode 100644 index 0000000..3d775ba --- /dev/null +++ b/node_modules/lodash/fp/isNative.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNative', require('../isNative'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isNil.js b/node_modules/lodash/fp/isNil.js new file mode 100644 index 0000000..5952c02 --- /dev/null +++ b/node_modules/lodash/fp/isNil.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNil', require('../isNil'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isNull.js b/node_modules/lodash/fp/isNull.js new file mode 100644 index 0000000..f201a35 --- /dev/null +++ b/node_modules/lodash/fp/isNull.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNull', require('../isNull'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isNumber.js b/node_modules/lodash/fp/isNumber.js new file mode 100644 index 0000000..a2b5fa0 --- /dev/null +++ b/node_modules/lodash/fp/isNumber.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNumber', require('../isNumber'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isObject.js b/node_modules/lodash/fp/isObject.js new file mode 100644 index 0000000..231ace0 --- /dev/null +++ b/node_modules/lodash/fp/isObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isObject', require('../isObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isObjectLike.js b/node_modules/lodash/fp/isObjectLike.js new file mode 100644 index 0000000..f16082e --- /dev/null +++ b/node_modules/lodash/fp/isObjectLike.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isObjectLike', require('../isObjectLike'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isPlainObject.js b/node_modules/lodash/fp/isPlainObject.js new file mode 100644 index 0000000..b5bea90 --- /dev/null +++ b/node_modules/lodash/fp/isPlainObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isPlainObject', require('../isPlainObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isRegExp.js b/node_modules/lodash/fp/isRegExp.js new file mode 100644 index 0000000..12a1a3d --- /dev/null +++ b/node_modules/lodash/fp/isRegExp.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isRegExp', require('../isRegExp'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isSafeInteger.js b/node_modules/lodash/fp/isSafeInteger.js new file mode 100644 index 0000000..7230f55 --- /dev/null +++ b/node_modules/lodash/fp/isSafeInteger.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isSafeInteger', require('../isSafeInteger'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isSet.js b/node_modules/lodash/fp/isSet.js new file mode 100644 index 0000000..35c01f6 --- /dev/null +++ b/node_modules/lodash/fp/isSet.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isSet', require('../isSet'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isString.js b/node_modules/lodash/fp/isString.js new file mode 100644 index 0000000..1fd0679 --- /dev/null +++ b/node_modules/lodash/fp/isString.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isString', require('../isString'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isSymbol.js b/node_modules/lodash/fp/isSymbol.js new file mode 100644 index 0000000..3867695 --- /dev/null +++ b/node_modules/lodash/fp/isSymbol.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isSymbol', require('../isSymbol'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isTypedArray.js b/node_modules/lodash/fp/isTypedArray.js new file mode 100644 index 0000000..8567953 --- /dev/null +++ b/node_modules/lodash/fp/isTypedArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isTypedArray', require('../isTypedArray'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isUndefined.js b/node_modules/lodash/fp/isUndefined.js new file mode 100644 index 0000000..ddbca31 --- /dev/null +++ b/node_modules/lodash/fp/isUndefined.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isUndefined', require('../isUndefined'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isWeakMap.js b/node_modules/lodash/fp/isWeakMap.js new file mode 100644 index 0000000..ef60c61 --- /dev/null +++ b/node_modules/lodash/fp/isWeakMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isWeakMap', require('../isWeakMap'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isWeakSet.js b/node_modules/lodash/fp/isWeakSet.js new file mode 100644 index 0000000..c99bfaa --- /dev/null +++ b/node_modules/lodash/fp/isWeakSet.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isWeakSet', require('../isWeakSet'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/iteratee.js b/node_modules/lodash/fp/iteratee.js new file mode 100644 index 0000000..9f0f717 --- /dev/null +++ b/node_modules/lodash/fp/iteratee.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('iteratee', require('../iteratee')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/join.js b/node_modules/lodash/fp/join.js new file mode 100644 index 0000000..a220e00 --- /dev/null +++ b/node_modules/lodash/fp/join.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('join', require('../join')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/juxt.js b/node_modules/lodash/fp/juxt.js new file mode 100644 index 0000000..f71e04e --- /dev/null +++ b/node_modules/lodash/fp/juxt.js @@ -0,0 +1 @@ +module.exports = require('./over'); diff --git a/node_modules/lodash/fp/kebabCase.js b/node_modules/lodash/fp/kebabCase.js new file mode 100644 index 0000000..60737f1 --- /dev/null +++ b/node_modules/lodash/fp/kebabCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('kebabCase', require('../kebabCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/keyBy.js b/node_modules/lodash/fp/keyBy.js new file mode 100644 index 0000000..9a6a85d --- /dev/null +++ b/node_modules/lodash/fp/keyBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('keyBy', require('../keyBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/keys.js b/node_modules/lodash/fp/keys.js new file mode 100644 index 0000000..e12bb07 --- /dev/null +++ b/node_modules/lodash/fp/keys.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('keys', require('../keys'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/keysIn.js b/node_modules/lodash/fp/keysIn.js new file mode 100644 index 0000000..f3eb36a --- /dev/null +++ b/node_modules/lodash/fp/keysIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('keysIn', require('../keysIn'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lang.js b/node_modules/lodash/fp/lang.js new file mode 100644 index 0000000..08cc9c1 --- /dev/null +++ b/node_modules/lodash/fp/lang.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../lang')); diff --git a/node_modules/lodash/fp/last.js b/node_modules/lodash/fp/last.js new file mode 100644 index 0000000..0f71699 --- /dev/null +++ b/node_modules/lodash/fp/last.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('last', require('../last'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lastIndexOf.js b/node_modules/lodash/fp/lastIndexOf.js new file mode 100644 index 0000000..ddf39c3 --- /dev/null +++ b/node_modules/lodash/fp/lastIndexOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lastIndexOf', require('../lastIndexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lastIndexOfFrom.js b/node_modules/lodash/fp/lastIndexOfFrom.js new file mode 100644 index 0000000..1ff6a0b --- /dev/null +++ b/node_modules/lodash/fp/lastIndexOfFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lastIndexOfFrom', require('../lastIndexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lowerCase.js b/node_modules/lodash/fp/lowerCase.js new file mode 100644 index 0000000..ea64bc1 --- /dev/null +++ b/node_modules/lodash/fp/lowerCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lowerCase', require('../lowerCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lowerFirst.js b/node_modules/lodash/fp/lowerFirst.js new file mode 100644 index 0000000..539720a --- /dev/null +++ b/node_modules/lodash/fp/lowerFirst.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lowerFirst', require('../lowerFirst'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lt.js b/node_modules/lodash/fp/lt.js new file mode 100644 index 0000000..a31d21e --- /dev/null +++ b/node_modules/lodash/fp/lt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lt', require('../lt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lte.js b/node_modules/lodash/fp/lte.js new file mode 100644 index 0000000..d795d10 --- /dev/null +++ b/node_modules/lodash/fp/lte.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lte', require('../lte')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/map.js b/node_modules/lodash/fp/map.js new file mode 100644 index 0000000..cf98794 --- /dev/null +++ b/node_modules/lodash/fp/map.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('map', require('../map')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mapKeys.js b/node_modules/lodash/fp/mapKeys.js new file mode 100644 index 0000000..1684587 --- /dev/null +++ b/node_modules/lodash/fp/mapKeys.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mapKeys', require('../mapKeys')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mapValues.js b/node_modules/lodash/fp/mapValues.js new file mode 100644 index 0000000..4004972 --- /dev/null +++ b/node_modules/lodash/fp/mapValues.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mapValues', require('../mapValues')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/matches.js b/node_modules/lodash/fp/matches.js new file mode 100644 index 0000000..29d1e1e --- /dev/null +++ b/node_modules/lodash/fp/matches.js @@ -0,0 +1 @@ +module.exports = require('./isMatch'); diff --git a/node_modules/lodash/fp/matchesProperty.js b/node_modules/lodash/fp/matchesProperty.js new file mode 100644 index 0000000..4575bd2 --- /dev/null +++ b/node_modules/lodash/fp/matchesProperty.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('matchesProperty', require('../matchesProperty')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/math.js b/node_modules/lodash/fp/math.js new file mode 100644 index 0000000..e8f50f7 --- /dev/null +++ b/node_modules/lodash/fp/math.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../math')); diff --git a/node_modules/lodash/fp/max.js b/node_modules/lodash/fp/max.js new file mode 100644 index 0000000..a66acac --- /dev/null +++ b/node_modules/lodash/fp/max.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('max', require('../max'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/maxBy.js b/node_modules/lodash/fp/maxBy.js new file mode 100644 index 0000000..d083fd6 --- /dev/null +++ b/node_modules/lodash/fp/maxBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('maxBy', require('../maxBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mean.js b/node_modules/lodash/fp/mean.js new file mode 100644 index 0000000..3117246 --- /dev/null +++ b/node_modules/lodash/fp/mean.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mean', require('../mean'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/meanBy.js b/node_modules/lodash/fp/meanBy.js new file mode 100644 index 0000000..556f25e --- /dev/null +++ b/node_modules/lodash/fp/meanBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('meanBy', require('../meanBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/memoize.js b/node_modules/lodash/fp/memoize.js new file mode 100644 index 0000000..638eec6 --- /dev/null +++ b/node_modules/lodash/fp/memoize.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('memoize', require('../memoize')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/merge.js b/node_modules/lodash/fp/merge.js new file mode 100644 index 0000000..ac66add --- /dev/null +++ b/node_modules/lodash/fp/merge.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('merge', require('../merge')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mergeAll.js b/node_modules/lodash/fp/mergeAll.js new file mode 100644 index 0000000..a3674d6 --- /dev/null +++ b/node_modules/lodash/fp/mergeAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mergeAll', require('../merge')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mergeAllWith.js b/node_modules/lodash/fp/mergeAllWith.js new file mode 100644 index 0000000..4bd4206 --- /dev/null +++ b/node_modules/lodash/fp/mergeAllWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mergeAllWith', require('../mergeWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mergeWith.js b/node_modules/lodash/fp/mergeWith.js new file mode 100644 index 0000000..00d44d5 --- /dev/null +++ b/node_modules/lodash/fp/mergeWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mergeWith', require('../mergeWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/method.js b/node_modules/lodash/fp/method.js new file mode 100644 index 0000000..f4060c6 --- /dev/null +++ b/node_modules/lodash/fp/method.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('method', require('../method')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/methodOf.js b/node_modules/lodash/fp/methodOf.js new file mode 100644 index 0000000..6139905 --- /dev/null +++ b/node_modules/lodash/fp/methodOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('methodOf', require('../methodOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/min.js b/node_modules/lodash/fp/min.js new file mode 100644 index 0000000..d12c6b4 --- /dev/null +++ b/node_modules/lodash/fp/min.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('min', require('../min'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/minBy.js b/node_modules/lodash/fp/minBy.js new file mode 100644 index 0000000..fdb9e24 --- /dev/null +++ b/node_modules/lodash/fp/minBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('minBy', require('../minBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mixin.js b/node_modules/lodash/fp/mixin.js new file mode 100644 index 0000000..332e6fb --- /dev/null +++ b/node_modules/lodash/fp/mixin.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mixin', require('../mixin')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/multiply.js b/node_modules/lodash/fp/multiply.js new file mode 100644 index 0000000..4dcf0b0 --- /dev/null +++ b/node_modules/lodash/fp/multiply.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('multiply', require('../multiply')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/nAry.js b/node_modules/lodash/fp/nAry.js new file mode 100644 index 0000000..f262a76 --- /dev/null +++ b/node_modules/lodash/fp/nAry.js @@ -0,0 +1 @@ +module.exports = require('./ary'); diff --git a/node_modules/lodash/fp/negate.js b/node_modules/lodash/fp/negate.js new file mode 100644 index 0000000..8b6dc7c --- /dev/null +++ b/node_modules/lodash/fp/negate.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('negate', require('../negate'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/next.js b/node_modules/lodash/fp/next.js new file mode 100644 index 0000000..140155e --- /dev/null +++ b/node_modules/lodash/fp/next.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('next', require('../next'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/noop.js b/node_modules/lodash/fp/noop.js new file mode 100644 index 0000000..b9e32cc --- /dev/null +++ b/node_modules/lodash/fp/noop.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('noop', require('../noop'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/now.js b/node_modules/lodash/fp/now.js new file mode 100644 index 0000000..6de2068 --- /dev/null +++ b/node_modules/lodash/fp/now.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('now', require('../now'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/nth.js b/node_modules/lodash/fp/nth.js new file mode 100644 index 0000000..da4fda7 --- /dev/null +++ b/node_modules/lodash/fp/nth.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('nth', require('../nth')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/nthArg.js b/node_modules/lodash/fp/nthArg.js new file mode 100644 index 0000000..fce3165 --- /dev/null +++ b/node_modules/lodash/fp/nthArg.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('nthArg', require('../nthArg')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/number.js b/node_modules/lodash/fp/number.js new file mode 100644 index 0000000..5c10b88 --- /dev/null +++ b/node_modules/lodash/fp/number.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../number')); diff --git a/node_modules/lodash/fp/object.js b/node_modules/lodash/fp/object.js new file mode 100644 index 0000000..ae39a13 --- /dev/null +++ b/node_modules/lodash/fp/object.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../object')); diff --git a/node_modules/lodash/fp/omit.js b/node_modules/lodash/fp/omit.js new file mode 100644 index 0000000..fd68529 --- /dev/null +++ b/node_modules/lodash/fp/omit.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('omit', require('../omit')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/omitAll.js b/node_modules/lodash/fp/omitAll.js new file mode 100644 index 0000000..144cf4b --- /dev/null +++ b/node_modules/lodash/fp/omitAll.js @@ -0,0 +1 @@ +module.exports = require('./omit'); diff --git a/node_modules/lodash/fp/omitBy.js b/node_modules/lodash/fp/omitBy.js new file mode 100644 index 0000000..90df738 --- /dev/null +++ b/node_modules/lodash/fp/omitBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('omitBy', require('../omitBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/once.js b/node_modules/lodash/fp/once.js new file mode 100644 index 0000000..f8f0a5c --- /dev/null +++ b/node_modules/lodash/fp/once.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('once', require('../once'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/orderBy.js b/node_modules/lodash/fp/orderBy.js new file mode 100644 index 0000000..848e210 --- /dev/null +++ b/node_modules/lodash/fp/orderBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('orderBy', require('../orderBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/over.js b/node_modules/lodash/fp/over.js new file mode 100644 index 0000000..01eba7b --- /dev/null +++ b/node_modules/lodash/fp/over.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('over', require('../over')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/overArgs.js b/node_modules/lodash/fp/overArgs.js new file mode 100644 index 0000000..738556f --- /dev/null +++ b/node_modules/lodash/fp/overArgs.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('overArgs', require('../overArgs')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/overEvery.js b/node_modules/lodash/fp/overEvery.js new file mode 100644 index 0000000..9f5a032 --- /dev/null +++ b/node_modules/lodash/fp/overEvery.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('overEvery', require('../overEvery')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/overSome.js b/node_modules/lodash/fp/overSome.js new file mode 100644 index 0000000..15939d5 --- /dev/null +++ b/node_modules/lodash/fp/overSome.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('overSome', require('../overSome')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pad.js b/node_modules/lodash/fp/pad.js new file mode 100644 index 0000000..f1dea4a --- /dev/null +++ b/node_modules/lodash/fp/pad.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pad', require('../pad')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/padChars.js b/node_modules/lodash/fp/padChars.js new file mode 100644 index 0000000..d6e0804 --- /dev/null +++ b/node_modules/lodash/fp/padChars.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padChars', require('../pad')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/padCharsEnd.js b/node_modules/lodash/fp/padCharsEnd.js new file mode 100644 index 0000000..d4ab79a --- /dev/null +++ b/node_modules/lodash/fp/padCharsEnd.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padCharsEnd', require('../padEnd')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/padCharsStart.js b/node_modules/lodash/fp/padCharsStart.js new file mode 100644 index 0000000..a08a300 --- /dev/null +++ b/node_modules/lodash/fp/padCharsStart.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padCharsStart', require('../padStart')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/padEnd.js b/node_modules/lodash/fp/padEnd.js new file mode 100644 index 0000000..a8522ec --- /dev/null +++ b/node_modules/lodash/fp/padEnd.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padEnd', require('../padEnd')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/padStart.js b/node_modules/lodash/fp/padStart.js new file mode 100644 index 0000000..f4ca79d --- /dev/null +++ b/node_modules/lodash/fp/padStart.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padStart', require('../padStart')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/parseInt.js b/node_modules/lodash/fp/parseInt.js new file mode 100644 index 0000000..27314cc --- /dev/null +++ b/node_modules/lodash/fp/parseInt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('parseInt', require('../parseInt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/partial.js b/node_modules/lodash/fp/partial.js new file mode 100644 index 0000000..5d46015 --- /dev/null +++ b/node_modules/lodash/fp/partial.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('partial', require('../partial')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/partialRight.js b/node_modules/lodash/fp/partialRight.js new file mode 100644 index 0000000..7f05fed --- /dev/null +++ b/node_modules/lodash/fp/partialRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('partialRight', require('../partialRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/partition.js b/node_modules/lodash/fp/partition.js new file mode 100644 index 0000000..2ebcacc --- /dev/null +++ b/node_modules/lodash/fp/partition.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('partition', require('../partition')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/path.js b/node_modules/lodash/fp/path.js new file mode 100644 index 0000000..b29cfb2 --- /dev/null +++ b/node_modules/lodash/fp/path.js @@ -0,0 +1 @@ +module.exports = require('./get'); diff --git a/node_modules/lodash/fp/pathEq.js b/node_modules/lodash/fp/pathEq.js new file mode 100644 index 0000000..36c027a --- /dev/null +++ b/node_modules/lodash/fp/pathEq.js @@ -0,0 +1 @@ +module.exports = require('./matchesProperty'); diff --git a/node_modules/lodash/fp/pathOr.js b/node_modules/lodash/fp/pathOr.js new file mode 100644 index 0000000..4ab5820 --- /dev/null +++ b/node_modules/lodash/fp/pathOr.js @@ -0,0 +1 @@ +module.exports = require('./getOr'); diff --git a/node_modules/lodash/fp/paths.js b/node_modules/lodash/fp/paths.js new file mode 100644 index 0000000..1eb7950 --- /dev/null +++ b/node_modules/lodash/fp/paths.js @@ -0,0 +1 @@ +module.exports = require('./at'); diff --git a/node_modules/lodash/fp/pick.js b/node_modules/lodash/fp/pick.js new file mode 100644 index 0000000..197393d --- /dev/null +++ b/node_modules/lodash/fp/pick.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pick', require('../pick')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pickAll.js b/node_modules/lodash/fp/pickAll.js new file mode 100644 index 0000000..a8ecd46 --- /dev/null +++ b/node_modules/lodash/fp/pickAll.js @@ -0,0 +1 @@ +module.exports = require('./pick'); diff --git a/node_modules/lodash/fp/pickBy.js b/node_modules/lodash/fp/pickBy.js new file mode 100644 index 0000000..d832d16 --- /dev/null +++ b/node_modules/lodash/fp/pickBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pickBy', require('../pickBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pipe.js b/node_modules/lodash/fp/pipe.js new file mode 100644 index 0000000..b2e1e2c --- /dev/null +++ b/node_modules/lodash/fp/pipe.js @@ -0,0 +1 @@ +module.exports = require('./flow'); diff --git a/node_modules/lodash/fp/placeholder.js b/node_modules/lodash/fp/placeholder.js new file mode 100644 index 0000000..1ce1739 --- /dev/null +++ b/node_modules/lodash/fp/placeholder.js @@ -0,0 +1,6 @@ +/** + * The default argument placeholder value for methods. + * + * @type {Object} + */ +module.exports = {}; diff --git a/node_modules/lodash/fp/plant.js b/node_modules/lodash/fp/plant.js new file mode 100644 index 0000000..eca8f32 --- /dev/null +++ b/node_modules/lodash/fp/plant.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('plant', require('../plant'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pluck.js b/node_modules/lodash/fp/pluck.js new file mode 100644 index 0000000..0d1e1ab --- /dev/null +++ b/node_modules/lodash/fp/pluck.js @@ -0,0 +1 @@ +module.exports = require('./map'); diff --git a/node_modules/lodash/fp/prop.js b/node_modules/lodash/fp/prop.js new file mode 100644 index 0000000..b29cfb2 --- /dev/null +++ b/node_modules/lodash/fp/prop.js @@ -0,0 +1 @@ +module.exports = require('./get'); diff --git a/node_modules/lodash/fp/propEq.js b/node_modules/lodash/fp/propEq.js new file mode 100644 index 0000000..36c027a --- /dev/null +++ b/node_modules/lodash/fp/propEq.js @@ -0,0 +1 @@ +module.exports = require('./matchesProperty'); diff --git a/node_modules/lodash/fp/propOr.js b/node_modules/lodash/fp/propOr.js new file mode 100644 index 0000000..4ab5820 --- /dev/null +++ b/node_modules/lodash/fp/propOr.js @@ -0,0 +1 @@ +module.exports = require('./getOr'); diff --git a/node_modules/lodash/fp/property.js b/node_modules/lodash/fp/property.js new file mode 100644 index 0000000..b29cfb2 --- /dev/null +++ b/node_modules/lodash/fp/property.js @@ -0,0 +1 @@ +module.exports = require('./get'); diff --git a/node_modules/lodash/fp/propertyOf.js b/node_modules/lodash/fp/propertyOf.js new file mode 100644 index 0000000..f6273ee --- /dev/null +++ b/node_modules/lodash/fp/propertyOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('propertyOf', require('../get')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/props.js b/node_modules/lodash/fp/props.js new file mode 100644 index 0000000..1eb7950 --- /dev/null +++ b/node_modules/lodash/fp/props.js @@ -0,0 +1 @@ +module.exports = require('./at'); diff --git a/node_modules/lodash/fp/pull.js b/node_modules/lodash/fp/pull.js new file mode 100644 index 0000000..8d7084f --- /dev/null +++ b/node_modules/lodash/fp/pull.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pull', require('../pull')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pullAll.js b/node_modules/lodash/fp/pullAll.js new file mode 100644 index 0000000..98d5c9a --- /dev/null +++ b/node_modules/lodash/fp/pullAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pullAll', require('../pullAll')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pullAllBy.js b/node_modules/lodash/fp/pullAllBy.js new file mode 100644 index 0000000..876bc3b --- /dev/null +++ b/node_modules/lodash/fp/pullAllBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pullAllBy', require('../pullAllBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pullAllWith.js b/node_modules/lodash/fp/pullAllWith.js new file mode 100644 index 0000000..f71ba4d --- /dev/null +++ b/node_modules/lodash/fp/pullAllWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pullAllWith', require('../pullAllWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pullAt.js b/node_modules/lodash/fp/pullAt.js new file mode 100644 index 0000000..e8b3bb6 --- /dev/null +++ b/node_modules/lodash/fp/pullAt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pullAt', require('../pullAt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/random.js b/node_modules/lodash/fp/random.js new file mode 100644 index 0000000..99d852e --- /dev/null +++ b/node_modules/lodash/fp/random.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('random', require('../random')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/range.js b/node_modules/lodash/fp/range.js new file mode 100644 index 0000000..a6bb591 --- /dev/null +++ b/node_modules/lodash/fp/range.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('range', require('../range')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/rangeRight.js b/node_modules/lodash/fp/rangeRight.js new file mode 100644 index 0000000..fdb712f --- /dev/null +++ b/node_modules/lodash/fp/rangeRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rangeRight', require('../rangeRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/rangeStep.js b/node_modules/lodash/fp/rangeStep.js new file mode 100644 index 0000000..d72dfc2 --- /dev/null +++ b/node_modules/lodash/fp/rangeStep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rangeStep', require('../range')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/rangeStepRight.js b/node_modules/lodash/fp/rangeStepRight.js new file mode 100644 index 0000000..8b2a67b --- /dev/null +++ b/node_modules/lodash/fp/rangeStepRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rangeStepRight', require('../rangeRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/rearg.js b/node_modules/lodash/fp/rearg.js new file mode 100644 index 0000000..678e02a --- /dev/null +++ b/node_modules/lodash/fp/rearg.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rearg', require('../rearg')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/reduce.js b/node_modules/lodash/fp/reduce.js new file mode 100644 index 0000000..4cef0a0 --- /dev/null +++ b/node_modules/lodash/fp/reduce.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('reduce', require('../reduce')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/reduceRight.js b/node_modules/lodash/fp/reduceRight.js new file mode 100644 index 0000000..caf5bb5 --- /dev/null +++ b/node_modules/lodash/fp/reduceRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('reduceRight', require('../reduceRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/reject.js b/node_modules/lodash/fp/reject.js new file mode 100644 index 0000000..c163273 --- /dev/null +++ b/node_modules/lodash/fp/reject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('reject', require('../reject')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/remove.js b/node_modules/lodash/fp/remove.js new file mode 100644 index 0000000..e9d1327 --- /dev/null +++ b/node_modules/lodash/fp/remove.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('remove', require('../remove')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/repeat.js b/node_modules/lodash/fp/repeat.js new file mode 100644 index 0000000..08470f2 --- /dev/null +++ b/node_modules/lodash/fp/repeat.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('repeat', require('../repeat')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/replace.js b/node_modules/lodash/fp/replace.js new file mode 100644 index 0000000..2227db6 --- /dev/null +++ b/node_modules/lodash/fp/replace.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('replace', require('../replace')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/rest.js b/node_modules/lodash/fp/rest.js new file mode 100644 index 0000000..c1f3d64 --- /dev/null +++ b/node_modules/lodash/fp/rest.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rest', require('../rest')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/restFrom.js b/node_modules/lodash/fp/restFrom.js new file mode 100644 index 0000000..714e42b --- /dev/null +++ b/node_modules/lodash/fp/restFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('restFrom', require('../rest')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/result.js b/node_modules/lodash/fp/result.js new file mode 100644 index 0000000..f86ce07 --- /dev/null +++ b/node_modules/lodash/fp/result.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('result', require('../result')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/reverse.js b/node_modules/lodash/fp/reverse.js new file mode 100644 index 0000000..07c9f5e --- /dev/null +++ b/node_modules/lodash/fp/reverse.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('reverse', require('../reverse')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/round.js b/node_modules/lodash/fp/round.js new file mode 100644 index 0000000..4c0e5c8 --- /dev/null +++ b/node_modules/lodash/fp/round.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('round', require('../round')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sample.js b/node_modules/lodash/fp/sample.js new file mode 100644 index 0000000..6bea125 --- /dev/null +++ b/node_modules/lodash/fp/sample.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sample', require('../sample'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sampleSize.js b/node_modules/lodash/fp/sampleSize.js new file mode 100644 index 0000000..359ed6f --- /dev/null +++ b/node_modules/lodash/fp/sampleSize.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sampleSize', require('../sampleSize')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/seq.js b/node_modules/lodash/fp/seq.js new file mode 100644 index 0000000..d8f42b0 --- /dev/null +++ b/node_modules/lodash/fp/seq.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../seq')); diff --git a/node_modules/lodash/fp/set.js b/node_modules/lodash/fp/set.js new file mode 100644 index 0000000..0b56a56 --- /dev/null +++ b/node_modules/lodash/fp/set.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('set', require('../set')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/setWith.js b/node_modules/lodash/fp/setWith.js new file mode 100644 index 0000000..0b58495 --- /dev/null +++ b/node_modules/lodash/fp/setWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('setWith', require('../setWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/shuffle.js b/node_modules/lodash/fp/shuffle.js new file mode 100644 index 0000000..aa3a1ca --- /dev/null +++ b/node_modules/lodash/fp/shuffle.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('shuffle', require('../shuffle'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/size.js b/node_modules/lodash/fp/size.js new file mode 100644 index 0000000..7490136 --- /dev/null +++ b/node_modules/lodash/fp/size.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('size', require('../size'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/slice.js b/node_modules/lodash/fp/slice.js new file mode 100644 index 0000000..15945d3 --- /dev/null +++ b/node_modules/lodash/fp/slice.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('slice', require('../slice')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/snakeCase.js b/node_modules/lodash/fp/snakeCase.js new file mode 100644 index 0000000..a0ff780 --- /dev/null +++ b/node_modules/lodash/fp/snakeCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('snakeCase', require('../snakeCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/some.js b/node_modules/lodash/fp/some.js new file mode 100644 index 0000000..a4fa2d0 --- /dev/null +++ b/node_modules/lodash/fp/some.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('some', require('../some')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortBy.js b/node_modules/lodash/fp/sortBy.js new file mode 100644 index 0000000..e0790ad --- /dev/null +++ b/node_modules/lodash/fp/sortBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortBy', require('../sortBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedIndex.js b/node_modules/lodash/fp/sortedIndex.js new file mode 100644 index 0000000..364a054 --- /dev/null +++ b/node_modules/lodash/fp/sortedIndex.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedIndex', require('../sortedIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedIndexBy.js b/node_modules/lodash/fp/sortedIndexBy.js new file mode 100644 index 0000000..9593dbd --- /dev/null +++ b/node_modules/lodash/fp/sortedIndexBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedIndexBy', require('../sortedIndexBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedIndexOf.js b/node_modules/lodash/fp/sortedIndexOf.js new file mode 100644 index 0000000..c9084ca --- /dev/null +++ b/node_modules/lodash/fp/sortedIndexOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedIndexOf', require('../sortedIndexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedLastIndex.js b/node_modules/lodash/fp/sortedLastIndex.js new file mode 100644 index 0000000..47fe241 --- /dev/null +++ b/node_modules/lodash/fp/sortedLastIndex.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedLastIndex', require('../sortedLastIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedLastIndexBy.js b/node_modules/lodash/fp/sortedLastIndexBy.js new file mode 100644 index 0000000..0f9a347 --- /dev/null +++ b/node_modules/lodash/fp/sortedLastIndexBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedLastIndexBy', require('../sortedLastIndexBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedLastIndexOf.js b/node_modules/lodash/fp/sortedLastIndexOf.js new file mode 100644 index 0000000..0d4d932 --- /dev/null +++ b/node_modules/lodash/fp/sortedLastIndexOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedLastIndexOf', require('../sortedLastIndexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedUniq.js b/node_modules/lodash/fp/sortedUniq.js new file mode 100644 index 0000000..882d283 --- /dev/null +++ b/node_modules/lodash/fp/sortedUniq.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedUniq', require('../sortedUniq'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedUniqBy.js b/node_modules/lodash/fp/sortedUniqBy.js new file mode 100644 index 0000000..033db91 --- /dev/null +++ b/node_modules/lodash/fp/sortedUniqBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedUniqBy', require('../sortedUniqBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/split.js b/node_modules/lodash/fp/split.js new file mode 100644 index 0000000..14de1a7 --- /dev/null +++ b/node_modules/lodash/fp/split.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('split', require('../split')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/spread.js b/node_modules/lodash/fp/spread.js new file mode 100644 index 0000000..2d11b70 --- /dev/null +++ b/node_modules/lodash/fp/spread.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('spread', require('../spread')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/spreadFrom.js b/node_modules/lodash/fp/spreadFrom.js new file mode 100644 index 0000000..0b630df --- /dev/null +++ b/node_modules/lodash/fp/spreadFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('spreadFrom', require('../spread')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/startCase.js b/node_modules/lodash/fp/startCase.js new file mode 100644 index 0000000..ada98c9 --- /dev/null +++ b/node_modules/lodash/fp/startCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('startCase', require('../startCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/startsWith.js b/node_modules/lodash/fp/startsWith.js new file mode 100644 index 0000000..985e2f2 --- /dev/null +++ b/node_modules/lodash/fp/startsWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('startsWith', require('../startsWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/string.js b/node_modules/lodash/fp/string.js new file mode 100644 index 0000000..773b037 --- /dev/null +++ b/node_modules/lodash/fp/string.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../string')); diff --git a/node_modules/lodash/fp/stubArray.js b/node_modules/lodash/fp/stubArray.js new file mode 100644 index 0000000..cd604cb --- /dev/null +++ b/node_modules/lodash/fp/stubArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubArray', require('../stubArray'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/stubFalse.js b/node_modules/lodash/fp/stubFalse.js new file mode 100644 index 0000000..3296664 --- /dev/null +++ b/node_modules/lodash/fp/stubFalse.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubFalse', require('../stubFalse'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/stubObject.js b/node_modules/lodash/fp/stubObject.js new file mode 100644 index 0000000..c6c8ec4 --- /dev/null +++ b/node_modules/lodash/fp/stubObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubObject', require('../stubObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/stubString.js b/node_modules/lodash/fp/stubString.js new file mode 100644 index 0000000..701051e --- /dev/null +++ b/node_modules/lodash/fp/stubString.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubString', require('../stubString'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/stubTrue.js b/node_modules/lodash/fp/stubTrue.js new file mode 100644 index 0000000..9249082 --- /dev/null +++ b/node_modules/lodash/fp/stubTrue.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubTrue', require('../stubTrue'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/subtract.js b/node_modules/lodash/fp/subtract.js new file mode 100644 index 0000000..d32b16d --- /dev/null +++ b/node_modules/lodash/fp/subtract.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('subtract', require('../subtract')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sum.js b/node_modules/lodash/fp/sum.js new file mode 100644 index 0000000..5cce12b --- /dev/null +++ b/node_modules/lodash/fp/sum.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sum', require('../sum'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sumBy.js b/node_modules/lodash/fp/sumBy.js new file mode 100644 index 0000000..c882656 --- /dev/null +++ b/node_modules/lodash/fp/sumBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sumBy', require('../sumBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/symmetricDifference.js b/node_modules/lodash/fp/symmetricDifference.js new file mode 100644 index 0000000..78c16ad --- /dev/null +++ b/node_modules/lodash/fp/symmetricDifference.js @@ -0,0 +1 @@ +module.exports = require('./xor'); diff --git a/node_modules/lodash/fp/symmetricDifferenceBy.js b/node_modules/lodash/fp/symmetricDifferenceBy.js new file mode 100644 index 0000000..298fc7f --- /dev/null +++ b/node_modules/lodash/fp/symmetricDifferenceBy.js @@ -0,0 +1 @@ +module.exports = require('./xorBy'); diff --git a/node_modules/lodash/fp/symmetricDifferenceWith.js b/node_modules/lodash/fp/symmetricDifferenceWith.js new file mode 100644 index 0000000..70bc6fa --- /dev/null +++ b/node_modules/lodash/fp/symmetricDifferenceWith.js @@ -0,0 +1 @@ +module.exports = require('./xorWith'); diff --git a/node_modules/lodash/fp/tail.js b/node_modules/lodash/fp/tail.js new file mode 100644 index 0000000..f122f0a --- /dev/null +++ b/node_modules/lodash/fp/tail.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('tail', require('../tail'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/take.js b/node_modules/lodash/fp/take.js new file mode 100644 index 0000000..9af98a7 --- /dev/null +++ b/node_modules/lodash/fp/take.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('take', require('../take')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/takeLast.js b/node_modules/lodash/fp/takeLast.js new file mode 100644 index 0000000..e98c84a --- /dev/null +++ b/node_modules/lodash/fp/takeLast.js @@ -0,0 +1 @@ +module.exports = require('./takeRight'); diff --git a/node_modules/lodash/fp/takeLastWhile.js b/node_modules/lodash/fp/takeLastWhile.js new file mode 100644 index 0000000..5367968 --- /dev/null +++ b/node_modules/lodash/fp/takeLastWhile.js @@ -0,0 +1 @@ +module.exports = require('./takeRightWhile'); diff --git a/node_modules/lodash/fp/takeRight.js b/node_modules/lodash/fp/takeRight.js new file mode 100644 index 0000000..b82950a --- /dev/null +++ b/node_modules/lodash/fp/takeRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('takeRight', require('../takeRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/takeRightWhile.js b/node_modules/lodash/fp/takeRightWhile.js new file mode 100644 index 0000000..8ffb0a2 --- /dev/null +++ b/node_modules/lodash/fp/takeRightWhile.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('takeRightWhile', require('../takeRightWhile')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/takeWhile.js b/node_modules/lodash/fp/takeWhile.js new file mode 100644 index 0000000..2813664 --- /dev/null +++ b/node_modules/lodash/fp/takeWhile.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('takeWhile', require('../takeWhile')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/tap.js b/node_modules/lodash/fp/tap.js new file mode 100644 index 0000000..d33ad6e --- /dev/null +++ b/node_modules/lodash/fp/tap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('tap', require('../tap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/template.js b/node_modules/lodash/fp/template.js new file mode 100644 index 0000000..74857e1 --- /dev/null +++ b/node_modules/lodash/fp/template.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('template', require('../template')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/templateSettings.js b/node_modules/lodash/fp/templateSettings.js new file mode 100644 index 0000000..7bcc0a8 --- /dev/null +++ b/node_modules/lodash/fp/templateSettings.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('templateSettings', require('../templateSettings'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/throttle.js b/node_modules/lodash/fp/throttle.js new file mode 100644 index 0000000..77fff14 --- /dev/null +++ b/node_modules/lodash/fp/throttle.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('throttle', require('../throttle')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/thru.js b/node_modules/lodash/fp/thru.js new file mode 100644 index 0000000..d42b3b1 --- /dev/null +++ b/node_modules/lodash/fp/thru.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('thru', require('../thru')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/times.js b/node_modules/lodash/fp/times.js new file mode 100644 index 0000000..0dab06d --- /dev/null +++ b/node_modules/lodash/fp/times.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('times', require('../times')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toArray.js b/node_modules/lodash/fp/toArray.js new file mode 100644 index 0000000..f0c360a --- /dev/null +++ b/node_modules/lodash/fp/toArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toArray', require('../toArray'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toFinite.js b/node_modules/lodash/fp/toFinite.js new file mode 100644 index 0000000..3a47687 --- /dev/null +++ b/node_modules/lodash/fp/toFinite.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toFinite', require('../toFinite'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toInteger.js b/node_modules/lodash/fp/toInteger.js new file mode 100644 index 0000000..e0af6a7 --- /dev/null +++ b/node_modules/lodash/fp/toInteger.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toInteger', require('../toInteger'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toIterator.js b/node_modules/lodash/fp/toIterator.js new file mode 100644 index 0000000..65e6baa --- /dev/null +++ b/node_modules/lodash/fp/toIterator.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toIterator', require('../toIterator'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toJSON.js b/node_modules/lodash/fp/toJSON.js new file mode 100644 index 0000000..2d718d0 --- /dev/null +++ b/node_modules/lodash/fp/toJSON.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toJSON', require('../toJSON'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toLength.js b/node_modules/lodash/fp/toLength.js new file mode 100644 index 0000000..b97cdd9 --- /dev/null +++ b/node_modules/lodash/fp/toLength.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toLength', require('../toLength'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toLower.js b/node_modules/lodash/fp/toLower.js new file mode 100644 index 0000000..616ef36 --- /dev/null +++ b/node_modules/lodash/fp/toLower.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toLower', require('../toLower'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toNumber.js b/node_modules/lodash/fp/toNumber.js new file mode 100644 index 0000000..d0c6f4d --- /dev/null +++ b/node_modules/lodash/fp/toNumber.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toNumber', require('../toNumber'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toPairs.js b/node_modules/lodash/fp/toPairs.js new file mode 100644 index 0000000..af78378 --- /dev/null +++ b/node_modules/lodash/fp/toPairs.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toPairs', require('../toPairs'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toPairsIn.js b/node_modules/lodash/fp/toPairsIn.js new file mode 100644 index 0000000..66504ab --- /dev/null +++ b/node_modules/lodash/fp/toPairsIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toPairsIn', require('../toPairsIn'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toPath.js b/node_modules/lodash/fp/toPath.js new file mode 100644 index 0000000..b4d5e50 --- /dev/null +++ b/node_modules/lodash/fp/toPath.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toPath', require('../toPath'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toPlainObject.js b/node_modules/lodash/fp/toPlainObject.js new file mode 100644 index 0000000..278bb86 --- /dev/null +++ b/node_modules/lodash/fp/toPlainObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toPlainObject', require('../toPlainObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toSafeInteger.js b/node_modules/lodash/fp/toSafeInteger.js new file mode 100644 index 0000000..367a26f --- /dev/null +++ b/node_modules/lodash/fp/toSafeInteger.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toSafeInteger', require('../toSafeInteger'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toString.js b/node_modules/lodash/fp/toString.js new file mode 100644 index 0000000..cec4f8e --- /dev/null +++ b/node_modules/lodash/fp/toString.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toString', require('../toString'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toUpper.js b/node_modules/lodash/fp/toUpper.js new file mode 100644 index 0000000..54f9a56 --- /dev/null +++ b/node_modules/lodash/fp/toUpper.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toUpper', require('../toUpper'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/transform.js b/node_modules/lodash/fp/transform.js new file mode 100644 index 0000000..759d088 --- /dev/null +++ b/node_modules/lodash/fp/transform.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('transform', require('../transform')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/trim.js b/node_modules/lodash/fp/trim.js new file mode 100644 index 0000000..e6319a7 --- /dev/null +++ b/node_modules/lodash/fp/trim.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trim', require('../trim')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/trimChars.js b/node_modules/lodash/fp/trimChars.js new file mode 100644 index 0000000..c9294de --- /dev/null +++ b/node_modules/lodash/fp/trimChars.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimChars', require('../trim')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/trimCharsEnd.js b/node_modules/lodash/fp/trimCharsEnd.js new file mode 100644 index 0000000..284bc2f --- /dev/null +++ b/node_modules/lodash/fp/trimCharsEnd.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimCharsEnd', require('../trimEnd')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/trimCharsStart.js b/node_modules/lodash/fp/trimCharsStart.js new file mode 100644 index 0000000..ff0ee65 --- /dev/null +++ b/node_modules/lodash/fp/trimCharsStart.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimCharsStart', require('../trimStart')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/trimEnd.js b/node_modules/lodash/fp/trimEnd.js new file mode 100644 index 0000000..7190880 --- /dev/null +++ b/node_modules/lodash/fp/trimEnd.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimEnd', require('../trimEnd')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/trimStart.js b/node_modules/lodash/fp/trimStart.js new file mode 100644 index 0000000..fda902c --- /dev/null +++ b/node_modules/lodash/fp/trimStart.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimStart', require('../trimStart')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/truncate.js b/node_modules/lodash/fp/truncate.js new file mode 100644 index 0000000..d265c1d --- /dev/null +++ b/node_modules/lodash/fp/truncate.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('truncate', require('../truncate')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unapply.js b/node_modules/lodash/fp/unapply.js new file mode 100644 index 0000000..c5dfe77 --- /dev/null +++ b/node_modules/lodash/fp/unapply.js @@ -0,0 +1 @@ +module.exports = require('./rest'); diff --git a/node_modules/lodash/fp/unary.js b/node_modules/lodash/fp/unary.js new file mode 100644 index 0000000..286c945 --- /dev/null +++ b/node_modules/lodash/fp/unary.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unary', require('../unary'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unescape.js b/node_modules/lodash/fp/unescape.js new file mode 100644 index 0000000..fddcb46 --- /dev/null +++ b/node_modules/lodash/fp/unescape.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unescape', require('../unescape'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/union.js b/node_modules/lodash/fp/union.js new file mode 100644 index 0000000..ef8228d --- /dev/null +++ b/node_modules/lodash/fp/union.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('union', require('../union')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unionBy.js b/node_modules/lodash/fp/unionBy.js new file mode 100644 index 0000000..603687a --- /dev/null +++ b/node_modules/lodash/fp/unionBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unionBy', require('../unionBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unionWith.js b/node_modules/lodash/fp/unionWith.js new file mode 100644 index 0000000..65bb3a7 --- /dev/null +++ b/node_modules/lodash/fp/unionWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unionWith', require('../unionWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/uniq.js b/node_modules/lodash/fp/uniq.js new file mode 100644 index 0000000..bc18524 --- /dev/null +++ b/node_modules/lodash/fp/uniq.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('uniq', require('../uniq'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/uniqBy.js b/node_modules/lodash/fp/uniqBy.js new file mode 100644 index 0000000..634c6a8 --- /dev/null +++ b/node_modules/lodash/fp/uniqBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('uniqBy', require('../uniqBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/uniqWith.js b/node_modules/lodash/fp/uniqWith.js new file mode 100644 index 0000000..0ec601a --- /dev/null +++ b/node_modules/lodash/fp/uniqWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('uniqWith', require('../uniqWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/uniqueId.js b/node_modules/lodash/fp/uniqueId.js new file mode 100644 index 0000000..aa8fc2f --- /dev/null +++ b/node_modules/lodash/fp/uniqueId.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('uniqueId', require('../uniqueId')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unnest.js b/node_modules/lodash/fp/unnest.js new file mode 100644 index 0000000..5d34060 --- /dev/null +++ b/node_modules/lodash/fp/unnest.js @@ -0,0 +1 @@ +module.exports = require('./flatten'); diff --git a/node_modules/lodash/fp/unset.js b/node_modules/lodash/fp/unset.js new file mode 100644 index 0000000..ea203a0 --- /dev/null +++ b/node_modules/lodash/fp/unset.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unset', require('../unset')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unzip.js b/node_modules/lodash/fp/unzip.js new file mode 100644 index 0000000..cc364b3 --- /dev/null +++ b/node_modules/lodash/fp/unzip.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unzip', require('../unzip'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unzipWith.js b/node_modules/lodash/fp/unzipWith.js new file mode 100644 index 0000000..182eaa1 --- /dev/null +++ b/node_modules/lodash/fp/unzipWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unzipWith', require('../unzipWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/update.js b/node_modules/lodash/fp/update.js new file mode 100644 index 0000000..b8ce2cc --- /dev/null +++ b/node_modules/lodash/fp/update.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('update', require('../update')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/updateWith.js b/node_modules/lodash/fp/updateWith.js new file mode 100644 index 0000000..d5e8282 --- /dev/null +++ b/node_modules/lodash/fp/updateWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('updateWith', require('../updateWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/upperCase.js b/node_modules/lodash/fp/upperCase.js new file mode 100644 index 0000000..c886f20 --- /dev/null +++ b/node_modules/lodash/fp/upperCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('upperCase', require('../upperCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/upperFirst.js b/node_modules/lodash/fp/upperFirst.js new file mode 100644 index 0000000..d8c04df --- /dev/null +++ b/node_modules/lodash/fp/upperFirst.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('upperFirst', require('../upperFirst'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/useWith.js b/node_modules/lodash/fp/useWith.js new file mode 100644 index 0000000..d8b3df5 --- /dev/null +++ b/node_modules/lodash/fp/useWith.js @@ -0,0 +1 @@ +module.exports = require('./overArgs'); diff --git a/node_modules/lodash/fp/util.js b/node_modules/lodash/fp/util.js new file mode 100644 index 0000000..18c00ba --- /dev/null +++ b/node_modules/lodash/fp/util.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../util')); diff --git a/node_modules/lodash/fp/value.js b/node_modules/lodash/fp/value.js new file mode 100644 index 0000000..555eec7 --- /dev/null +++ b/node_modules/lodash/fp/value.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('value', require('../value'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/valueOf.js b/node_modules/lodash/fp/valueOf.js new file mode 100644 index 0000000..f968807 --- /dev/null +++ b/node_modules/lodash/fp/valueOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('valueOf', require('../valueOf'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/values.js b/node_modules/lodash/fp/values.js new file mode 100644 index 0000000..2dfc561 --- /dev/null +++ b/node_modules/lodash/fp/values.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('values', require('../values'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/valuesIn.js b/node_modules/lodash/fp/valuesIn.js new file mode 100644 index 0000000..a1b2bb8 --- /dev/null +++ b/node_modules/lodash/fp/valuesIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('valuesIn', require('../valuesIn'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/where.js b/node_modules/lodash/fp/where.js new file mode 100644 index 0000000..3247f64 --- /dev/null +++ b/node_modules/lodash/fp/where.js @@ -0,0 +1 @@ +module.exports = require('./conformsTo'); diff --git a/node_modules/lodash/fp/whereEq.js b/node_modules/lodash/fp/whereEq.js new file mode 100644 index 0000000..29d1e1e --- /dev/null +++ b/node_modules/lodash/fp/whereEq.js @@ -0,0 +1 @@ +module.exports = require('./isMatch'); diff --git a/node_modules/lodash/fp/without.js b/node_modules/lodash/fp/without.js new file mode 100644 index 0000000..bad9e12 --- /dev/null +++ b/node_modules/lodash/fp/without.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('without', require('../without')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/words.js b/node_modules/lodash/fp/words.js new file mode 100644 index 0000000..4a90141 --- /dev/null +++ b/node_modules/lodash/fp/words.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('words', require('../words')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/wrap.js b/node_modules/lodash/fp/wrap.js new file mode 100644 index 0000000..e93bd8a --- /dev/null +++ b/node_modules/lodash/fp/wrap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrap', require('../wrap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/wrapperAt.js b/node_modules/lodash/fp/wrapperAt.js new file mode 100644 index 0000000..8f0a310 --- /dev/null +++ b/node_modules/lodash/fp/wrapperAt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperAt', require('../wrapperAt'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/wrapperChain.js b/node_modules/lodash/fp/wrapperChain.js new file mode 100644 index 0000000..2a48ea2 --- /dev/null +++ b/node_modules/lodash/fp/wrapperChain.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperChain', require('../wrapperChain'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/wrapperLodash.js b/node_modules/lodash/fp/wrapperLodash.js new file mode 100644 index 0000000..a7162d0 --- /dev/null +++ b/node_modules/lodash/fp/wrapperLodash.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperLodash', require('../wrapperLodash'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/wrapperReverse.js b/node_modules/lodash/fp/wrapperReverse.js new file mode 100644 index 0000000..e1481aa --- /dev/null +++ b/node_modules/lodash/fp/wrapperReverse.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperReverse', require('../wrapperReverse'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/wrapperValue.js b/node_modules/lodash/fp/wrapperValue.js new file mode 100644 index 0000000..8eb9112 --- /dev/null +++ b/node_modules/lodash/fp/wrapperValue.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperValue', require('../wrapperValue'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/xor.js b/node_modules/lodash/fp/xor.js new file mode 100644 index 0000000..29e2819 --- /dev/null +++ b/node_modules/lodash/fp/xor.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('xor', require('../xor')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/xorBy.js b/node_modules/lodash/fp/xorBy.js new file mode 100644 index 0000000..b355686 --- /dev/null +++ b/node_modules/lodash/fp/xorBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('xorBy', require('../xorBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/xorWith.js b/node_modules/lodash/fp/xorWith.js new file mode 100644 index 0000000..8e05739 --- /dev/null +++ b/node_modules/lodash/fp/xorWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('xorWith', require('../xorWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/zip.js b/node_modules/lodash/fp/zip.js new file mode 100644 index 0000000..69e147a --- /dev/null +++ b/node_modules/lodash/fp/zip.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zip', require('../zip')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/zipAll.js b/node_modules/lodash/fp/zipAll.js new file mode 100644 index 0000000..efa8ccb --- /dev/null +++ b/node_modules/lodash/fp/zipAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zipAll', require('../zip')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/zipObj.js b/node_modules/lodash/fp/zipObj.js new file mode 100644 index 0000000..f4a3453 --- /dev/null +++ b/node_modules/lodash/fp/zipObj.js @@ -0,0 +1 @@ +module.exports = require('./zipObject'); diff --git a/node_modules/lodash/fp/zipObject.js b/node_modules/lodash/fp/zipObject.js new file mode 100644 index 0000000..462dbb6 --- /dev/null +++ b/node_modules/lodash/fp/zipObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zipObject', require('../zipObject')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/zipObjectDeep.js b/node_modules/lodash/fp/zipObjectDeep.js new file mode 100644 index 0000000..53a5d33 --- /dev/null +++ b/node_modules/lodash/fp/zipObjectDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zipObjectDeep', require('../zipObjectDeep')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/zipWith.js b/node_modules/lodash/fp/zipWith.js new file mode 100644 index 0000000..c5cf9e2 --- /dev/null +++ b/node_modules/lodash/fp/zipWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zipWith', require('../zipWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fromPairs.js b/node_modules/lodash/fromPairs.js new file mode 100644 index 0000000..83548be --- /dev/null +++ b/node_modules/lodash/fromPairs.js @@ -0,0 +1,30 @@ +var baseAssignValue = require('./_baseAssignValue'); + +/** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ +function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + baseAssignValue(result, pair[0], pair[1]); + } + return result; +} + +module.exports = fromPairs; diff --git a/node_modules/lodash/function.js b/node_modules/lodash/function.js new file mode 100644 index 0000000..b0fc6d9 --- /dev/null +++ b/node_modules/lodash/function.js @@ -0,0 +1,25 @@ +module.exports = { + 'after': require('./after'), + 'ary': require('./ary'), + 'before': require('./before'), + 'bind': require('./bind'), + 'bindKey': require('./bindKey'), + 'curry': require('./curry'), + 'curryRight': require('./curryRight'), + 'debounce': require('./debounce'), + 'defer': require('./defer'), + 'delay': require('./delay'), + 'flip': require('./flip'), + 'memoize': require('./memoize'), + 'negate': require('./negate'), + 'once': require('./once'), + 'overArgs': require('./overArgs'), + 'partial': require('./partial'), + 'partialRight': require('./partialRight'), + 'rearg': require('./rearg'), + 'rest': require('./rest'), + 'spread': require('./spread'), + 'throttle': require('./throttle'), + 'unary': require('./unary'), + 'wrap': require('./wrap') +}; diff --git a/node_modules/lodash/functions.js b/node_modules/lodash/functions.js new file mode 100644 index 0000000..9722928 --- /dev/null +++ b/node_modules/lodash/functions.js @@ -0,0 +1,31 @@ +var baseFunctions = require('./_baseFunctions'), + keys = require('./keys'); + +/** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ +function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); +} + +module.exports = functions; diff --git a/node_modules/lodash/functionsIn.js b/node_modules/lodash/functionsIn.js new file mode 100644 index 0000000..f00345d --- /dev/null +++ b/node_modules/lodash/functionsIn.js @@ -0,0 +1,31 @@ +var baseFunctions = require('./_baseFunctions'), + keysIn = require('./keysIn'); + +/** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ +function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); +} + +module.exports = functionsIn; diff --git a/node_modules/lodash/get.js b/node_modules/lodash/get.js new file mode 100644 index 0000000..8805ff9 --- /dev/null +++ b/node_modules/lodash/get.js @@ -0,0 +1,33 @@ +var baseGet = require('./_baseGet'); + +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ +function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; +} + +module.exports = get; diff --git a/node_modules/lodash/groupBy.js b/node_modules/lodash/groupBy.js new file mode 100644 index 0000000..babf4f6 --- /dev/null +++ b/node_modules/lodash/groupBy.js @@ -0,0 +1,41 @@ +var baseAssignValue = require('./_baseAssignValue'), + createAggregator = require('./_createAggregator'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ +var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } +}); + +module.exports = groupBy; diff --git a/node_modules/lodash/gt.js b/node_modules/lodash/gt.js new file mode 100644 index 0000000..3a66282 --- /dev/null +++ b/node_modules/lodash/gt.js @@ -0,0 +1,29 @@ +var baseGt = require('./_baseGt'), + createRelationalOperation = require('./_createRelationalOperation'); + +/** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ +var gt = createRelationalOperation(baseGt); + +module.exports = gt; diff --git a/node_modules/lodash/gte.js b/node_modules/lodash/gte.js new file mode 100644 index 0000000..4180a68 --- /dev/null +++ b/node_modules/lodash/gte.js @@ -0,0 +1,30 @@ +var createRelationalOperation = require('./_createRelationalOperation'); + +/** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ +var gte = createRelationalOperation(function(value, other) { + return value >= other; +}); + +module.exports = gte; diff --git a/node_modules/lodash/has.js b/node_modules/lodash/has.js new file mode 100644 index 0000000..34df55e --- /dev/null +++ b/node_modules/lodash/has.js @@ -0,0 +1,35 @@ +var baseHas = require('./_baseHas'), + hasPath = require('./_hasPath'); + +/** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ +function has(object, path) { + return object != null && hasPath(object, path, baseHas); +} + +module.exports = has; diff --git a/node_modules/lodash/hasIn.js b/node_modules/lodash/hasIn.js new file mode 100644 index 0000000..06a3686 --- /dev/null +++ b/node_modules/lodash/hasIn.js @@ -0,0 +1,34 @@ +var baseHasIn = require('./_baseHasIn'), + hasPath = require('./_hasPath'); + +/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ +function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); +} + +module.exports = hasIn; diff --git a/node_modules/lodash/head.js b/node_modules/lodash/head.js new file mode 100644 index 0000000..dee9d1f --- /dev/null +++ b/node_modules/lodash/head.js @@ -0,0 +1,23 @@ +/** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ +function head(array) { + return (array && array.length) ? array[0] : undefined; +} + +module.exports = head; diff --git a/node_modules/lodash/identity.js b/node_modules/lodash/identity.js new file mode 100644 index 0000000..2d5d963 --- /dev/null +++ b/node_modules/lodash/identity.js @@ -0,0 +1,21 @@ +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ +function identity(value) { + return value; +} + +module.exports = identity; diff --git a/node_modules/lodash/inRange.js b/node_modules/lodash/inRange.js new file mode 100644 index 0000000..f20728d --- /dev/null +++ b/node_modules/lodash/inRange.js @@ -0,0 +1,55 @@ +var baseInRange = require('./_baseInRange'), + toFinite = require('./toFinite'), + toNumber = require('./toNumber'); + +/** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ +function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); +} + +module.exports = inRange; diff --git a/node_modules/lodash/includes.js b/node_modules/lodash/includes.js new file mode 100644 index 0000000..ae0deed --- /dev/null +++ b/node_modules/lodash/includes.js @@ -0,0 +1,53 @@ +var baseIndexOf = require('./_baseIndexOf'), + isArrayLike = require('./isArrayLike'), + isString = require('./isString'), + toInteger = require('./toInteger'), + values = require('./values'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ +function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); +} + +module.exports = includes; diff --git a/node_modules/lodash/index.js b/node_modules/lodash/index.js new file mode 100644 index 0000000..5d063e2 --- /dev/null +++ b/node_modules/lodash/index.js @@ -0,0 +1 @@ +module.exports = require('./lodash'); \ No newline at end of file diff --git a/node_modules/lodash/indexOf.js b/node_modules/lodash/indexOf.js new file mode 100644 index 0000000..3c644af --- /dev/null +++ b/node_modules/lodash/indexOf.js @@ -0,0 +1,42 @@ +var baseIndexOf = require('./_baseIndexOf'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ +function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); +} + +module.exports = indexOf; diff --git a/node_modules/lodash/initial.js b/node_modules/lodash/initial.js new file mode 100644 index 0000000..f47fc50 --- /dev/null +++ b/node_modules/lodash/initial.js @@ -0,0 +1,22 @@ +var baseSlice = require('./_baseSlice'); + +/** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ +function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; +} + +module.exports = initial; diff --git a/node_modules/lodash/intersection.js b/node_modules/lodash/intersection.js new file mode 100644 index 0000000..a94c135 --- /dev/null +++ b/node_modules/lodash/intersection.js @@ -0,0 +1,30 @@ +var arrayMap = require('./_arrayMap'), + baseIntersection = require('./_baseIntersection'), + baseRest = require('./_baseRest'), + castArrayLikeObject = require('./_castArrayLikeObject'); + +/** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ +var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; +}); + +module.exports = intersection; diff --git a/node_modules/lodash/intersectionBy.js b/node_modules/lodash/intersectionBy.js new file mode 100644 index 0000000..31461aa --- /dev/null +++ b/node_modules/lodash/intersectionBy.js @@ -0,0 +1,45 @@ +var arrayMap = require('./_arrayMap'), + baseIntersection = require('./_baseIntersection'), + baseIteratee = require('./_baseIteratee'), + baseRest = require('./_baseRest'), + castArrayLikeObject = require('./_castArrayLikeObject'), + last = require('./last'); + +/** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ +var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, baseIteratee(iteratee, 2)) + : []; +}); + +module.exports = intersectionBy; diff --git a/node_modules/lodash/intersectionWith.js b/node_modules/lodash/intersectionWith.js new file mode 100644 index 0000000..63cabfa --- /dev/null +++ b/node_modules/lodash/intersectionWith.js @@ -0,0 +1,41 @@ +var arrayMap = require('./_arrayMap'), + baseIntersection = require('./_baseIntersection'), + baseRest = require('./_baseRest'), + castArrayLikeObject = require('./_castArrayLikeObject'), + last = require('./last'); + +/** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ +var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; +}); + +module.exports = intersectionWith; diff --git a/node_modules/lodash/invert.js b/node_modules/lodash/invert.js new file mode 100644 index 0000000..8c47950 --- /dev/null +++ b/node_modules/lodash/invert.js @@ -0,0 +1,42 @@ +var constant = require('./constant'), + createInverter = require('./_createInverter'), + identity = require('./identity'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ +var invert = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + result[value] = key; +}, constant(identity)); + +module.exports = invert; diff --git a/node_modules/lodash/invertBy.js b/node_modules/lodash/invertBy.js new file mode 100644 index 0000000..3f4f7e5 --- /dev/null +++ b/node_modules/lodash/invertBy.js @@ -0,0 +1,56 @@ +var baseIteratee = require('./_baseIteratee'), + createInverter = require('./_createInverter'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ +var invertBy = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } +}, baseIteratee); + +module.exports = invertBy; diff --git a/node_modules/lodash/invoke.js b/node_modules/lodash/invoke.js new file mode 100644 index 0000000..97d51eb --- /dev/null +++ b/node_modules/lodash/invoke.js @@ -0,0 +1,24 @@ +var baseInvoke = require('./_baseInvoke'), + baseRest = require('./_baseRest'); + +/** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ +var invoke = baseRest(baseInvoke); + +module.exports = invoke; diff --git a/node_modules/lodash/invokeMap.js b/node_modules/lodash/invokeMap.js new file mode 100644 index 0000000..8da5126 --- /dev/null +++ b/node_modules/lodash/invokeMap.js @@ -0,0 +1,41 @@ +var apply = require('./_apply'), + baseEach = require('./_baseEach'), + baseInvoke = require('./_baseInvoke'), + baseRest = require('./_baseRest'), + isArrayLike = require('./isArrayLike'); + +/** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ +var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; +}); + +module.exports = invokeMap; diff --git a/node_modules/lodash/isArguments.js b/node_modules/lodash/isArguments.js new file mode 100644 index 0000000..8b9ed66 --- /dev/null +++ b/node_modules/lodash/isArguments.js @@ -0,0 +1,36 @@ +var baseIsArguments = require('./_baseIsArguments'), + isObjectLike = require('./isObjectLike'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; + +module.exports = isArguments; diff --git a/node_modules/lodash/isArray.js b/node_modules/lodash/isArray.js new file mode 100644 index 0000000..88ab55f --- /dev/null +++ b/node_modules/lodash/isArray.js @@ -0,0 +1,26 @@ +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +module.exports = isArray; diff --git a/node_modules/lodash/isArrayBuffer.js b/node_modules/lodash/isArrayBuffer.js new file mode 100644 index 0000000..12904a6 --- /dev/null +++ b/node_modules/lodash/isArrayBuffer.js @@ -0,0 +1,27 @@ +var baseIsArrayBuffer = require('./_baseIsArrayBuffer'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer; + +/** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ +var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + +module.exports = isArrayBuffer; diff --git a/node_modules/lodash/isArrayLike.js b/node_modules/lodash/isArrayLike.js new file mode 100644 index 0000000..0f96680 --- /dev/null +++ b/node_modules/lodash/isArrayLike.js @@ -0,0 +1,33 @@ +var isFunction = require('./isFunction'), + isLength = require('./isLength'); + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +module.exports = isArrayLike; diff --git a/node_modules/lodash/isArrayLikeObject.js b/node_modules/lodash/isArrayLikeObject.js new file mode 100644 index 0000000..6c4812a --- /dev/null +++ b/node_modules/lodash/isArrayLikeObject.js @@ -0,0 +1,33 @@ +var isArrayLike = require('./isArrayLike'), + isObjectLike = require('./isObjectLike'); + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +module.exports = isArrayLikeObject; diff --git a/node_modules/lodash/isBoolean.js b/node_modules/lodash/isBoolean.js new file mode 100644 index 0000000..a43ed4b --- /dev/null +++ b/node_modules/lodash/isBoolean.js @@ -0,0 +1,29 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]'; + +/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ +function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); +} + +module.exports = isBoolean; diff --git a/node_modules/lodash/isBuffer.js b/node_modules/lodash/isBuffer.js new file mode 100644 index 0000000..c103cc7 --- /dev/null +++ b/node_modules/lodash/isBuffer.js @@ -0,0 +1,38 @@ +var root = require('./_root'), + stubFalse = require('./stubFalse'); + +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +module.exports = isBuffer; diff --git a/node_modules/lodash/isDate.js b/node_modules/lodash/isDate.js new file mode 100644 index 0000000..7f0209f --- /dev/null +++ b/node_modules/lodash/isDate.js @@ -0,0 +1,27 @@ +var baseIsDate = require('./_baseIsDate'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsDate = nodeUtil && nodeUtil.isDate; + +/** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ +var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + +module.exports = isDate; diff --git a/node_modules/lodash/isElement.js b/node_modules/lodash/isElement.js new file mode 100644 index 0000000..76ae29c --- /dev/null +++ b/node_modules/lodash/isElement.js @@ -0,0 +1,25 @@ +var isObjectLike = require('./isObjectLike'), + isPlainObject = require('./isPlainObject'); + +/** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ +function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); +} + +module.exports = isElement; diff --git a/node_modules/lodash/isEmpty.js b/node_modules/lodash/isEmpty.js new file mode 100644 index 0000000..3597294 --- /dev/null +++ b/node_modules/lodash/isEmpty.js @@ -0,0 +1,77 @@ +var baseKeys = require('./_baseKeys'), + getTag = require('./_getTag'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isArrayLike = require('./isArrayLike'), + isBuffer = require('./isBuffer'), + isPrototype = require('./_isPrototype'), + isTypedArray = require('./isTypedArray'); + +/** `Object#toString` result references. */ +var mapTag = '[object Map]', + setTag = '[object Set]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ +function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; +} + +module.exports = isEmpty; diff --git a/node_modules/lodash/isEqual.js b/node_modules/lodash/isEqual.js new file mode 100644 index 0000000..5e23e76 --- /dev/null +++ b/node_modules/lodash/isEqual.js @@ -0,0 +1,35 @@ +var baseIsEqual = require('./_baseIsEqual'); + +/** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ +function isEqual(value, other) { + return baseIsEqual(value, other); +} + +module.exports = isEqual; diff --git a/node_modules/lodash/isEqualWith.js b/node_modules/lodash/isEqualWith.js new file mode 100644 index 0000000..21bdc7f --- /dev/null +++ b/node_modules/lodash/isEqualWith.js @@ -0,0 +1,41 @@ +var baseIsEqual = require('./_baseIsEqual'); + +/** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ +function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; +} + +module.exports = isEqualWith; diff --git a/node_modules/lodash/isError.js b/node_modules/lodash/isError.js new file mode 100644 index 0000000..b4f41e0 --- /dev/null +++ b/node_modules/lodash/isError.js @@ -0,0 +1,36 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'), + isPlainObject = require('./isPlainObject'); + +/** `Object#toString` result references. */ +var domExcTag = '[object DOMException]', + errorTag = '[object Error]'; + +/** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ +function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); +} + +module.exports = isError; diff --git a/node_modules/lodash/isFinite.js b/node_modules/lodash/isFinite.js new file mode 100644 index 0000000..601842b --- /dev/null +++ b/node_modules/lodash/isFinite.js @@ -0,0 +1,36 @@ +var root = require('./_root'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = root.isFinite; + +/** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ +function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); +} + +module.exports = isFinite; diff --git a/node_modules/lodash/isFunction.js b/node_modules/lodash/isFunction.js new file mode 100644 index 0000000..907a8cd --- /dev/null +++ b/node_modules/lodash/isFunction.js @@ -0,0 +1,37 @@ +var baseGetTag = require('./_baseGetTag'), + isObject = require('./isObject'); + +/** `Object#toString` result references. */ +var asyncTag = '[object AsyncFunction]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} + +module.exports = isFunction; diff --git a/node_modules/lodash/isInteger.js b/node_modules/lodash/isInteger.js new file mode 100644 index 0000000..66aa87d --- /dev/null +++ b/node_modules/lodash/isInteger.js @@ -0,0 +1,33 @@ +var toInteger = require('./toInteger'); + +/** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ +function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); +} + +module.exports = isInteger; diff --git a/node_modules/lodash/isLength.js b/node_modules/lodash/isLength.js new file mode 100644 index 0000000..3a95caa --- /dev/null +++ b/node_modules/lodash/isLength.js @@ -0,0 +1,35 @@ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +module.exports = isLength; diff --git a/node_modules/lodash/isMap.js b/node_modules/lodash/isMap.js new file mode 100644 index 0000000..44f8517 --- /dev/null +++ b/node_modules/lodash/isMap.js @@ -0,0 +1,27 @@ +var baseIsMap = require('./_baseIsMap'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsMap = nodeUtil && nodeUtil.isMap; + +/** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ +var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + +module.exports = isMap; diff --git a/node_modules/lodash/isMatch.js b/node_modules/lodash/isMatch.js new file mode 100644 index 0000000..9773a18 --- /dev/null +++ b/node_modules/lodash/isMatch.js @@ -0,0 +1,36 @@ +var baseIsMatch = require('./_baseIsMatch'), + getMatchData = require('./_getMatchData'); + +/** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ +function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); +} + +module.exports = isMatch; diff --git a/node_modules/lodash/isMatchWith.js b/node_modules/lodash/isMatchWith.js new file mode 100644 index 0000000..187b6a6 --- /dev/null +++ b/node_modules/lodash/isMatchWith.js @@ -0,0 +1,41 @@ +var baseIsMatch = require('./_baseIsMatch'), + getMatchData = require('./_getMatchData'); + +/** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ +function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); +} + +module.exports = isMatchWith; diff --git a/node_modules/lodash/isNaN.js b/node_modules/lodash/isNaN.js new file mode 100644 index 0000000..7d0d783 --- /dev/null +++ b/node_modules/lodash/isNaN.js @@ -0,0 +1,38 @@ +var isNumber = require('./isNumber'); + +/** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ +function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; +} + +module.exports = isNaN; diff --git a/node_modules/lodash/isNative.js b/node_modules/lodash/isNative.js new file mode 100644 index 0000000..f0cb8d5 --- /dev/null +++ b/node_modules/lodash/isNative.js @@ -0,0 +1,40 @@ +var baseIsNative = require('./_baseIsNative'), + isMaskable = require('./_isMaskable'); + +/** Error message constants. */ +var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.'; + +/** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ +function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); +} + +module.exports = isNative; diff --git a/node_modules/lodash/isNil.js b/node_modules/lodash/isNil.js new file mode 100644 index 0000000..79f0505 --- /dev/null +++ b/node_modules/lodash/isNil.js @@ -0,0 +1,25 @@ +/** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ +function isNil(value) { + return value == null; +} + +module.exports = isNil; diff --git a/node_modules/lodash/isNull.js b/node_modules/lodash/isNull.js new file mode 100644 index 0000000..c0a374d --- /dev/null +++ b/node_modules/lodash/isNull.js @@ -0,0 +1,22 @@ +/** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ +function isNull(value) { + return value === null; +} + +module.exports = isNull; diff --git a/node_modules/lodash/isNumber.js b/node_modules/lodash/isNumber.js new file mode 100644 index 0000000..cd34ee4 --- /dev/null +++ b/node_modules/lodash/isNumber.js @@ -0,0 +1,38 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var numberTag = '[object Number]'; + +/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ +function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); +} + +module.exports = isNumber; diff --git a/node_modules/lodash/isObject.js b/node_modules/lodash/isObject.js new file mode 100644 index 0000000..1dc8939 --- /dev/null +++ b/node_modules/lodash/isObject.js @@ -0,0 +1,31 @@ +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +module.exports = isObject; diff --git a/node_modules/lodash/isObjectLike.js b/node_modules/lodash/isObjectLike.js new file mode 100644 index 0000000..301716b --- /dev/null +++ b/node_modules/lodash/isObjectLike.js @@ -0,0 +1,29 @@ +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +module.exports = isObjectLike; diff --git a/node_modules/lodash/isPlainObject.js b/node_modules/lodash/isPlainObject.js new file mode 100644 index 0000000..2387373 --- /dev/null +++ b/node_modules/lodash/isPlainObject.js @@ -0,0 +1,62 @@ +var baseGetTag = require('./_baseGetTag'), + getPrototype = require('./_getPrototype'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; + +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; +} + +module.exports = isPlainObject; diff --git a/node_modules/lodash/isRegExp.js b/node_modules/lodash/isRegExp.js new file mode 100644 index 0000000..76c9b6e --- /dev/null +++ b/node_modules/lodash/isRegExp.js @@ -0,0 +1,27 @@ +var baseIsRegExp = require('./_baseIsRegExp'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp; + +/** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ +var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + +module.exports = isRegExp; diff --git a/node_modules/lodash/isSafeInteger.js b/node_modules/lodash/isSafeInteger.js new file mode 100644 index 0000000..2a48526 --- /dev/null +++ b/node_modules/lodash/isSafeInteger.js @@ -0,0 +1,37 @@ +var isInteger = require('./isInteger'); + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ +function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; +} + +module.exports = isSafeInteger; diff --git a/node_modules/lodash/isSet.js b/node_modules/lodash/isSet.js new file mode 100644 index 0000000..ab88bdf --- /dev/null +++ b/node_modules/lodash/isSet.js @@ -0,0 +1,27 @@ +var baseIsSet = require('./_baseIsSet'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsSet = nodeUtil && nodeUtil.isSet; + +/** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ +var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + +module.exports = isSet; diff --git a/node_modules/lodash/isString.js b/node_modules/lodash/isString.js new file mode 100644 index 0000000..627eb9c --- /dev/null +++ b/node_modules/lodash/isString.js @@ -0,0 +1,30 @@ +var baseGetTag = require('./_baseGetTag'), + isArray = require('./isArray'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var stringTag = '[object String]'; + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); +} + +module.exports = isString; diff --git a/node_modules/lodash/isSymbol.js b/node_modules/lodash/isSymbol.js new file mode 100644 index 0000000..dfb60b9 --- /dev/null +++ b/node_modules/lodash/isSymbol.js @@ -0,0 +1,29 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); +} + +module.exports = isSymbol; diff --git a/node_modules/lodash/isTypedArray.js b/node_modules/lodash/isTypedArray.js new file mode 100644 index 0000000..da3f8dd --- /dev/null +++ b/node_modules/lodash/isTypedArray.js @@ -0,0 +1,27 @@ +var baseIsTypedArray = require('./_baseIsTypedArray'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + +module.exports = isTypedArray; diff --git a/node_modules/lodash/isUndefined.js b/node_modules/lodash/isUndefined.js new file mode 100644 index 0000000..377d121 --- /dev/null +++ b/node_modules/lodash/isUndefined.js @@ -0,0 +1,22 @@ +/** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ +function isUndefined(value) { + return value === undefined; +} + +module.exports = isUndefined; diff --git a/node_modules/lodash/isWeakMap.js b/node_modules/lodash/isWeakMap.js new file mode 100644 index 0000000..8d36f66 --- /dev/null +++ b/node_modules/lodash/isWeakMap.js @@ -0,0 +1,28 @@ +var getTag = require('./_getTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var weakMapTag = '[object WeakMap]'; + +/** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ +function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; +} + +module.exports = isWeakMap; diff --git a/node_modules/lodash/isWeakSet.js b/node_modules/lodash/isWeakSet.js new file mode 100644 index 0000000..e628b26 --- /dev/null +++ b/node_modules/lodash/isWeakSet.js @@ -0,0 +1,28 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var weakSetTag = '[object WeakSet]'; + +/** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ +function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; +} + +module.exports = isWeakSet; diff --git a/node_modules/lodash/iteratee.js b/node_modules/lodash/iteratee.js new file mode 100644 index 0000000..61b73a8 --- /dev/null +++ b/node_modules/lodash/iteratee.js @@ -0,0 +1,53 @@ +var baseClone = require('./_baseClone'), + baseIteratee = require('./_baseIteratee'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1; + +/** + * Creates a function that invokes `func` with the arguments of the created + * function. If `func` is a property name, the created function returns the + * property value for a given element. If `func` is an array or object, the + * created function returns `true` for elements that contain the equivalent + * source properties, otherwise it returns `false`. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Util + * @param {*} [func=_.identity] The value to convert to a callback. + * @returns {Function} Returns the callback. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); + * // => [{ 'user': 'barney', 'age': 36, 'active': true }] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, _.iteratee(['user', 'fred'])); + * // => [{ 'user': 'fred', 'age': 40 }] + * + * // The `_.property` iteratee shorthand. + * _.map(users, _.iteratee('user')); + * // => ['barney', 'fred'] + * + * // Create custom iteratee shorthands. + * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { + * return !_.isRegExp(func) ? iteratee(func) : function(string) { + * return func.test(string); + * }; + * }); + * + * _.filter(['abc', 'def'], /ef/); + * // => ['def'] + */ +function iteratee(func) { + return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); +} + +module.exports = iteratee; diff --git a/node_modules/lodash/join.js b/node_modules/lodash/join.js new file mode 100644 index 0000000..45de079 --- /dev/null +++ b/node_modules/lodash/join.js @@ -0,0 +1,26 @@ +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeJoin = arrayProto.join; + +/** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ +function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); +} + +module.exports = join; diff --git a/node_modules/lodash/kebabCase.js b/node_modules/lodash/kebabCase.js new file mode 100644 index 0000000..8a52be6 --- /dev/null +++ b/node_modules/lodash/kebabCase.js @@ -0,0 +1,28 @@ +var createCompounder = require('./_createCompounder'); + +/** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ +var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); +}); + +module.exports = kebabCase; diff --git a/node_modules/lodash/keyBy.js b/node_modules/lodash/keyBy.js new file mode 100644 index 0000000..acc007a --- /dev/null +++ b/node_modules/lodash/keyBy.js @@ -0,0 +1,36 @@ +var baseAssignValue = require('./_baseAssignValue'), + createAggregator = require('./_createAggregator'); + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ +var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); +}); + +module.exports = keyBy; diff --git a/node_modules/lodash/keys.js b/node_modules/lodash/keys.js new file mode 100644 index 0000000..d143c71 --- /dev/null +++ b/node_modules/lodash/keys.js @@ -0,0 +1,37 @@ +var arrayLikeKeys = require('./_arrayLikeKeys'), + baseKeys = require('./_baseKeys'), + isArrayLike = require('./isArrayLike'); + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +module.exports = keys; diff --git a/node_modules/lodash/keysIn.js b/node_modules/lodash/keysIn.js new file mode 100644 index 0000000..a62308f --- /dev/null +++ b/node_modules/lodash/keysIn.js @@ -0,0 +1,32 @@ +var arrayLikeKeys = require('./_arrayLikeKeys'), + baseKeysIn = require('./_baseKeysIn'), + isArrayLike = require('./isArrayLike'); + +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ +function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); +} + +module.exports = keysIn; diff --git a/node_modules/lodash/lang.js b/node_modules/lodash/lang.js new file mode 100644 index 0000000..a396216 --- /dev/null +++ b/node_modules/lodash/lang.js @@ -0,0 +1,58 @@ +module.exports = { + 'castArray': require('./castArray'), + 'clone': require('./clone'), + 'cloneDeep': require('./cloneDeep'), + 'cloneDeepWith': require('./cloneDeepWith'), + 'cloneWith': require('./cloneWith'), + 'conformsTo': require('./conformsTo'), + 'eq': require('./eq'), + 'gt': require('./gt'), + 'gte': require('./gte'), + 'isArguments': require('./isArguments'), + 'isArray': require('./isArray'), + 'isArrayBuffer': require('./isArrayBuffer'), + 'isArrayLike': require('./isArrayLike'), + 'isArrayLikeObject': require('./isArrayLikeObject'), + 'isBoolean': require('./isBoolean'), + 'isBuffer': require('./isBuffer'), + 'isDate': require('./isDate'), + 'isElement': require('./isElement'), + 'isEmpty': require('./isEmpty'), + 'isEqual': require('./isEqual'), + 'isEqualWith': require('./isEqualWith'), + 'isError': require('./isError'), + 'isFinite': require('./isFinite'), + 'isFunction': require('./isFunction'), + 'isInteger': require('./isInteger'), + 'isLength': require('./isLength'), + 'isMap': require('./isMap'), + 'isMatch': require('./isMatch'), + 'isMatchWith': require('./isMatchWith'), + 'isNaN': require('./isNaN'), + 'isNative': require('./isNative'), + 'isNil': require('./isNil'), + 'isNull': require('./isNull'), + 'isNumber': require('./isNumber'), + 'isObject': require('./isObject'), + 'isObjectLike': require('./isObjectLike'), + 'isPlainObject': require('./isPlainObject'), + 'isRegExp': require('./isRegExp'), + 'isSafeInteger': require('./isSafeInteger'), + 'isSet': require('./isSet'), + 'isString': require('./isString'), + 'isSymbol': require('./isSymbol'), + 'isTypedArray': require('./isTypedArray'), + 'isUndefined': require('./isUndefined'), + 'isWeakMap': require('./isWeakMap'), + 'isWeakSet': require('./isWeakSet'), + 'lt': require('./lt'), + 'lte': require('./lte'), + 'toArray': require('./toArray'), + 'toFinite': require('./toFinite'), + 'toInteger': require('./toInteger'), + 'toLength': require('./toLength'), + 'toNumber': require('./toNumber'), + 'toPlainObject': require('./toPlainObject'), + 'toSafeInteger': require('./toSafeInteger'), + 'toString': require('./toString') +}; diff --git a/node_modules/lodash/last.js b/node_modules/lodash/last.js new file mode 100644 index 0000000..cad1eaf --- /dev/null +++ b/node_modules/lodash/last.js @@ -0,0 +1,20 @@ +/** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ +function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; +} + +module.exports = last; diff --git a/node_modules/lodash/lastIndexOf.js b/node_modules/lodash/lastIndexOf.js new file mode 100644 index 0000000..dabfb61 --- /dev/null +++ b/node_modules/lodash/lastIndexOf.js @@ -0,0 +1,46 @@ +var baseFindIndex = require('./_baseFindIndex'), + baseIsNaN = require('./_baseIsNaN'), + strictLastIndexOf = require('./_strictLastIndexOf'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ +function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); +} + +module.exports = lastIndexOf; diff --git a/node_modules/lodash/lodash.js b/node_modules/lodash/lodash.js new file mode 100644 index 0000000..8634cab --- /dev/null +++ b/node_modules/lodash/lodash.js @@ -0,0 +1,17259 @@ +/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.18.1'; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function', + INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`', + INVALID_TEMPL_IMPORTS_ERROR_TEXT = 'Invalid `imports` option passed into `_.template`'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; + + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] + ]; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + + /** Used to match leading whitespace. */ + var reTrimStart = /^\s+/; + + /** Used to match a single whitespace character. */ + var reWhitespace = /\s/; + + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + + /** + * Used to validate the `validate` option in `_.template` variable. + * + * Forbids characters which could potentially change the meaning of the function argument definition: + * - "()," (modification of function parameters) + * - "=" (default value) + * - "[]{}" (destructuring of function parameters) + * - "/" (beginning of a comment) + * - whitespace + */ + var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + + /** Used to compose unicode regexes. */ + var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); + + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join('|'), 'g'); + + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; + + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /*--------------------------------------------------------------------------*/ + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; + } + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } + + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); + + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } + + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } + + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } + + /** + * The base implementation of `_.trim`. + * + * @private + * @param {string} string The string to trim. + * @returns {string} Returns the trimmed string. + */ + function baseTrim(string) { + return string + ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') + : string; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the last non-whitespace character. + */ + function trimmedEndIndex(string) { + var index = string.length; + + while (index-- && reWhitespace.test(string.charAt(index))) {} + return index; + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; + } + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. + * + * **Security:** See + * [threat model](https://github.com/lodash/lodash/blob/main/threat-model.md) + * — `_.template` is insecure and will be removed in v5. + * + * @static + * @memberOf _ + * @type {Object} + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash + } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; + } + + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `_.sample` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; + } + + /** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); + } + + /** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + + /** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. + */ + function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; + } + + /** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } + + /** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; + } + + /** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + + /** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEachRight = createBaseEach(baseForOwnRight, true); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + + /** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; + } + + /** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; + } + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; + } + + /** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; + } + + /** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseOrderBy(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = arrayMap(iteratees, function(iteratee) { + if (isArray(iteratee)) { + return function(value) { + return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); + }; + } + return iteratee; + }); + } else { + iteratees = [identity]; + } + + var index = -1; + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; + } + + /** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + + /** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; + } + + /** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ + function baseSample(collection) { + return arraySample(values(collection)); + } + + /** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + return object; + } + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.shuffle`. + * + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); + } + + /** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndexBy(array, value, iteratee, retHighest) { + var low = 0, + high = array == null ? 0 : array.length; + if (high === 0) { + return 0; + } + + value = iteratee(value); + var valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } + + /** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ + function baseUnset(object, path) { + path = castPath(path, object); + + // Prevent prototype pollution: + // https://github.com/lodash/lodash/security/advisories/GHSA-xxjr-mmjv-4gpg + // https://github.com/lodash/lodash/security/advisories/GHSA-f23m-r3pf-42rh + var index = -1, + length = path.length; + + if (!length) { + return true; + } + + while (++index < length) { + var key = toKey(path[index]); + + // Always block "__proto__" anywhere in the path if it's not expected + if (key === '__proto__' && !hasOwnProperty.call(object, '__proto__')) { + return false; + } + + // Block constructor/prototype as non-terminal traversal keys to prevent + // escaping the object graph into built-in constructors and prototypes. + if ((key === 'constructor' || key === 'prototype') && index < length - 1) { + return false; + } + } + + var obj = parent(object, path); + return obj == null || delete obj[toKey(last(path))]; + } + + /** + * The base implementation of `_.update`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + + /** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. + */ + function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); + + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } + } + return baseUniq(baseFlatten(result, 1), iteratee, comparator); + } + + /** + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. + */ + function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; + + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; + } + + /** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } + + /** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ + function castFunction(value) { + return typeof value == 'function' ? value : identity; + } + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + var castRest = baseRest; + + /** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); + } + + /** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + /** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + + /** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + + /** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); + } + + /** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + + /** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; + } + + /** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } + + /** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; + } + + /** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; + } + + /** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } + + /** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + + /** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } + + /** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } + + /** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision && nativeIsFinite(number)) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; + } + + /** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; + + /** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } + + /** + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } + + /** + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; + } + + /** + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. + * + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } + + /** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; + } + + /** + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. + * + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. + */ + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return new Ctor; + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return new Ctor; + + case symbolTag: + return cloneSymbol(object); + } + } + + /** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ + var isMaskable = coreJsData ? isFunction : stubFalse; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = shortOut(baseSetData); + + /** + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */ + function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; + } + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `-0`, `0n`, `""`, `undefined`, and `NaN` are falsy. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + baseAssignValue(result, pair[0], pair[1]); + } + return result; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } + + /** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); + } + + /** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */ + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + } + + /** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */ + var pull = baseRest(pullAll); + + /** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; + } + + /** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */ + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */ + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + + /** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */ + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } + + /** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + + /** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */ + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } + + /** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */ + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } + + /** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */ + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */ + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; + } + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */ + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + + /** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } + + /** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example + * + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */ + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + + /** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); + + /** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */ + var zip = baseRest(unzip); + + /** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. + * + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */ + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); + } + + /** + * This method is like `_.zipObject` except that it supports property paths. + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */ + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); + } + + /** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */ + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * This method is the wrapper version of `_.at`. + * + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */ + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */ + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; + } + + /** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] + */ + function wrapperToIterator() { + return this; + } + + /** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + * + * // Combining several predicates using `_.overEvery` or `_.overSome`. + * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); + * // => objects for ['fred', 'barney'] + */ + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(findLastIndex); + + /** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); + } + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } + }); + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + } + + /** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + } + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + } + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */ + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + + /** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */ + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } + + /** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */ + function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 30 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + */ + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ + var now = ctxNow || function() { + return root.Date.now(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ + function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + + /** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + + /** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ + function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + timeWaiting = wait - timeSinceLastCall; + + return maxing + ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + clearTimeout(timerId); + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ + function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /** + * Creates a function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */ + var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(getIteratee())) + : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + + /** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); + }); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */ + var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); + } + + /** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start == null ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + + /** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); + } + + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */ + function unary(func) { + return ary(func, 1); + } + + /** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + return partial(castFunction(wrapper), value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ + function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; + } + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ + function cloneWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ + function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ + function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ + var gt = createRelationalOperation(baseGt); + + /** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ + var gte = createRelationalOperation(function(value, other) { + return value >= other; + }); + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + + /** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + } + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ + function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + + /** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + + /** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + function isNil(value) { + return value == null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + + /** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + + /** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ + function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; + } + + /** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ + var lt = createRelationalOperation(baseLt); + + /** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (symIterator && value[symIterator]) { + return iteratorToArray(value[symIterator]()); + } + var tag = getTag(value), + func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + + return func(value); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */ + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = baseTrim(value); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */ + function toSafeInteger(value) { + return value + ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + + /** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + + /** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); + + /** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ + var at = flatRest(baseAt); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : baseAssign(result, properties); + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; + }); + + /** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ + var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); + }); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + + /** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ + function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ + function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } + + /** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + + /** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ + var invert = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + result[value] = key; + }, constant(identity)); + + /** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ + var invertBy = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + }, getIteratee); + + /** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ + var invoke = baseRest(baseInvoke); + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. + * + * **Note:** This method is considerably slower than `_.pick`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ + var omit = flatRest(function(object, paths) { + var result = {}; + if (object == null) { + return result; + } + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result); + if (isDeep) { + result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result, paths[length]); + } + return result; + }); + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = getIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + path = castPath(path, object); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + length = 1; + object = undefined; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + + /** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + + /** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ + function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); + } + + /** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ + var toPairs = createToPairs(keys); + + /** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */ + var toPairsIn = createToPairs(keysIn); + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function transform(object, iteratee, accumulator) { + var isArr = isArray(object), + isArrLike = isArr || isBuffer(object) || isTypedArray(object); + + iteratee = getIteratee(iteratee, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor : []; + } + else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */ + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + + /** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 + * + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */ + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + + /** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */ + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object == null ? [] : baseValues(object, keys(object)); + } + + /** + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ + function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + + /** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + + /** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * **Note:** If `lower` is greater than `upper`, the values are swapped. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * // when lower is greater than upper the values are swapped + * _.random(5, 0); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(-5); + * // => an integer between -5 and 0 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; + } + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + + /** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; + } + + /** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); + }); + + /** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ + var lowerFirst = createCaseFirst('toLowerCase'); + + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor(mid), chars) + + string + + createPadding(nativeCeil(mid), chars) + ); + } + + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; + } + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + + /** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ + function replace() { + var args = arguments, + string = toString(args[0]); + + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + + /** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ + function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + + /** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = toString(string); + position = position == null + ? 0 + : baseClamp(toInteger(position), 0, string.length); + + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Security:** `_.template` is insecure and should not be used. It will be + * removed in Lodash v5. Avoid untrusted input. See + * [threat model](https://github.com/lodash/lodash/blob/main/threat-model.md). + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': ' +``` + +## Usage + +### Basic named error + +```javascript +var CustomError = makeError("CustomError"); + +// Parameters are forwarded to the super class (here Error). +throw new CustomError("a message"); +``` + +### Advanced error class + +```javascript +function CustomError(customValue) { + CustomError.super.call(this, "custom error message"); + + this.customValue = customValue; +} +makeError(CustomError); + +// Feel free to extend the prototype. +CustomError.prototype.myMethod = function CustomError$myMethod() { + console.log("CustomError.myMethod (%s, %s)", this.code, this.message); +}; + +//----- + +try { + throw new CustomError(42); +} catch (error) { + error.myMethod(); +} +``` + +### Specialized error + +```javascript +var SpecializedError = makeError("SpecializedError", CustomError); + +throw new SpecializedError(42); +``` + +### Inheritance + +> Best for ES2015+. + +```javascript +import { BaseError } from "make-error"; + +class CustomError extends BaseError { + constructor() { + super("custom error message"); + } +} +``` + +## Related + +- [make-error-cause](https://www.npmjs.com/package/make-error-cause): Make your own error types, with a cause! + +## Contributions + +Contributions are _very_ welcomed, either on the documentation or on +the code. + +You may: + +- report any [issue](https://github.com/JsCommunity/make-error/issues) + you've encountered; +- fork and create a pull request. + +## License + +ISC © [Julien Fontanet](http://julien.isonoe.net) diff --git a/node_modules/make-error/dist/make-error.js b/node_modules/make-error/dist/make-error.js new file mode 100644 index 0000000..32444c6 --- /dev/null +++ b/node_modules/make-error/dist/make-error.js @@ -0,0 +1 @@ +!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).makeError=f()}}(function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i; + +/** + * Set the constructor prototype to `BaseError`. + */ +declare function makeError(super_: { + new (...args: any[]): T; +}): makeError.Constructor; + +/** + * Create a specialized error instance. + */ +declare function makeError( + name: string | Function, + super_: K +): K & makeError.SpecializedConstructor; + +declare namespace makeError { + /** + * Use with ES2015+ inheritance. + */ + export class BaseError extends Error { + message: string; + name: string; + stack: string; + + constructor(message?: string); + } + + export interface Constructor { + new (message?: string): T; + super_: any; + prototype: T; + } + + export interface SpecializedConstructor { + super_: any; + prototype: T; + } +} + +export = makeError; diff --git a/node_modules/make-error/index.js b/node_modules/make-error/index.js new file mode 100644 index 0000000..fab6040 --- /dev/null +++ b/node_modules/make-error/index.js @@ -0,0 +1,151 @@ +// ISC @ Julien Fontanet + +"use strict"; + +// =================================================================== + +var construct = typeof Reflect !== "undefined" ? Reflect.construct : undefined; +var defineProperty = Object.defineProperty; + +// ------------------------------------------------------------------- + +var captureStackTrace = Error.captureStackTrace; +if (captureStackTrace === undefined) { + captureStackTrace = function captureStackTrace(error) { + var container = new Error(); + + defineProperty(error, "stack", { + configurable: true, + get: function getStack() { + var stack = container.stack; + + // Replace property with value for faster future accesses. + defineProperty(this, "stack", { + configurable: true, + value: stack, + writable: true, + }); + + return stack; + }, + set: function setStack(stack) { + defineProperty(error, "stack", { + configurable: true, + value: stack, + writable: true, + }); + }, + }); + }; +} + +// ------------------------------------------------------------------- + +function BaseError(message) { + if (message !== undefined) { + defineProperty(this, "message", { + configurable: true, + value: message, + writable: true, + }); + } + + var cname = this.constructor.name; + if (cname !== undefined && cname !== this.name) { + defineProperty(this, "name", { + configurable: true, + value: cname, + writable: true, + }); + } + + captureStackTrace(this, this.constructor); +} + +BaseError.prototype = Object.create(Error.prototype, { + // See: https://github.com/JsCommunity/make-error/issues/4 + constructor: { + configurable: true, + value: BaseError, + writable: true, + }, +}); + +// ------------------------------------------------------------------- + +// Sets the name of a function if possible (depends of the JS engine). +var setFunctionName = (function() { + function setFunctionName(fn, name) { + return defineProperty(fn, "name", { + configurable: true, + value: name, + }); + } + try { + var f = function() {}; + setFunctionName(f, "foo"); + if (f.name === "foo") { + return setFunctionName; + } + } catch (_) {} +})(); + +// ------------------------------------------------------------------- + +function makeError(constructor, super_) { + if (super_ == null || super_ === Error) { + super_ = BaseError; + } else if (typeof super_ !== "function") { + throw new TypeError("super_ should be a function"); + } + + var name; + if (typeof constructor === "string") { + name = constructor; + constructor = + construct !== undefined + ? function() { + return construct(super_, arguments, this.constructor); + } + : function() { + super_.apply(this, arguments); + }; + + // If the name can be set, do it once and for all. + if (setFunctionName !== undefined) { + setFunctionName(constructor, name); + name = undefined; + } + } else if (typeof constructor !== "function") { + throw new TypeError("constructor should be either a string or a function"); + } + + // Also register the super constructor also as `constructor.super_` just + // like Node's `util.inherits()`. + // + // eslint-disable-next-line dot-notation + constructor.super_ = constructor["super"] = super_; + + var properties = { + constructor: { + configurable: true, + value: constructor, + writable: true, + }, + }; + + // If the name could not be set on the constructor, set it on the + // prototype. + if (name !== undefined) { + properties.name = { + configurable: true, + value: name, + writable: true, + }; + } + constructor.prototype = Object.create(super_.prototype, properties); + + return constructor; +} +exports = module.exports = makeError; +exports.BaseError = BaseError; diff --git a/node_modules/make-error/package.json b/node_modules/make-error/package.json new file mode 100644 index 0000000..2af27e1 --- /dev/null +++ b/node_modules/make-error/package.json @@ -0,0 +1,62 @@ +{ + "name": "make-error", + "version": "1.3.6", + "main": "index.js", + "license": "ISC", + "description": "Make your own error types!", + "keywords": [ + "create", + "custom", + "derive", + "error", + "errors", + "extend", + "extending", + "extension", + "factory", + "inherit", + "make", + "subclass" + ], + "homepage": "https://github.com/JsCommunity/make-error", + "bugs": "https://github.com/JsCommunity/make-error/issues", + "author": "Julien Fontanet ", + "repository": { + "type": "git", + "url": "git://github.com/JsCommunity/make-error.git" + }, + "devDependencies": { + "browserify": "^16.2.3", + "eslint": "^6.5.1", + "eslint-config-prettier": "^6.4.0", + "eslint-config-standard": "^14.1.0", + "eslint-plugin-import": "^2.14.0", + "eslint-plugin-node": "^10.0.0", + "eslint-plugin-promise": "^4.0.1", + "eslint-plugin-standard": "^4.0.0", + "husky": "^3.0.9", + "jest": "^24", + "prettier": "^1.14.3", + "uglify-js": "^3.3.2" + }, + "jest": { + "testEnvironment": "node" + }, + "scripts": { + "dev-test": "jest --watch", + "format": "prettier --write '**'", + "prepublishOnly": "mkdir -p dist && browserify -s makeError index.js | uglifyjs -c > dist/make-error.js", + "pretest": "eslint --ignore-path .gitignore .", + "test": "jest" + }, + "files": [ + "dist/", + "index.js", + "index.d.ts" + ], + "husky": { + "hooks": { + "commit-msg": "npm run test" + } + } +} diff --git a/node_modules/mime-db/HISTORY.md b/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..7436f64 --- /dev/null +++ b/node_modules/mime-db/HISTORY.md @@ -0,0 +1,507 @@ +1.52.0 / 2022-02-21 +=================== + + * Add extensions from IANA for more `image/*` types + * Add extension `.asc` to `application/pgp-keys` + * Add extensions to various XML types + * Add new upstream MIME types + +1.51.0 / 2021-11-08 +=================== + + * Add new upstream MIME types + * Mark `image/vnd.microsoft.icon` as compressible + * Mark `image/vnd.ms-dds` as compressible + +1.50.0 / 2021-09-15 +=================== + + * Add deprecated iWorks mime types and extensions + * Add new upstream MIME types + +1.49.0 / 2021-07-26 +=================== + + * Add extension `.trig` to `application/trig` + * Add new upstream MIME types + +1.48.0 / 2021-05-30 +=================== + + * Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + * Add new upstream MIME types + * Mark `text/yaml` as compressible + +1.47.0 / 2021-04-01 +=================== + + * Add new upstream MIME types + * Remove ambigious extensions from IANA for `application/*+xml` types + * Update primary extension to `.es` for `application/ecmascript` + +1.46.0 / 2021-02-13 +=================== + + * Add extension `.amr` to `audio/amr` + * Add extension `.m4s` to `video/iso.segment` + * Add extension `.opus` to `audio/ogg` + * Add new upstream MIME types + +1.45.0 / 2020-09-22 +=================== + + * Add `application/ubjson` with extension `.ubj` + * Add `image/avif` with extension `.avif` + * Add `image/ktx2` with extension `.ktx2` + * Add extension `.dbf` to `application/vnd.dbf` + * Add extension `.rar` to `application/vnd.rar` + * Add extension `.td` to `application/urc-targetdesc+xml` + * Add new upstream MIME types + * Fix extension of `application/vnd.apple.keynote` to be `.key` + +1.44.0 / 2020-04-22 +=================== + + * Add charsets from IANA + * Add extension `.cjs` to `application/node` + * Add new upstream MIME types + +1.43.0 / 2020-01-05 +=================== + + * Add `application/x-keepass2` with extension `.kdbx` + * Add extension `.mxmf` to `audio/mobile-xmf` + * Add extensions from IANA for `application/*+xml` types + * Add new upstream MIME types + +1.42.0 / 2019-09-25 +=================== + + * Add `image/vnd.ms-dds` with extension `.dds` + * Add new upstream MIME types + * Remove compressible from `multipart/mixed` + +1.41.0 / 2019-08-30 +=================== + + * Add new upstream MIME types + * Add `application/toml` with extension `.toml` + * Mark `font/ttf` as compressible + +1.40.0 / 2019-04-20 +=================== + + * Add extensions from IANA for `model/*` types + * Add `text/mdx` with extension `.mdx` + +1.39.0 / 2019-04-04 +=================== + + * Add extensions `.siv` and `.sieve` to `application/sieve` + * Add new upstream MIME types + +1.38.0 / 2019-02-04 +=================== + + * Add extension `.nq` to `application/n-quads` + * Add extension `.nt` to `application/n-triples` + * Add new upstream MIME types + * Mark `text/less` as compressible + +1.37.0 / 2018-10-19 +=================== + + * Add extensions to HEIC image types + * Add new upstream MIME types + +1.36.0 / 2018-08-20 +=================== + + * Add Apple file extensions from IANA + * Add extensions from IANA for `image/*` types + * Add new upstream MIME types + +1.35.0 / 2018-07-15 +=================== + + * Add extension `.owl` to `application/rdf+xml` + * Add new upstream MIME types + - Removes extension `.woff` from `application/font-woff` + +1.34.0 / 2018-06-03 +=================== + + * Add extension `.csl` to `application/vnd.citationstyles.style+xml` + * Add extension `.es` to `application/ecmascript` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/turtle` + * Mark all XML-derived types as compressible + +1.33.0 / 2018-02-15 +=================== + + * Add extensions from IANA for `message/*` types + * Add new upstream MIME types + * Fix some incorrect OOXML types + * Remove `application/font-woff2` + +1.32.0 / 2017-11-29 +=================== + + * Add new upstream MIME types + * Update `text/hjson` to registered `application/hjson` + * Add `text/shex` with extension `.shex` + +1.31.0 / 2017-10-25 +=================== + + * Add `application/raml+yaml` with extension `.raml` + * Add `application/wasm` with extension `.wasm` + * Add new `font` type from IANA + * Add new upstream font extensions + * Add new upstream MIME types + * Add extensions for JPEG-2000 images + +1.30.0 / 2017-08-27 +=================== + + * Add `application/vnd.ms-outlook` + * Add `application/x-arj` + * Add extension `.mjs` to `application/javascript` + * Add glTF types and extensions + * Add new upstream MIME types + * Add `text/x-org` + * Add VirtualBox MIME types + * Fix `source` records for `video/*` types that are IANA + * Update `font/opentype` to registered `font/otf` + +1.29.0 / 2017-07-10 +=================== + + * Add `application/fido.trusted-apps+json` + * Add extension `.wadl` to `application/vnd.sun.wadl+xml` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/css` + +1.28.0 / 2017-05-14 +=================== + + * Add new upstream MIME types + * Add extension `.gz` to `application/gzip` + * Update extensions `.md` and `.markdown` to be `text/markdown` + +1.27.0 / 2017-03-16 +=================== + + * Add new upstream MIME types + * Add `image/apng` with extension `.apng` + +1.26.0 / 2017-01-14 +=================== + + * Add new upstream MIME types + * Add extension `.geojson` to `application/geo+json` + +1.25.0 / 2016-11-11 +=================== + + * Add new upstream MIME types + +1.24.0 / 2016-09-18 +=================== + + * Add `audio/mp3` + * Add new upstream MIME types + +1.23.0 / 2016-05-01 +=================== + + * Add new upstream MIME types + * Add extension `.3gpp` to `audio/3gpp` + +1.22.0 / 2016-02-15 +=================== + + * Add `text/slim` + * Add extension `.rng` to `application/xml` + * Add new upstream MIME types + * Fix extension of `application/dash+xml` to be `.mpd` + * Update primary extension to `.m4a` for `audio/mp4` + +1.21.0 / 2016-01-06 +=================== + + * Add Google document types + * Add new upstream MIME types + +1.20.0 / 2015-11-10 +=================== + + * Add `text/x-suse-ymp` + * Add new upstream MIME types + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.apple.pkpass` + * Add new upstream MIME types + +1.18.0 / 2015-09-03 +=================== + + * Add new upstream MIME types + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + +1.8.0 / 2015-03-13 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/node_modules/mime-db/LICENSE b/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..0751cb1 --- /dev/null +++ b/node_modules/mime-db/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015-2022 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mime-db/README.md b/node_modules/mime-db/README.md new file mode 100644 index 0000000..5a8fcfe --- /dev/null +++ b/node_modules/mime-db/README.md @@ -0,0 +1,100 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a large database of mime types and information about them. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +It aggregates data from the following sources: + +- http://www.iana.org/assignments/media-types/media-types.xhtml +- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types + +## Installation + +```bash +npm install mime-db +``` + +### Database Download + +If you're crazy enough to use this in the browser, you can just grab the +JSON file using [jsDelivr](https://www.jsdelivr.com/). It is recommended to +replace `master` with [a release tag](https://github.com/jshttp/mime-db/tags) +as the JSON format may change in the future. + +``` +https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json +``` + +## Usage + +```js +var db = require('mime-db') + +// grab data on .js files +var data = db['application/javascript'] +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + If not set, it's probably a custom media type. + - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) +- `.extensions[]` - known extensions associated with this mime type. +- `.compressible` - whether a file of this type can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom-types.json` or +`src/custom-suffix.json`. + +The `src/custom-types.json` file is a JSON object with the MIME type as the +keys and the values being an object with the following keys: + +- `compressible` - leave out if you don't know, otherwise `true`/`false` to + indicate whether the data represented by the type is typically compressible. +- `extensions` - include an array of file extensions that are associated with + the type. +- `notes` - human-readable notes about the type, typically what the type is. +- `sources` - include an array of URLs of where the MIME type and the associated + extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); + links to type aggregating sites and Wikipedia are _not acceptable_. + +To update the build, run `npm run build`. + +### Adding Custom Media Types + +The best way to get new media types included in this library is to register +them with the IANA. The community registration procedure is outlined in +[RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types +registered with the IANA are automatically pulled into this library. + +If that is not possible / feasible, they can be added directly here as a +"custom" type. To do this, it is required to have a primary source that +definitively lists the media type. If an extension is going to be listed as +associateed with this media type, the source must definitively link the +media type and extension as well. + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci +[ci-url]: https://github.com/jshttp/mime-db/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master +[node-image]: https://badgen.net/npm/node/mime-db +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-db +[npm-url]: https://npmjs.org/package/mime-db +[npm-version-image]: https://badgen.net/npm/v/mime-db diff --git a/node_modules/mime-db/db.json b/node_modules/mime-db/db.json new file mode 100644 index 0000000..eb9c42c --- /dev/null +++ b/node_modules/mime-db/db.json @@ -0,0 +1,8519 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/3gpp-ims+xml": { + "source": "iana", + "compressible": true + }, + "application/3gpphal+json": { + "source": "iana", + "compressible": true + }, + "application/3gpphalforms+json": { + "source": "iana", + "compressible": true + }, + "application/a2l": { + "source": "iana" + }, + "application/ace+cbor": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/activity+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamcontrol+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamparams+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/at+jwt": { + "source": "iana" + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomdeleted"] + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomsvc"] + }, + "application/atsc-dwd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dwd"] + }, + "application/atsc-dynamic-event-message": { + "source": "iana" + }, + "application/atsc-held+xml": { + "source": "iana", + "compressible": true, + "extensions": ["held"] + }, + "application/atsc-rdt+json": { + "source": "iana", + "compressible": true + }, + "application/atsc-rsat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsat"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana", + "compressible": true + }, + "application/bacnet-xdd+zip": { + "source": "iana", + "compressible": false + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xcs"] + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/captive+json": { + "source": "iana", + "compressible": true + }, + "application/cbor": { + "source": "iana" + }, + "application/cbor-seq": { + "source": "iana" + }, + "application/cccex": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana", + "compressible": true + }, + "application/ccxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdfx"] + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana", + "compressible": true + }, + "application/cellml+xml": { + "source": "iana", + "compressible": true + }, + "application/cfw": { + "source": "iana" + }, + "application/city+json": { + "source": "iana", + "compressible": true + }, + "application/clr": { + "source": "iana" + }, + "application/clue+xml": { + "source": "iana", + "compressible": true + }, + "application/clue_info+xml": { + "source": "iana", + "compressible": true + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana", + "compressible": true + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/coap-payload": { + "source": "iana" + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/cose": { + "source": "iana" + }, + "application/cose-key": { + "source": "iana" + }, + "application/cose-key-set": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cpl"] + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana", + "compressible": true + }, + "application/cstadata+xml": { + "source": "iana", + "compressible": true + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cwt": { + "source": "iana" + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpd"] + }, + "application/dash-patch+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "compressible": true, + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana", + "compressible": true + }, + "application/dicom": { + "source": "iana" + }, + "application/dicom+json": { + "source": "iana", + "compressible": true + }, + "application/dicom+xml": { + "source": "iana", + "compressible": true + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/dns+json": { + "source": "iana", + "compressible": true + }, + "application/dns-message": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dbk"] + }, + "application/dots+cbor": { + "source": "iana" + }, + "application/dskpp+xml": { + "source": "iana", + "compressible": true + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["es","ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/efi": { + "source": "iana" + }, + "application/elm+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/elm+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.cap+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/emergencycalldata.comment+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.control+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.ecall.msd": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.veds+xml": { + "source": "iana", + "compressible": true + }, + "application/emma+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emotionml"] + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana", + "compressible": true + }, + "application/epub+zip": { + "source": "iana", + "compressible": false, + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/expect-ct-report+json": { + "source": "iana", + "compressible": true + }, + "application/express": { + "source": "iana", + "extensions": ["exp"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fdt"] + }, + "application/fhir+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fhir+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fido.trusted-apps+json": { + "compressible": true + }, + "application/fits": { + "source": "iana" + }, + "application/flexfec": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false + }, + "application/framework-attributes+xml": { + "source": "iana", + "compressible": true + }, + "application/geo+json": { + "source": "iana", + "compressible": true, + "extensions": ["geojson"] + }, + "application/geo+json-seq": { + "source": "iana" + }, + "application/geopackage+sqlite3": { + "source": "iana" + }, + "application/geoxacml+xml": { + "source": "iana", + "compressible": true + }, + "application/gltf-buffer": { + "source": "iana" + }, + "application/gml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false, + "extensions": ["gz"] + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana", + "compressible": true + }, + "application/hjson": { + "extensions": ["hjson"] + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pkg-reply+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana", + "compressible": true, + "extensions": ["its"] + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js","mjs"] + }, + "application/jf2feed+json": { + "source": "iana", + "compressible": true + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/jscalendar+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana", + "compressible": true + }, + "application/kpml-response+xml": { + "source": "iana", + "compressible": true + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/lgr+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lgr"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana", + "compressible": true + }, + "application/lost+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana", + "compressible": true + }, + "application/lpf+zip": { + "source": "iana", + "compressible": false + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mads"] + }, + "application/manifest+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana", + "compressible": true + }, + "application/mathml-presentation+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-deregister+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-envelope+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-protection-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-reception-report+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-user-service-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpf"] + }, + "application/media_control+xml": { + "source": "iana", + "compressible": true + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "compressible": true, + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "compressible": true, + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mipc": { + "source": "iana" + }, + "application/missing-blocks+cbor-seq": { + "source": "iana" + }, + "application/mmt-aei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["maei"] + }, + "application/mmt-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musd"] + }, + "application/mods+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana", + "compressible": true + }, + "application/mrb-publish+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-ivr+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msc-mixer+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mud+json": { + "source": "iana", + "compressible": true + }, + "application/multipart-core": { + "source": "iana" + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/n-quads": { + "source": "iana", + "extensions": ["nq"] + }, + "application/n-triples": { + "source": "iana", + "extensions": ["nt"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-groupinfo": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana", + "compressible": true + }, + "application/node": { + "source": "iana", + "extensions": ["cjs"] + }, + "application/nss": { + "source": "iana" + }, + "application/oauth-authz-req+jwt": { + "source": "iana" + }, + "application/oblivious-dns-message": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] + }, + "application/oda": { + "source": "iana", + "extensions": ["oda"] + }, + "application/odm+xml": { + "source": "iana", + "compressible": true + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/opc-nodeset+xml": { + "source": "iana", + "compressible": true + }, + "application/oscore": { + "source": "iana" + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p21": { + "source": "iana" + }, + "application/p21+zip": { + "source": "iana", + "compressible": false + }, + "application/p2p-overlay+xml": { + "source": "iana", + "compressible": true, + "extensions": ["relo"] + }, + "application/parityfec": { + "source": "iana" + }, + "application/passport": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pem-certificate-chain": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana", + "extensions": ["asc"] + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pidf-diff+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkcs8-encrypted": { + "source": "iana" + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/ppsp-tracker+json": { + "source": "iana", + "compressible": true + }, + "application/problem+json": { + "source": "iana", + "compressible": true + }, + "application/problem+xml": { + "source": "iana", + "compressible": true + }, + "application/provenance+xml": { + "source": "iana", + "compressible": true, + "extensions": ["provx"] + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.cyn": { + "source": "iana", + "charset": "7-BIT" + }, + "application/prs.hpub+zip": { + "source": "iana", + "compressible": false + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana", + "compressible": true + }, + "application/pskc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pskcxml"] + }, + "application/pvd+json": { + "source": "iana", + "compressible": true + }, + "application/qsig": { + "source": "iana" + }, + "application/raml+yaml": { + "compressible": true, + "extensions": ["raml"] + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf","owl"] + }, + "application/reginfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana", + "compressible": true + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana", + "compressible": true + }, + "application/rls-services+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rs"] + }, + "application/route-apd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rapd"] + }, + "application/route-s-tsid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sls"] + }, + "application/route-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rusd"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-publication": { + "source": "iana" + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana", + "compressible": true + }, + "application/samlmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/sarif+json": { + "source": "iana", + "compressible": true + }, + "application/sarif-external-properties+json": { + "source": "iana", + "compressible": true + }, + "application/sbe": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana", + "compressible": true + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/secevent+jwt": { + "source": "iana" + }, + "application/senml+cbor": { + "source": "iana" + }, + "application/senml+json": { + "source": "iana", + "compressible": true + }, + "application/senml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["senmlx"] + }, + "application/senml-etch+cbor": { + "source": "iana" + }, + "application/senml-etch+json": { + "source": "iana", + "compressible": true + }, + "application/senml-exi": { + "source": "iana" + }, + "application/sensml+cbor": { + "source": "iana" + }, + "application/sensml+json": { + "source": "iana", + "compressible": true + }, + "application/sensml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sensmlx"] + }, + "application/sensml-exi": { + "source": "iana" + }, + "application/sep+xml": { + "source": "iana", + "compressible": true + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana", + "extensions": ["siv","sieve"] + }, + "application/simple-filter+xml": { + "source": "iana", + "compressible": true + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/sipc": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "compressible": true, + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "compressible": true, + "extensions": ["srx"] + }, + "application/spdx+json": { + "source": "iana", + "compressible": true + }, + "application/spirits-event+xml": { + "source": "iana", + "compressible": true + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ssml"] + }, + "application/stix+json": { + "source": "iana", + "compressible": true + }, + "application/swid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["swidtag"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/taxii+json": { + "source": "iana", + "compressible": true + }, + "application/td+json": { + "source": "iana", + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tei","teicorpus"] + }, + "application/tetra_isi": { + "source": "iana" + }, + "application/thraud+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/tlsrpt+gzip": { + "source": "iana" + }, + "application/tlsrpt+json": { + "source": "iana", + "compressible": true + }, + "application/tnauthlist": { + "source": "iana" + }, + "application/token-introspection+jwt": { + "source": "iana" + }, + "application/toml": { + "compressible": true, + "extensions": ["toml"] + }, + "application/trickle-ice-sdpfrag": { + "source": "iana" + }, + "application/trig": { + "source": "iana", + "extensions": ["trig"] + }, + "application/ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ttml"] + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/tzif": { + "source": "iana" + }, + "application/tzif-leap": { + "source": "iana" + }, + "application/ubjson": { + "compressible": false, + "extensions": ["ubj"] + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-ressheet+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsheet"] + }, + "application/urc-targetdesc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["td"] + }, + "application/urc-uisocketdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana", + "compressible": true + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + "source": "iana", + "compressible": true, + "extensions": ["1km"] + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-v2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gnas": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gmop+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gtpc": { + "source": "iana" + }, + "application/vnd.3gpp.interworking-data": { + "source": "iana" + }, + "application/vnd.3gpp.lpp": { + "source": "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-payload": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-signalling": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ngap": { + "source": "iana" + }, + "application/vnd.3gpp.pfcp": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.s1ap": { + "source": "iana" + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.sms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + "source": "iana" + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "compressible": false, + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + "source": "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + "source": "iana" + }, + "application/vnd.afpc.foca-charset": { + "source": "iana" + }, + "application/vnd.afpc.foca-codedfont": { + "source": "iana" + }, + "application/vnd.afpc.foca-codepage": { + "source": "iana" + }, + "application/vnd.afpc.modca": { + "source": "iana" + }, + "application/vnd.afpc.modca-cmtable": { + "source": "iana" + }, + "application/vnd.afpc.modca-formdef": { + "source": "iana" + }, + "application/vnd.afpc.modca-mediummap": { + "source": "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + "source": "iana" + }, + "application/vnd.afpc.modca-overlay": { + "source": "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + "source": "iana" + }, + "application/vnd.age": { + "source": "iana", + "extensions": ["age"] + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amadeus+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + "source": "iana" + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.android.ota": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.arrow.file": { + "source": "iana" + }, + "application/vnd.apache.arrow.stream": { + "source": "iana" + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.aplextor.warrp+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apothekende.reservation+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpkg"] + }, + "application/vnd.apple.keynote": { + "source": "iana", + "extensions": ["key"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.numbers": { + "source": "iana", + "extensions": ["numbers"] + }, + "application/vnd.apple.pages": { + "source": "iana", + "extensions": ["pages"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artisan+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avalon+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.avistar+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.banana-accounting": { + "source": "iana" + }, + "application/vnd.bbf.usp.error": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bint.med-content": { + "source": "iana" + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.blink-idb-value-wrapper": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.bpf": { + "source": "iana" + }, + "application/vnd.bpf3": { + "source": "iana" + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.byu.uapi+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.capasystems-pg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdxml"] + }, + "application/vnd.chess-pgn": { + "source": "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.ciedi": { + "source": "iana" + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana", + "compressible": true, + "extensions": ["csl"] + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.comicbook+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.comicbook-rar": { + "source": "iana" + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.crypto-shade-file": { + "source": "iana" + }, + "application/vnd.cryptomator.encrypted": { + "source": "iana" + }, + "application/vnd.cryptomator.vault": { + "source": "iana" + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.cyclonedx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cyclonedx+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.d3m-dataset": { + "source": "iana" + }, + "application/vnd.d3m-problem": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.datapackage+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dataresource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dbf": { + "source": "iana", + "extensions": ["dbf"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume.movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecip.rlp": { + "source": "iana" + }, + "application/vnd.eclipse.ditto+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.efi.img": { + "source": "iana" + }, + "application/vnd.efi.iso": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.espass-espass+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "compressible": true, + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.cug+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.sci+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eu.kasparian.car+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.evolv.ecig.profile": { + "source": "iana" + }, + "application/vnd.evolv.ecig.settings": { + "source": "iana" + }, + "application/vnd.evolv.ecig.theme": { + "source": "iana" + }, + "application/vnd.exstream-empower+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.exstream-package": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.ficlab.flb+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.futoin+cbor": { + "source": "iana" + }, + "application/vnd.futoin+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.gentics.grd+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.slides": { + "source": "iana" + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "compressible": true, + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.hdt": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hl7cda+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.hl7v2+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyper-item+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.imagemeter.image+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las": { + "source": "iana" + }, + "application/vnd.las.las+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.las.las+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lasxml"] + }, + "application/vnd.laszip": { + "source": "iana" + }, + "application/vnd.leap+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.liberty-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.loom": { + "source": "iana" + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana", + "extensions": ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxar.archive.3tz+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-outlook": { + "compressible": false, + "extensions": ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-printschematicket+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nearst.inv+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nebumind.line": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nimn": { + "source": "iana" + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.ocf+cbor": { + "source": "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+cbor": { + "source": "iana" + }, + "application/vnd.oma.lwm2m+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+tlv": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-email+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-file+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-folder+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.onepager": { + "source": "iana" + }, + "application/vnd.onepagertamp": { + "source": "iana" + }, + "application/vnd.onepagertamx": { + "source": "iana" + }, + "application/vnd.onepagertat": { + "source": "iana" + }, + "application/vnd.onepagertatp": { + "source": "iana" + }, + "application/vnd.onepagertatx": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana", + "compressible": true, + "extensions": ["obgx"] + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osm"] + }, + "application/vnd.opentimestamps.ots": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "iana", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "iana", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "iana", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "iana" + }, + "application/vnd.patentdive": { + "source": "iana" + }, + "application/vnd.patientecommsdoc": { + "source": "iana" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.psfs": { + "source": "iana" + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quarantainenet": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.rar": { + "source": "iana", + "extensions": ["rar"] + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.resilient.logic": { + "source": "iana" + }, + "application/vnd.restful+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "compressible": true, + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sar": { + "source": "iana" + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.seis+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shade-save-file": { + "source": "iana" + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.shootproof+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shopkick+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shp": { + "source": "iana" + }, + "application/vnd.shx": { + "source": "iana" + }, + "application/vnd.sigrok.session": { + "source": "iana" + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.snesdev-page-table": { + "source": "iana" + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sqlite3": { + "source": "iana" + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wadl"] + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.sycle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syft+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tableschema+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.tri.onesource": { + "source": "iana" + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.vel+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.veritone.aion+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veryant.thin": { + "source": "iana" + }, + "application/vnd.ves.encrypted": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.dpp": { + "source": "iana" + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.wv.ssp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.youtube.yt": { + "source": "iana" + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["vxml"] + }, + "application/voucher-cms+json": { + "source": "iana", + "compressible": true + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/wasm": { + "source": "iana", + "compressible": true, + "extensions": ["wasm"] + }, + "application/watcherinfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wif"] + }, + "application/webpush-options+json": { + "source": "iana", + "compressible": true + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-arj": { + "compressible": false, + "extensions": ["arj"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "compressible": true, + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + "extensions": ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + "extensions": ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + "extensions": ["pages"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-keepass2": { + "extensions": ["kdbx"] + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "source": "apache", + "extensions": ["nc","cdf"] + }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, + "application/x-nzb": { + "source": "apache", + "extensions": ["nzb"] + }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, + "application/x-pkcs12": { + "source": "apache", + "compressible": false, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-pki-message": { + "source": "iana" + }, + "application/x-rar-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["rar"] + }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, + "application/x-research-info-systems": { + "source": "apache", + "extensions": ["ris"] + }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, + "application/x-sh": { + "source": "apache", + "compressible": true, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-virtualbox-hdd": { + "compressible": true, + "extensions": ["hdd"] + }, + "application/x-virtualbox-ova": { + "compressible": true, + "extensions": ["ova"] + }, + "application/x-virtualbox-ovf": { + "compressible": true, + "extensions": ["ovf"] + }, + "application/x-virtualbox-vbox": { + "compressible": true, + "extensions": ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + "compressible": false, + "extensions": ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + "compressible": true, + "extensions": ["vdi"] + }, + "application/x-virtualbox-vhd": { + "compressible": true, + "extensions": ["vhd"] + }, + "application/x-virtualbox-vmdk": { + "compressible": true, + "extensions": ["vmdk"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "iana", + "extensions": ["der","crt","pem"] + }, + "application/x-x509-ca-ra-cert": { + "source": "iana" + }, + "application/x-x509-next-ca-cert": { + "source": "iana" + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana", + "compressible": true + }, + "application/xaml+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xav"] + }, + "application/xcap-caps+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xca"] + }, + "application/xcap-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xel"] + }, + "application/xcap-error+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-ns+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xns"] + }, + "application/xcon-conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/xenc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache", + "compressible": true + }, + "application/xliff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xlf"] + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd","rng"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/xmpp+xml": { + "source": "iana", + "compressible": true + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsl","xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yang-data+json": { + "source": "iana", + "compressible": true + }, + "application/yang-data+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+json": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/yin+xml": { + "source": "iana", + "compressible": true, + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "application/zstd": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana", + "compressible": false, + "extensions": ["3gpp"] + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/aac": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana", + "extensions": ["amr"] + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/flexfec": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/melp": { + "source": "iana" + }, + "audio/melp1200": { + "source": "iana" + }, + "audio/melp2400": { + "source": "iana" + }, + "audio/melp600": { + "source": "iana" + }, + "audio/mhas": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana", + "extensions": ["mxmf"] + }, + "audio/mp3": { + "compressible": false, + "extensions": ["mp3"] + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["m4a","mp4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx","opus"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/scip": { + "source": "iana" + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sofa": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tetra_acelp": { + "source": "iana" + }, + "audio/tetra_acelp_bb": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/tsvcis": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/usac": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dts.uhd": { + "source": "iana" + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.presonus.multitrack": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/collection": { + "source": "iana", + "extensions": ["ttc"] + }, + "font/otf": { + "source": "iana", + "compressible": true, + "extensions": ["otf"] + }, + "font/sfnt": { + "source": "iana" + }, + "font/ttf": { + "source": "iana", + "compressible": true, + "extensions": ["ttf"] + }, + "font/woff": { + "source": "iana", + "extensions": ["woff"] + }, + "font/woff2": { + "source": "iana", + "extensions": ["woff2"] + }, + "image/aces": { + "source": "iana", + "extensions": ["exr"] + }, + "image/apng": { + "compressible": false, + "extensions": ["apng"] + }, + "image/avci": { + "source": "iana", + "extensions": ["avci"] + }, + "image/avcs": { + "source": "iana", + "extensions": ["avcs"] + }, + "image/avif": { + "source": "iana", + "compressible": false, + "extensions": ["avif"] + }, + "image/bmp": { + "source": "iana", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/dicom-rle": { + "source": "iana", + "extensions": ["drle"] + }, + "image/emf": { + "source": "iana", + "extensions": ["emf"] + }, + "image/fits": { + "source": "iana", + "extensions": ["fits"] + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/heic": { + "source": "iana", + "extensions": ["heic"] + }, + "image/heic-sequence": { + "source": "iana", + "extensions": ["heics"] + }, + "image/heif": { + "source": "iana", + "extensions": ["heif"] + }, + "image/heif-sequence": { + "source": "iana", + "extensions": ["heifs"] + }, + "image/hej2k": { + "source": "iana", + "extensions": ["hej2"] + }, + "image/hsj2": { + "source": "iana", + "extensions": ["hsj2"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jls": { + "source": "iana", + "extensions": ["jls"] + }, + "image/jp2": { + "source": "iana", + "compressible": false, + "extensions": ["jp2","jpg2"] + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jph": { + "source": "iana", + "extensions": ["jph"] + }, + "image/jphc": { + "source": "iana", + "extensions": ["jhc"] + }, + "image/jpm": { + "source": "iana", + "compressible": false, + "extensions": ["jpm"] + }, + "image/jpx": { + "source": "iana", + "compressible": false, + "extensions": ["jpx","jpf"] + }, + "image/jxr": { + "source": "iana", + "extensions": ["jxr"] + }, + "image/jxra": { + "source": "iana", + "extensions": ["jxra"] + }, + "image/jxrs": { + "source": "iana", + "extensions": ["jxrs"] + }, + "image/jxs": { + "source": "iana", + "extensions": ["jxs"] + }, + "image/jxsc": { + "source": "iana", + "extensions": ["jxsc"] + }, + "image/jxsi": { + "source": "iana", + "extensions": ["jxsi"] + }, + "image/jxss": { + "source": "iana", + "extensions": ["jxss"] + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/ktx2": { + "source": "iana", + "extensions": ["ktx2"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana", + "extensions": ["pti"] + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana", + "extensions": ["t38"] + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tif","tiff"] + }, + "image/tiff-fx": { + "source": "iana", + "extensions": ["tfx"] + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana", + "extensions": ["azv"] + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana", + "compressible": true, + "extensions": ["ico"] + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-dds": { + "compressible": true, + "extensions": ["dds"] + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.pco.b16": { + "source": "iana", + "extensions": ["b16"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana", + "extensions": ["tap"] + }, + "image/vnd.valve.source.texture": { + "source": "iana", + "extensions": ["vtf"] + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana", + "extensions": ["pcx"] + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/wmf": { + "source": "iana", + "extensions": ["wmf"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "compressible": true, + "extensions": ["ico"] + }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, + "image/x-mrsid-image": { + "source": "apache", + "extensions": ["sid"] + }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, + "image/x-pcx": { + "source": "apache", + "extensions": ["pcx"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana", + "extensions": [ + "disposition-notification" + ] + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana", + "extensions": ["u8msg"] + }, + "message/global-delivery-status": { + "source": "iana", + "extensions": ["u8dsn"] + }, + "message/global-disposition-notification": { + "source": "iana", + "extensions": ["u8mdn"] + }, + "message/global-headers": { + "source": "iana", + "extensions": ["u8hdr"] + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana", + "extensions": ["wsc"] + }, + "model/3mf": { + "source": "iana", + "extensions": ["3mf"] + }, + "model/e57": { + "source": "iana" + }, + "model/gltf+json": { + "source": "iana", + "compressible": true, + "extensions": ["gltf"] + }, + "model/gltf-binary": { + "source": "iana", + "compressible": true, + "extensions": ["glb"] + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/mtl": { + "source": "iana", + "extensions": ["mtl"] + }, + "model/obj": { + "source": "iana", + "extensions": ["obj"] + }, + "model/step": { + "source": "iana" + }, + "model/step+xml": { + "source": "iana", + "compressible": true, + "extensions": ["stpx"] + }, + "model/step+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpz"] + }, + "model/step-xml+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpxz"] + }, + "model/stl": { + "source": "iana", + "extensions": ["stl"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana", + "compressible": true + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana", + "extensions": ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana", + "extensions": ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana", + "extensions": ["x_t"] + }, + "model/vnd.pytha.pyox": { + "source": "iana" + }, + "model/vnd.rosette.annotated-data-model": { + "source": "iana" + }, + "model/vnd.sap.vds": { + "source": "iana", + "extensions": ["vds"] + }, + "model/vnd.usdz+zip": { + "source": "iana", + "compressible": false, + "extensions": ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana", + "extensions": ["bsp"] + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana", + "extensions": ["x3db"] + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana", + "extensions": ["x3dv"] + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana" + }, + "multipart/multilingual": { + "source": "iana" + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/vnd.bint.med-plus": { + "source": "iana" + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/cql": { + "source": "iana" + }, + "text/cql-expression": { + "source": "iana" + }, + "text/cql-identifier": { + "source": "iana" + }, + "text/css": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fhirpath": { + "source": "iana" + }, + "text/flexfec": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/gff3": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "compressible": true, + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana", + "compressible": true, + "extensions": ["markdown","md"] + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mdx": { + "compressible": true, + "extensions": ["mdx"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana", + "charset": "UTF-8" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana", + "charset": "UTF-8" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/prs.prop.logic": { + "source": "iana" + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/shaclc": { + "source": "iana" + }, + "text/shex": { + "source": "iana", + "extensions": ["shex"] + }, + "text/slim": { + "extensions": ["slim","slm"] + }, + "text/spdx": { + "source": "iana", + "extensions": ["spdx"] + }, + "text/strings": { + "source": "iana" + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.ascii-art": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.familysearch.gedcom": { + "source": "iana", + "extensions": ["ged"] + }, + "text/vnd.ficlab.flt": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.gml": { + "source": "iana" + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.hans": { + "source": "iana" + }, + "text/vnd.hgl": { + "source": "iana" + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.senx.warpscript": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sosi": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-org": { + "compressible": true, + "extensions": ["org"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "compressible": true, + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "iana" + }, + "video/3gpp": { + "source": "iana", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "iana" + }, + "video/3gpp2": { + "source": "iana", + "extensions": ["3g2"] + }, + "video/av1": { + "source": "iana" + }, + "video/bmpeg": { + "source": "iana" + }, + "video/bt656": { + "source": "iana" + }, + "video/celb": { + "source": "iana" + }, + "video/dv": { + "source": "iana" + }, + "video/encaprtp": { + "source": "iana" + }, + "video/ffv1": { + "source": "iana" + }, + "video/flexfec": { + "source": "iana" + }, + "video/h261": { + "source": "iana", + "extensions": ["h261"] + }, + "video/h263": { + "source": "iana", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "iana" + }, + "video/h263-2000": { + "source": "iana" + }, + "video/h264": { + "source": "iana", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "iana" + }, + "video/h264-svc": { + "source": "iana" + }, + "video/h265": { + "source": "iana" + }, + "video/iso.segment": { + "source": "iana", + "extensions": ["m4s"] + }, + "video/jpeg": { + "source": "iana", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "iana" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/jxsv": { + "source": "iana" + }, + "video/mj2": { + "source": "iana", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "iana" + }, + "video/mp2p": { + "source": "iana" + }, + "video/mp2t": { + "source": "iana", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "iana" + }, + "video/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "iana" + }, + "video/mpv": { + "source": "iana" + }, + "video/nv": { + "source": "iana" + }, + "video/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "iana" + }, + "video/pointer": { + "source": "iana" + }, + "video/quicktime": { + "source": "iana", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raptorfec": { + "source": "iana" + }, + "video/raw": { + "source": "iana" + }, + "video/rtp-enc-aescm128": { + "source": "iana" + }, + "video/rtploopback": { + "source": "iana" + }, + "video/rtx": { + "source": "iana" + }, + "video/scip": { + "source": "iana" + }, + "video/smpte291": { + "source": "iana" + }, + "video/smpte292m": { + "source": "iana" + }, + "video/ulpfec": { + "source": "iana" + }, + "video/vc1": { + "source": "iana" + }, + "video/vc2": { + "source": "iana" + }, + "video/vnd.cctv": { + "source": "iana" + }, + "video/vnd.dece.hd": { + "source": "iana", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "iana", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "iana" + }, + "video/vnd.dece.pd": { + "source": "iana", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "iana", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "iana", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "iana" + }, + "video/vnd.directv.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dvb.file": { + "source": "iana", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "iana", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "iana" + }, + "video/vnd.motorola.video": { + "source": "iana" + }, + "video/vnd.motorola.videop": { + "source": "iana" + }, + "video/vnd.mpegurl": { + "source": "iana", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "iana", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "iana" + }, + "video/vnd.nokia.mp4vr": { + "source": "iana" + }, + "video/vnd.nokia.videovoip": { + "source": "iana" + }, + "video/vnd.objectvideo": { + "source": "iana" + }, + "video/vnd.radgamettools.bink": { + "source": "iana" + }, + "video/vnd.radgamettools.smacker": { + "source": "iana" + }, + "video/vnd.sealed.mpeg1": { + "source": "iana" + }, + "video/vnd.sealed.mpeg4": { + "source": "iana" + }, + "video/vnd.sealed.swf": { + "source": "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "iana" + }, + "video/vnd.uvvu.mp4": { + "source": "iana", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "iana", + "extensions": ["viv"] + }, + "video/vnd.youtube.yt": { + "source": "iana" + }, + "video/vp8": { + "source": "iana" + }, + "video/vp9": { + "source": "iana" + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/node_modules/mime-db/index.js b/node_modules/mime-db/index.js new file mode 100644 index 0000000..ec2be30 --- /dev/null +++ b/node_modules/mime-db/index.js @@ -0,0 +1,12 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/node_modules/mime-db/package.json b/node_modules/mime-db/package.json new file mode 100644 index 0000000..32c14b8 --- /dev/null +++ b/node_modules/mime-db/package.json @@ -0,0 +1,60 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.52.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "Robert Kieffer (http://github.com/broofa)" + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": "jshttp/mime-db", + "devDependencies": { + "bluebird": "3.7.2", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "4.16.3", + "eslint": "7.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.1.1", + "eslint-plugin-standard": "4.1.0", + "gnode": "0.1.2", + "media-typer": "1.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0", + "raw-body": "2.5.0", + "stream-to-array": "2.3.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "fetch": "node scripts/fetch-apache && gnode scripts/fetch-iana && node scripts/fetch-nginx", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/mime-types/HISTORY.md b/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..c5043b7 --- /dev/null +++ b/node_modules/mime-types/HISTORY.md @@ -0,0 +1,397 @@ +2.1.35 / 2022-03-12 +=================== + + * deps: mime-db@1.52.0 + - Add extensions from IANA for more `image/*` types + - Add extension `.asc` to `application/pgp-keys` + - Add extensions to various XML types + - Add new upstream MIME types + +2.1.34 / 2021-11-08 +=================== + + * deps: mime-db@1.51.0 + - Add new upstream MIME types + +2.1.33 / 2021-10-01 +=================== + + * deps: mime-db@1.50.0 + - Add deprecated iWorks mime types and extensions + - Add new upstream MIME types + +2.1.32 / 2021-07-27 +=================== + + * deps: mime-db@1.49.0 + - Add extension `.trig` to `application/trig` + - Add new upstream MIME types + +2.1.31 / 2021-06-01 +=================== + + * deps: mime-db@1.48.0 + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add new upstream MIME types + +2.1.30 / 2021-04-02 +=================== + + * deps: mime-db@1.47.0 + - Add extension `.amr` to `audio/amr` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +2.1.29 / 2021-02-17 +=================== + + * deps: mime-db@1.46.0 + - Add extension `.amr` to `audio/amr` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.opus` to `audio/ogg` + - Add new upstream MIME types + +2.1.28 / 2021-01-01 +=================== + + * deps: mime-db@1.45.0 + - Add `application/ubjson` with extension `.ubj` + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + +2.1.27 / 2020-04-23 +=================== + + * deps: mime-db@1.44.0 + - Add charsets from IANA + - Add extension `.cjs` to `application/node` + - Add new upstream MIME types + +2.1.26 / 2020-01-05 +=================== + + * deps: mime-db@1.43.0 + - Add `application/x-keepass2` with extension `.kdbx` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extensions from IANA for `application/*+xml` types + - Add new upstream MIME types + +2.1.25 / 2019-11-12 +=================== + + * deps: mime-db@1.42.0 + - Add new upstream MIME types + - Add `application/toml` with extension `.toml` + - Add `image/vnd.ms-dds` with extension `.dds` + +2.1.24 / 2019-04-20 +=================== + + * deps: mime-db@1.40.0 + - Add extensions from IANA for `model/*` types + - Add `text/mdx` with extension `.mdx` + +2.1.23 / 2019-04-17 +=================== + + * deps: mime-db@~1.39.0 + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add new upstream MIME types + +2.1.22 / 2019-02-14 +=================== + + * deps: mime-db@~1.38.0 + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add new upstream MIME types + +2.1.21 / 2018-10-19 +=================== + + * deps: mime-db@~1.37.0 + - Add extensions to HEIC image types + - Add new upstream MIME types + +2.1.20 / 2018-08-26 +=================== + + * deps: mime-db@~1.36.0 + - Add Apple file extensions from IANA + - Add extensions from IANA for `image/*` types + - Add new upstream MIME types + +2.1.19 / 2018-07-17 +=================== + + * deps: mime-db@~1.35.0 + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.owl` to `application/rdf+xml` + - Add new upstream MIME types + - Add UTF-8 as default charset for `text/turtle` + +2.1.18 / 2018-02-16 +=================== + + * deps: mime-db@~1.33.0 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add new upstream MIME types + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +2.1.17 / 2017-09-01 +=================== + + * deps: mime-db@~1.30.0 + - Add `application/vnd.ms-outlook` + - Add `application/x-arj` + - Add extension `.mjs` to `application/javascript` + - Add glTF types and extensions + - Add new upstream MIME types + - Add `text/x-org` + - Add VirtualBox MIME types + - Fix `source` records for `video/*` types that are IANA + - Update `font/opentype` to registered `font/otf` + +2.1.16 / 2017-07-24 +=================== + + * deps: mime-db@~1.29.0 + - Add `application/fido.trusted-apps+json` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add new upstream MIME types + - Update extensions `.md` and `.markdown` to be `text/markdown` + +2.1.15 / 2017-03-23 +=================== + + * deps: mime-db@~1.27.0 + - Add new mime types + - Add `image/apng` + +2.1.14 / 2017-01-14 +=================== + + * deps: mime-db@~1.26.0 + - Add new mime types + +2.1.13 / 2016-11-18 +=================== + + * deps: mime-db@~1.25.0 + - Add new mime types + +2.1.12 / 2016-09-18 +=================== + + * deps: mime-db@~1.24.0 + - Add new mime types + - Add `audio/mp3` + +2.1.11 / 2016-05-01 +=================== + + * deps: mime-db@~1.23.0 + - Add new mime types + +2.1.10 / 2016-02-15 +=================== + + * deps: mime-db@~1.22.0 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + +2.0.10 / 2015-03-13 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/node_modules/mime-types/LICENSE b/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mime-types/README.md b/node_modules/mime-types/README.md new file mode 100644 index 0000000..48d2fb4 --- /dev/null +++ b/node_modules/mime-types/README.md @@ -0,0 +1,113 @@ +# mime-types + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +The ultimate javascript content-type utility. + +Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, + `mime-types` simply returns `false`, so do + `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- No `.define()` functionality +- Bug fixes for `.lookup(path)` + +Otherwise, the API is compatible with `mime` 1.x. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. +When given an extension, `mime.lookup` is used to get the matching +content-type, otherwise the given content-type is used. Then if the +content-type does not already have a `charset` parameter, `mime.charset` +is used to get the default charset and add to the returned content-type. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' +mime.contentType('text/html') // 'text/html; charset=utf-8' +mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci +[ci-url]: https://github.com/jshttp/mime-types/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master +[node-version-image]: https://badgen.net/npm/node/mime-types +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-types +[npm-url]: https://npmjs.org/package/mime-types +[npm-version-image]: https://badgen.net/npm/v/mime-types diff --git a/node_modules/mime-types/index.js b/node_modules/mime-types/index.js new file mode 100644 index 0000000..b9f34d5 --- /dev/null +++ b/node_modules/mime-types/index.js @@ -0,0 +1,188 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var db = require('mime-db') +var extname = require('path').extname + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/node_modules/mime-types/package.json b/node_modules/mime-types/package.json new file mode 100644 index 0000000..bbef696 --- /dev/null +++ b/node_modules/mime-types/package.json @@ -0,0 +1,44 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.35", + "contributors": [ + "Douglas Christopher Wilson ", + "Jeremiah Senkpiel (https://searchbeam.jit.su)", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": "jshttp/mime-types", + "dependencies": { + "mime-db": "1.52.0" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.2", + "nyc": "15.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec test/test.js", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/minio/LICENSE b/node_modules/minio/LICENSE new file mode 100644 index 0000000..8f71f43 --- /dev/null +++ b/node_modules/minio/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/node_modules/minio/MAINTAINERS.md b/node_modules/minio/MAINTAINERS.md new file mode 100644 index 0000000..57cfc2f --- /dev/null +++ b/node_modules/minio/MAINTAINERS.md @@ -0,0 +1,66 @@ +# For maintainers only +Development of MinIO JS SDK require nodejs14+ and [npm7+](https://www.npmjs.org/). + +## Responsibilities +Go through [Maintainer Responsibility Guide](https://gist.github.com/abperiasamy/f4d9b31d3186bbd26522). + +## Setup your minio-js Github Repository +Clone [minio-js](https://github.com/minio/minio-js/) source repository locally. +```sh +$ git clone git@github.com:minio/minio-js +$ cd minio-js +``` + +### Install deps +```shell +$ npm install +``` + +### Testing +```shell +$ npm test +``` + +## Publishing new release +Edit `package.json` version and all other files to the latest version as shown below. +```sh +$ git grep 3.2.0 | cut -f1 -d: | xargs sed s/3.2.0/3.2.1/g -i +$ grep version package.json + "version": "3.2.1", +$ git commit -a -m "Bump to 3.2.1 release" +``` + +### Publish to NPM +Login to your npm account. +```sh +$ npm login +... +Logged in as minio on https://registry.npmjs.org/. +``` + +Build for release +```sh +$ npm run build +``` + +Publish the new release to npm repository. +``` +$ npm publish +``` + +### Tag +Tag and sign your release commit, additionally this step requires you to have access to MinIO's trusted private key. +``` +$ export GNUPGHOME=/media/${USER}/minio/trusted +$ git tag -s 3.2.1 +$ git push +$ git push --tags +``` + +### Announce +Announce new release by adding release notes at https://github.com/minio/minio-js/releases from `trusted@minio.io` account. Release notes requires two sections `highlights` and `changelog`. Highlights is a bulleted list of salient features in this release and Changelog contains list of all commits since the last release. + +To generate `changelog` +```sh +git log --no-color --pretty=format:'-%d %s (%cr) <%an>' .. +``` diff --git a/node_modules/minio/README.md b/node_modules/minio/README.md new file mode 100644 index 0000000..108eb0e --- /dev/null +++ b/node_modules/minio/README.md @@ -0,0 +1,272 @@ +# MinIO JavaScript Library for Amazon S3 Compatible Cloud Storage [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) + +[![NPM](https://nodei.co/npm/minio.png)](https://nodei.co/npm/minio/) + +The MinIO JavaScript Client SDK provides high level APIs to access any Amazon S3 compatible object storage server. + +This guide will show you how to install the client SDK and execute an example JavaScript program. +For a complete list of APIs and examples, please take a look at the [JavaScript Client API Reference](https://docs.min.io/enterprise/aistor-object-store/developers/sdk/javascript/api/) documentation. + +This document presumes you have a working [Node.js](http://nodejs.org/) development environment, LTS versions v16, v18 or v20. + +## Download from NPM + +```sh +npm install --save minio +``` + +## Download from Source + +```sh +git clone https://github.com/minio/minio-js +cd minio-js +npm install +npm run build +npm install -g +``` + +## Using with TypeScript + +`minio>7.1.0` is shipped with builtin type definition, `@types/minio` is no longer needed. + +## Initialize MinIO Client + +The following parameters are needed to connect to a MinIO object storage server: + +| Parameter | Description | +| :---------- | :--------------------------------------------------------------------------- | +| `endPoint` | Hostname of the object storage service. | +| `port` | TCP/IP port number. Optional, defaults to `80` for HTTP and `443` for HTTPs. | +| `accessKey` | Access key (user ID) of an account in the S3 service. | +| `secretKey` | Secret key (password) of an account in the S3 service. | +| `useSSL` | Optional, set to 'true' to enable secure (HTTPS) access. | + +```js +import * as Minio from 'minio' + +const minioClient = new Minio.Client({ + endPoint: 'play.min.io', + port: 9000, + useSSL: true, + accessKey: 'Q3AM3UQ867SPQQA43P2F', + secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG', +}) +``` + +## Quick Start Example - File Uploader + +This example connects to an object storage server, creates a bucket, and uploads a file to the bucket. +It uses the MinIO `play` server, a public MinIO cluster located at [https://play.min.io](https://play.min.io). + +The `play` server runs the latest stable version of MinIO and may be used for testing and development. +The access credentials shown in this example are open to the public. +All data uploaded to `play` should be considered public and non-protected. + +#### file-uploader.mjs + +```js +import * as Minio from 'minio' + +// Instantiate the MinIO client with the object store service +// endpoint and an authorized user's credentials +// play.min.io is the MinIO public test cluster +const minioClient = new Minio.Client({ + endPoint: 'play.min.io', + port: 9000, + useSSL: true, + accessKey: 'Q3AM3UQ867SPQQA43P2F', + secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG', +}) + +// File to upload +const sourceFile = '/tmp/test-file.txt' + +// Destination bucket +const bucket = 'js-test-bucket' + +// Destination object name +const destinationObject = 'my-test-file.txt' + +// Check if the bucket exists +// If it doesn't, create it +const exists = await minioClient.bucketExists(bucket) +if (exists) { + console.log('Bucket ' + bucket + ' exists.') +} else { + await minioClient.makeBucket(bucket, 'us-east-1') + console.log('Bucket ' + bucket + ' created in "us-east-1".') +} + +// Set the object metadata +var metaData = { + 'Content-Type': 'text/plain', + 'X-Amz-Meta-Testing': 1234, + example: 5678, +} + +// Upload the file with fPutObject +// If an object with the same name exists, +// it is updated with new data +await minioClient.fPutObject(bucket, destinationObject, sourceFile, metaData) +console.log('File ' + sourceFile + ' uploaded as object ' + destinationObject + ' in bucket ' + bucket) +``` + +#### Run the File Uploader + +```sh +node file-uploader.mjs +Bucket js-test-bucket created successfully in "us-east-1". +File /tmp/test-file.txt uploaded successfully as my-test-file.txt to bucket js-test-bucket +``` + +Verify the object was created with [`mc`](https://min.io/docs/minio/linux/reference/minio-mc.html): + +``` +mc ls play/js-test-bucket +[2023-11-10 17:52:20 UTC] 20KiB STANDARD my-test-file.txt +``` + +## API Reference + +The complete API Reference is available here: + +- [MinIO JavaScript API Reference](https://min.io/docs/minio/linux/developers/javascript/API.html) + +### Bucket Operations + +- [`makeBucket`](https://min.io/docs/minio/linux/developers/javascript/API.html#makeBucket) +- [`listBuckets`](https://min.io/docs/minio/linux/developers/javascript/API.html#listBuckets) +- [`bucketExists`](https://min.io/docs/minio/linux/developers/javascript/API.html#bucketExists) +- [`removeBucket`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeBucket) +- [`listObjects`](https://min.io/docs/minio/linux/developers/javascript/API.html#listObjects) +- [`listObjectsV2`](https://min.io/docs/minio/linux/developers/javascript/API.html#listObjectsV2) +- [`listObjectsV2WithMetadata`](https://min.io/docs/minio/linux/developers/javascript/API.html#listObjectsV2WithMetadata) (Extension) +- [`listIncompleteUploads`](https://min.io/docs/minio/linux/developers/javascript/API.html#listIncompleteUploads) +- [`getBucketVersioning`](https://min.io/docs/minio/linux/developers/javascript/API.html#getBucketVersioning) +- [`setBucketVersioning`](https://min.io/docs/minio/linux/developers/javascript/API.html#setBucketVersioning) +- [`setBucketLifecycle`](https://min.io/docs/minio/linux/developers/javascript/API.html#setBucketLifecycle) +- [`getBucketLifecycle`](https://min.io/docs/minio/linux/developers/javascript/API.html#getBucketLifecycle) +- [`removeBucketLifecycle`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeBucketLifecycle) +- [`getObjectLockConfig`](https://min.io/docs/minio/linux/developers/javascript/API.html#getObjectLockConfig) +- [`setObjectLockConfig`](https://min.io/docs/minio/linux/developers/javascript/API.html#setObjectLockConfig) + +### File Object Operations + +- [`fPutObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#fPutObject) +- [`fGetObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#fGetObject) + +### Object Operations + +- [`getObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#getObject) +- [`putObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#putObject) +- [`copyObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#copyObject) +- [`statObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#statObject) +- [`removeObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeObject) +- [`removeObjects`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeObjects) +- [`removeIncompleteUpload`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeIncompleteUpload) +- [`selectObjectContent`](https://min.io/docs/minio/linux/developers/javascript/API.html#selectObjectContent) + +### Presigned Operations + +- [`presignedUrl`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedUrl) +- [`presignedGetObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedGetObject) +- [`presignedPutObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedPutObject) +- [`presignedPostPolicy`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedPostPolicy) + +### Bucket Notification Operations + +- [`getBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#getBucketNotification) +- [`setBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#setBucketNotification) +- [`removeAllBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeAllBucketNotification) +- [`listenBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#listenBucketNotification) (MinIO Extension) + +### Bucket Policy Operations + +- [`getBucketPolicy`](https://min.io/docs/minio/linux/developers/javascript/API.html#getBucketPolicy) +- [`setBucketPolicy`](https://min.io/docs/minio/linux/developers/javascript/API.html#setBucketPolicy) + +## Examples + +#### Bucket Operations + +- [list-buckets.mjs](https://github.com/minio/minio-js/blob/master/examples/list-buckets.mjs) +- [list-objects.js](https://github.com/minio/minio-js/blob/master/examples/list-objects.js) +- [list-objects-v2.js](https://github.com/minio/minio-js/blob/master/examples/list-objects-v2.js) +- [list-objects-v2-with-metadata.js](https://github.com/minio/minio-js/blob/master/examples/list-objects-v2-with-metadata.js) (Extension) +- [bucket-exists.mjs](https://github.com/minio/minio-js/blob/master/examples/bucket-exists.mjs) +- [make-bucket.mjs](https://github.com/minio/minio-js/blob/master/examples/make-bucket.mjs) +- [remove-bucket.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-bucket.mjs) +- [list-incomplete-uploads.js](https://github.com/minio/minio-js/blob/master/examples/list-incomplete-uploads.js) +- [get-bucket-versioning.mjs](https://github.com/minio/minio-js/blob/master/examples/get-bucket-versioning.mjs) +- [set-bucket-versioning.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-versioning.mjs) +- [set-bucket-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-tagging.mjs) +- [get-bucket-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/get-bucket-tagging.mjs) +- [remove-bucket-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-bucket-tagging.mjs) +- [set-bucket-lifecycle.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-lifecycle.mjs) +- [get-bucket-lifecycle.mjs](https://github.com/minio/minio-js/blob/master/examples/get-bucket-lifecycle.mjs) +- [remove-bucket-lifecycle.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-bucket-lifecycle.mjs) +- [get-object-lock-config.mjs](https://github.com/minio/minio-js/blob/master/examples/get-object-lock-config.mjs) +- [set-object-lock-config.mjs](https://github.com/minio/minio-js/blob/master/examples/set-object-lock-config.mjs) +- [set-bucket-replication.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-replication.mjs) +- [get-bucket-replication.mjs](https://github.com/minio/minio-js/blob/master/examples/get-bucket-replication.mjs) +- [remove-bucket-replication.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-bucket-replication.mjs) +- [set-bucket-encryption.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-encryption.mjs) +- [get-bucket-encryption.mjs](https://github.com/minio/minio-js/blob/master/examples/get-bucket-encryption.mjs) +- [remove-bucket-encryption.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-bucket-encryption.mjs) + +#### File Object Operations + +- [fput-object.mjs](https://github.com/minio/minio-js/blob/master/examples/fput-object.mjs) +- [fget-object.mjs](https://github.com/minio/minio-js/blob/master/examples/fget-object.mjs) + +#### Object Operations + +- [put-object.mjs](https://github.com/minio/minio-js/blob/master/examples/put-object.mjs) +- [get-object.mjs](https://github.com/minio/minio-js/blob/master/examples/get-object.mjs) +- [copy-object.mjs](https://github.com/minio/minio-js/blob/master/examples/copy-object.mjs) +- [get-partialobject.mjs](https://github.com/minio/minio-js/blob/master/examples/get-partialobject.mjs) +- [remove-object.js](https://github.com/minio/minio-js/blob/master/examples/remove-object.js) +- [remove-incomplete-upload.js](https://github.com/minio/minio-js/blob/master/examples/remove-incomplete-upload.js) +- [stat-object.mjs](https://github.com/minio/minio-js/blob/master/examples/stat-object.mjs) +- [get-object-retention.mjs](https://github.com/minio/minio-js/blob/master/examples/get-object-retention.mjs) +- [put-object-retention.mjs](https://github.com/minio/minio-js/blob/master/examples/put-object-retention.mjs) +- [set-object-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/set-object-tagging.mjs) +- [get-object-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/get-object-tagging.mjs) +- [remove-object-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-object-tagging.mjs) +- [set-object-legal-hold.mjs](https://github.com/minio/minio-js/blob/master/examples/set-object-legal-hold.mjs) +- [get-object-legal-hold.mjs](https://github.com/minio/minio-js/blob/master/examples/get-object-legal-hold.mjs) +- [compose-object.mjs](https://github.com/minio/minio-js/blob/master/examples/compose-object.mjs) +- [select-object-content.mjs](https://github.com/minio/minio-js/blob/master/examples/select-object-content.mjs) + +#### Presigned Operations + +- [presigned-getobject.mjs](https://github.com/minio/minio-js/blob/master/examples/presigned-getobject.mjs) +- [presigned-putobject.mjs](https://github.com/minio/minio-js/blob/master/examples/presigned-putobject.mjs) +- [presigned-postpolicy.mjs](https://github.com/minio/minio-js/blob/master/examples/presigned-postpolicy.mjs) + +#### Bucket Notification Operations + +- [get-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/get-bucket-notification.js) +- [set-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/set-bucket-notification.js) +- [remove-all-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/remove-all-bucket-notification.js) +- [listen-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/minio/listen-bucket-notification.js) (MinIO Extension) + +#### Bucket Policy Operations + +- [get-bucket-policy.js](https://github.com/minio/minio-js/blob/master/examples/get-bucket-policy.js) +- [set-bucket-policy.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-policy.mjs) + +## Custom Settings + +- [setAccelerateEndPoint](https://github.com/minio/minio-js/blob/master/examples/set-accelerate-end-point.js) + +## Explore Further + +- [Complete Documentation](https://min.io/docs/minio/kubernetes/upstream/index.html) +- [MinIO JavaScript Client SDK API Reference](https://min.io/docs/minio/linux/developers/javascript/API.html) + +## Contribute + +- [Contributors Guide](https://github.com/minio/minio-js/blob/master/CONTRIBUTING.md) + +![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/minio/minio-js/nodejs.yml) diff --git a/node_modules/minio/README_zh_CN.md b/node_modules/minio/README_zh_CN.md new file mode 100644 index 0000000..4c44e6b --- /dev/null +++ b/node_modules/minio/README_zh_CN.md @@ -0,0 +1,200 @@ +# 适用于Amazon S3兼容云存储的Minio JavaScript Library [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) + +[![NPM](https://nodei.co/npm/minio.png)](https://nodei.co/npm/minio/) + +MinIO JavaScript Client SDK提供简单的API来访问任何Amazon S3兼容的对象存储服务。 + +本快速入门指南将向您展示如何安装客户端SDK并执行示例JavaScript程序。有关API和示例的完整列表,请参阅[JavaScript客户端API参考](https://docs.min.io/enterprise/aistor-object-store/developers/minio-drivers/#javascript)文档。 + +本文假设你已经安装了[nodejs](http://nodejs.org/) 。 + +## 使用NPM下载 + +`minio>7.1.0` 拥有自带的类型定义,不再需要安装 `@types/minio`。 + +## 下载并安装源码 + +```sh +git clone https://github.com/minio/minio-js +cd minio-js +npm install +npm install -g +``` + +## 初使化Minio Client + +你需要设置5个属性来链接Minio对象存储服务。 + +| 参数 | 描述 | +| :------- | :------------ | +| endPoint |对象存储服务的URL | +|port| TCP/IP端口号。可选值,如果是使用HTTP的话,默认值是`80`;如果使用HTTPS的话,默认值是`443`。| +| accessKey | Access key是唯一标识你的账户的用户ID。 | +| secretKey | Secret key是你账户的密码。 | +|useSSL |true代表使用HTTPS | + + +```js +import * as Minio from 'minio' + +const minioClient = new Minio.Client({ + endPoint: 'play.min.io', + port: 9000, + useSSL: true, + accessKey: 'Q3AM3UQ867SPQQA43P2F', + secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG' +}); +``` + +## 示例-文件上传 + +本示例连接到一个对象存储服务,创建一个存储桶并上传一个文件到存储桶中。 + +我们在本示例中使用运行在 [https://play.min.io](https://play.min.io) 上的Minio服务,你可以用这个服务来开发和测试。示例中的访问凭据是公开的。 + +#### file-uploader.js + +```js +import * as Minio from 'minio' + +// Instantiate the minio client with the endpoint +// and access keys as shown below. +const minioClient = new Minio.Client({ + endPoint: 'play.min.io', + port: 9000, + useSSL: true, + accessKey: 'Q3AM3UQ867SPQQA43P2F', + secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG' +}); + +// File that needs to be uploaded. +const file = '/tmp/photos-europe.tar' + +// Make a bucket called europetrip. +minioClient.makeBucket('europetrip', 'us-east-1', function(err) { + if (err) return console.log(err) + + console.log('Bucket created successfully in "us-east-1".') + + const metaData = { + 'Content-Type': 'application/octet-stream', + 'X-Amz-Meta-Testing': 1234, + 'example': 5678 + } + // Using fPutObject API upload your file to the bucket europetrip. + minioClient.fPutObject('europetrip', 'photos-europe.tar', file, metaData, function(err, etag) { + if (err) return console.log(err) + console.log('File uploaded successfully.') + }); +}); +``` + +#### 运行file-uploader + +```sh +node file-uploader.js +Bucket created successfully in "us-east-1". + +mc ls play/europetrip/ +[2016-05-25 23:49:50 PDT] 17MiB photos-europe.tar +``` + +## API文档 + +完整的API文档在这里。 +* [完整API文档](https://min.io/docs/minio/linux/developers/javascript/API.html) + +### API文档 : 操作存储桶 + +* [`makeBucket`](https://min.io/docs/minio/linux/developers/javascript/API.html#makeBucket) +* [`listBuckets`](https://min.io/docs/minio/linux/developers/javascript/API.html#listBuckets) +* [`bucketExists`](https://min.io/docs/minio/linux/developers/javascript/API.html#bucketExists) +* [`removeBucket`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeBucket) +* [`listObjects`](https://min.io/docs/minio/linux/developers/javascript/API.html#listObjects) +* [`listObjectsV2`](https://min.io/docs/minio/linux/developers/javascript/API.html#listObjectsV2) +* [`listIncompleteUploads`](https://min.io/docs/minio/linux/developers/javascript/API.html#listIncompleteUploads) + +### API文档 : 操作文件对象 + +* [`fPutObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#fPutObject) +* [`fGetObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#fGetObject) + +### API文档 : 操作对象 + +* [`getObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#getObject) +* [`putObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#putObject) +* [`copyObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#copyObject) +* [`statObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#statObject) +* [`removeObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeObject) +* [`removeIncompleteUpload`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeIncompleteUpload) + +### API文档 : Presigned操作 + +* [`presignedGetObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedGetObject) +* [`presignedPutObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedPutObject) +* [`presignedPostPolicy`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedPostPolicy) + +### API文档 : 存储桶通知 + +* [`getBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#getBucketNotification) +* [`setBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#setBucketNotification) +* [`removeAllBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeAllBucketNotification) +* [`listenBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#listenBucketNotification) (MinIO Extension) + +### API文档 : 存储桶策略 + +* [`getBucketPolicy`](https://min.io/docs/minio/linux/developers/javascript/API.html#getBucketPolicy) +* [`setBucketPolicy`](https://min.io/docs/minio/linux/developers/javascript/API.html#setBucketPolicy) + + +## 完整示例 + +#### 完整示例 : 操作存储桶 + +* [list-buckets.js](https://github.com/minio/minio-js/blob/master/examples/list-buckets.js) +* [list-objects.js](https://github.com/minio/minio-js/blob/master/examples/list-objects.js) +* [list-objects-v2.js](https://github.com/minio/minio-js/blob/master/examples/list-objects-v2.js) +* [bucket-exists.mjs](https://github.com/minio/minio-js/blob/master/examples/bucket-exists.mjs) +* [make-bucket.mjs](https://github.com/minio/minio-js/blob/master/examples/make-bucket.js) +* [remove-bucket.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-bucket.mjs) +* [list-incomplete-uploads.js](https://github.com/minio/minio-js/blob/master/examples/list-incomplete-uploads.js) + +#### 完整示例 : 操作文件对象 +* [fput-object.mjs](https://github.com/minio/minio-js/blob/master/examples/fput-object.js) +* [fget-object.mjs](https://github.com/minio/minio-js/blob/master/examples/fget-object.mjs) + +#### 完整示例 : 操作对象 +* [put-object.js](https://github.com/minio/minio-js/blob/master/examples/put-object.js) +* [get-object.mjs](https://github.com/minio/minio-js/blob/master/examples/get-object.mjs) +* [copy-object.js](https://github.com/minio/minio-js/blob/master/examples/copy-object.js) +* [get-partialobject.mjs](https://github.com/minio/minio-js/blob/master/examples/get-partialobject.mjs) +* [remove-object.js](https://github.com/minio/minio-js/blob/master/examples/remove-object.js) +* [remove-incomplete-upload.js](https://github.com/minio/minio-js/blob/master/examples/remove-incomplete-upload.js) +* [stat-object.mjs](https://github.com/minio/minio-js/blob/master/examples/stat-object.mjs) + +#### 完整示例 : Presigned操作 +* [presigned-getobject.mjs](https://github.com/minio/minio-js/blob/master/examples/presigned-getobject.js) +* [presigned-putobject.mjs](https://github.com/minio/minio-js/blob/master/examples/presigned-putobject.js) +* [presigned-postpolicy.mjs](https://github.com/minio/minio-js/blob/master/examples/presigned-postpolicy.js) + +#### 完整示例 : 存储桶通知 +* [get-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/get-bucket-notification.js) +* [set-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/set-bucket-notification.js) +* [remove-all-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/remove-all-bucket-notification.js) +* [listen-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/minio/listen-bucket-notification.js) (MinIO Extension) + +#### 完整示例 : 存储桶策略 +* [get-bucket-policy.js](https://github.com/minio/minio-js/blob/master/examples/get-bucket-policy.js) +* [set-bucket-policy.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-policy.mjs) + +## 了解更多 +* [完整文档]([https://docs.min.i](https://min.io/docs/minio/kubernetes/upstream/index.html)o) +* [MinIO JavaScript Client SDK API文档](https://min.io/docs/minio/linux/developers/javascript/API.html) +* [创建属于你的购物APP-完整示例](https://github.com/minio/minio-js-store-app) + +## 贡献 + +[贡献者指南](https://github.com/minio/minio-js/blob/master/CONTRIBUTING.md) + +[![Build Status](https://travis-ci.org/minio/minio-js.svg)](https://travis-ci.org/minio/minio-js) +[![Build status](https://ci.appveyor.com/api/projects/status/1d05e6nvxcelmrak?svg=true)](https://ci.appveyor.com/project/harshavardhana/minio-js) diff --git a/node_modules/minio/dist/esm/AssumeRoleProvider.d.mts b/node_modules/minio/dist/esm/AssumeRoleProvider.d.mts new file mode 100644 index 0000000..2dc0684 --- /dev/null +++ b/node_modules/minio/dist/esm/AssumeRoleProvider.d.mts @@ -0,0 +1,86 @@ +/// +import * as http from 'node:http'; +import { CredentialProvider } from "./CredentialProvider.mjs"; +import { Credentials } from "./Credentials.mjs"; +/** + * @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html + */ +type CredentialResponse = { + ErrorResponse?: { + Error?: { + Code?: string; + Message?: string; + }; + }; + AssumeRoleResponse: { + AssumeRoleResult: { + Credentials: { + AccessKeyId: string; + SecretAccessKey: string; + SessionToken: string; + Expiration: string; + }; + }; + }; +}; +export interface AssumeRoleProviderOptions { + stsEndpoint: string; + accessKey: string; + secretKey: string; + durationSeconds?: number; + sessionToken?: string; + policy?: string; + region?: string; + roleArn?: string; + roleSessionName?: string; + externalId?: string; + token?: string; + webIdentityToken?: string; + action?: string; + transportAgent?: http.Agent; +} +export declare class AssumeRoleProvider extends CredentialProvider { + private readonly stsEndpoint; + private readonly accessKey; + private readonly secretKey; + private readonly durationSeconds; + private readonly policy?; + private readonly region; + private readonly roleArn?; + private readonly roleSessionName?; + private readonly externalId?; + private readonly token?; + private readonly webIdentityToken?; + private readonly action; + private _credentials; + private readonly expirySeconds; + private accessExpiresAt; + private readonly transportAgent?; + private readonly transport; + constructor({ + stsEndpoint, + accessKey, + secretKey, + durationSeconds, + sessionToken, + policy, + region, + roleArn, + roleSessionName, + externalId, + token, + webIdentityToken, + action, + transportAgent + }: AssumeRoleProviderOptions); + getRequestConfig(): { + requestOptions: http.RequestOptions; + requestData: string; + }; + performRequest(): Promise; + parseCredentials(respObj: CredentialResponse): Credentials; + refreshCredentials(): Promise; + getCredentials(): Promise; + isAboutToExpire(): boolean; +} +export default AssumeRoleProvider; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/AssumeRoleProvider.mjs b/node_modules/minio/dist/esm/AssumeRoleProvider.mjs new file mode 100644 index 0000000..b017b40 --- /dev/null +++ b/node_modules/minio/dist/esm/AssumeRoleProvider.mjs @@ -0,0 +1,183 @@ +import * as http from "http"; +import * as https from "https"; +import { URL, URLSearchParams } from "url"; +import { CredentialProvider } from "./CredentialProvider.mjs"; +import { Credentials } from "./Credentials.mjs"; +import { makeDateLong, parseXml, toSha256 } from "./internal/helper.mjs"; +import { request } from "./internal/request.mjs"; +import { readAsString } from "./internal/response.mjs"; +import { signV4ByServiceName } from "./signing.mjs"; + +/** + * @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html + */ + +const defaultExpirySeconds = 900; +export class AssumeRoleProvider extends CredentialProvider { + accessExpiresAt = ''; + constructor({ + stsEndpoint, + accessKey, + secretKey, + durationSeconds = defaultExpirySeconds, + sessionToken, + policy, + region = '', + roleArn, + roleSessionName, + externalId, + token, + webIdentityToken, + action = 'AssumeRole', + transportAgent = undefined + }) { + super({ + accessKey, + secretKey, + sessionToken + }); + this.stsEndpoint = new URL(stsEndpoint); + this.accessKey = accessKey; + this.secretKey = secretKey; + this.policy = policy; + this.region = region; + this.roleArn = roleArn; + this.roleSessionName = roleSessionName; + this.externalId = externalId; + this.token = token; + this.webIdentityToken = webIdentityToken; + this.action = action; + this.durationSeconds = parseInt(durationSeconds); + let expirySeconds = this.durationSeconds; + if (this.durationSeconds < defaultExpirySeconds) { + expirySeconds = defaultExpirySeconds; + } + this.expirySeconds = expirySeconds; // for calculating refresh of credentials. + + // By default, nodejs uses a global agent if the 'agent' property + // is set to undefined. Otherwise, it's okay to assume the users + // know what they're doing if they specify a custom transport agent. + this.transportAgent = transportAgent; + const isHttp = this.stsEndpoint.protocol === 'http:'; + this.transport = isHttp ? http : https; + + /** + * Internal Tracking variables + */ + this._credentials = null; + } + getRequestConfig() { + const hostValue = this.stsEndpoint.hostname; + const portValue = this.stsEndpoint.port; + const qryParams = new URLSearchParams({ + Action: this.action, + Version: '2011-06-15' + }); + qryParams.set('DurationSeconds', this.expirySeconds.toString()); + if (this.policy) { + qryParams.set('Policy', this.policy); + } + if (this.roleArn) { + qryParams.set('RoleArn', this.roleArn); + } + if (this.roleSessionName != null) { + qryParams.set('RoleSessionName', this.roleSessionName); + } + if (this.token != null) { + qryParams.set('Token', this.token); + } + if (this.webIdentityToken) { + qryParams.set('WebIdentityToken', this.webIdentityToken); + } + if (this.externalId) { + qryParams.set('ExternalId', this.externalId); + } + const urlParams = qryParams.toString(); + const contentSha256 = toSha256(urlParams); + const date = new Date(); + const requestOptions = { + hostname: hostValue, + port: portValue, + path: '/', + protocol: this.stsEndpoint.protocol, + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'content-length': urlParams.length.toString(), + host: hostValue, + 'x-amz-date': makeDateLong(date), + 'x-amz-content-sha256': contentSha256 + }, + agent: this.transportAgent + }; + requestOptions.headers.authorization = signV4ByServiceName(requestOptions, this.accessKey, this.secretKey, this.region, date, contentSha256, 'sts'); + return { + requestOptions, + requestData: urlParams + }; + } + async performRequest() { + const { + requestOptions, + requestData + } = this.getRequestConfig(); + const res = await request(this.transport, requestOptions, requestData); + const body = await readAsString(res); + return parseXml(body); + } + parseCredentials(respObj) { + if (respObj.ErrorResponse) { + var _respObj$ErrorRespons, _respObj$ErrorRespons2, _respObj$ErrorRespons3, _respObj$ErrorRespons4; + throw new Error(`Unable to obtain credentials: ${(_respObj$ErrorRespons = respObj.ErrorResponse) === null || _respObj$ErrorRespons === void 0 ? void 0 : (_respObj$ErrorRespons2 = _respObj$ErrorRespons.Error) === null || _respObj$ErrorRespons2 === void 0 ? void 0 : _respObj$ErrorRespons2.Code} ${(_respObj$ErrorRespons3 = respObj.ErrorResponse) === null || _respObj$ErrorRespons3 === void 0 ? void 0 : (_respObj$ErrorRespons4 = _respObj$ErrorRespons3.Error) === null || _respObj$ErrorRespons4 === void 0 ? void 0 : _respObj$ErrorRespons4.Message}`, { + cause: respObj + }); + } + const { + AssumeRoleResponse: { + AssumeRoleResult: { + Credentials: { + AccessKeyId: accessKey, + SecretAccessKey: secretKey, + SessionToken: sessionToken, + Expiration: expiresAt + } + } + } + } = respObj; + this.accessExpiresAt = expiresAt; + return new Credentials({ + accessKey, + secretKey, + sessionToken + }); + } + async refreshCredentials() { + try { + const assumeRoleCredentials = await this.performRequest(); + this._credentials = this.parseCredentials(assumeRoleCredentials); + } catch (err) { + throw new Error(`Failed to get Credentials: ${err}`, { + cause: err + }); + } + return this._credentials; + } + async getCredentials() { + if (this._credentials && !this.isAboutToExpire()) { + return this._credentials; + } + this._credentials = await this.refreshCredentials(); + return this._credentials; + } + isAboutToExpire() { + const expiresAt = new Date(this.accessExpiresAt); + const provisionalExpiry = new Date(Date.now() + 1000 * 10); // check before 10 seconds. + return provisionalExpiry > expiresAt; + } +} + +// deprecated default export, please use named exports. +// keep for backward compatibility. +// eslint-disable-next-line import/no-default-export +export default AssumeRoleProvider; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJodHRwIiwiaHR0cHMiLCJVUkwiLCJVUkxTZWFyY2hQYXJhbXMiLCJDcmVkZW50aWFsUHJvdmlkZXIiLCJDcmVkZW50aWFscyIsIm1ha2VEYXRlTG9uZyIsInBhcnNlWG1sIiwidG9TaGEyNTYiLCJyZXF1ZXN0IiwicmVhZEFzU3RyaW5nIiwic2lnblY0QnlTZXJ2aWNlTmFtZSIsImRlZmF1bHRFeHBpcnlTZWNvbmRzIiwiQXNzdW1lUm9sZVByb3ZpZGVyIiwiYWNjZXNzRXhwaXJlc0F0IiwiY29uc3RydWN0b3IiLCJzdHNFbmRwb2ludCIsImFjY2Vzc0tleSIsInNlY3JldEtleSIsImR1cmF0aW9uU2Vjb25kcyIsInNlc3Npb25Ub2tlbiIsInBvbGljeSIsInJlZ2lvbiIsInJvbGVBcm4iLCJy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tJQUVBLE9BQU8sSUFBSSxDQUFDL0MsWUFBWTtFQUMxQjtFQUVBLE1BQU1nRCxjQUFjQSxDQUFBLEVBQXlCO0lBQzNDLElBQUksSUFBSSxDQUFDaEQsWUFBWSxJQUFJLENBQUMsSUFBSSxDQUFDaUQsZUFBZSxDQUFDLENBQUMsRUFBRTtNQUNoRCxPQUFPLElBQUksQ0FBQ2pELFlBQVk7SUFDMUI7SUFFQSxJQUFJLENBQUNBLFlBQVksR0FBRyxNQUFNLElBQUksQ0FBQzZDLGtCQUFrQixDQUFDLENBQUM7SUFDbkQsT0FBTyxJQUFJLENBQUM3QyxZQUFZO0VBQzFCO0VBRUFpRCxlQUFlQSxDQUFBLEVBQUc7SUFDaEIsTUFBTUwsU0FBUyxHQUFHLElBQUk5QixJQUFJLENBQUMsSUFBSSxDQUFDcEMsZUFBZSxDQUFDO0lBQ2hELE1BQU13RSxpQkFBaUIsR0FBRyxJQUFJcEMsSUFBSSxDQUFDQSxJQUFJLENBQUNxQyxHQUFHLENBQUMsQ0FBQyxHQUFHLElBQUksR0FBRyxFQUFFLENBQUMsRUFBQztJQUMzRCxPQUFPRCxpQkFBaUIsR0FBR04sU0FBUztFQUN0QztBQUNGOztBQUVBO0FBQ0E7QUFDQTtBQUNBLGVBQWVuRSxrQkFBa0IifQ== \ No newline at end of file diff --git a/node_modules/minio/dist/esm/CredentialProvider.d.mts b/node_modules/minio/dist/esm/CredentialProvider.d.mts new file mode 100644 index 0000000..e78ff7c --- /dev/null +++ b/node_modules/minio/dist/esm/CredentialProvider.d.mts @@ -0,0 +1,22 @@ +import { Credentials } from "./Credentials.mjs"; +export declare class CredentialProvider { + private credentials; + constructor({ + accessKey, + secretKey, + sessionToken + }: { + accessKey: string; + secretKey: string; + sessionToken?: string; + }); + getCredentials(): Promise; + setCredentials(credentials: Credentials): void; + setAccessKey(accessKey: string): void; + getAccessKey(): string; + setSecretKey(secretKey: string): void; + getSecretKey(): string; + setSessionToken(sessionToken: string): void; + getSessionToken(): string | undefined; +} +export default CredentialProvider; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/CredentialProvider.mjs b/node_modules/minio/dist/esm/CredentialProvider.mjs new file mode 100644 index 0000000..4fea541 --- /dev/null +++ b/node_modules/minio/dist/esm/CredentialProvider.mjs @@ -0,0 +1,48 @@ +import { Credentials } from "./Credentials.mjs"; +export class CredentialProvider { + constructor({ + accessKey, + secretKey, + sessionToken + }) { + this.credentials = new Credentials({ + accessKey, + secretKey, + sessionToken + }); + } + async getCredentials() { + return this.credentials.get(); + } + setCredentials(credentials) { + if (credentials instanceof Credentials) { + this.credentials = credentials; + } else { + throw new Error('Unable to set Credentials. it should be an instance of Credentials class'); + } + } + setAccessKey(accessKey) { + this.credentials.setAccessKey(accessKey); + } + getAccessKey() { + return this.credentials.getAccessKey(); + } + setSecretKey(secretKey) { + this.credentials.setSecretKey(secretKey); + } + getSecretKey() { + return this.credentials.getSecretKey(); + } + setSessionToken(sessionToken) { + this.credentials.setSessionToken(sessionToken); + } + getSessionToken() { + return this.credentials.getSessionToken(); + } +} + +// deprecated default export, please use named exports. +// keep for backward compatibility. +// eslint-disable-next-line import/no-default-export +export default CredentialProvider; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDcmVkZW50aWFscyIsIkNyZWRlbnRpYWxQcm92aWRlciIsImNvbnN0cnVjdG9yIiwiYWNjZXNzS2V5Iiwic2VjcmV0S2V5Iiwic2Vzc2lvblRva2VuIiwiY3JlZGVudGlhbHMiLCJnZXRDcmVkZW50aWFscyIsImdldCIsInNldENyZWRlbnRpYWxzIiwiRXJyb3IiLCJzZXRBY2Nlc3NLZXkiLCJnZXRBY2Nlc3NLZXkiLCJzZXRTZWNyZXRLZXkiLCJnZXRTZWNyZXRLZXkiLCJzZXRTZXNzaW9uVG9rZW4iLCJnZXRTZXNzaW9uVG9rZW4iXSwic291cmNlcyI6WyJDcmVkZW50aWFsUHJvdmlkZXIudHMiX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GVBQWVmLGtCQUFrQiJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/esm/Credentials.d.mts b/node_modules/minio/dist/esm/Credentials.d.mts new file mode 100644 index 0000000..9e8eb51 --- /dev/null +++ b/node_modules/minio/dist/esm/Credentials.d.mts @@ -0,0 +1,22 @@ +export declare class Credentials { + accessKey: string; + secretKey: string; + sessionToken?: string; + constructor({ + accessKey, + secretKey, + sessionToken + }: { + accessKey: string; + secretKey: string; + sessionToken?: string; + }); + setAccessKey(accessKey: string): void; + getAccessKey(): string; + setSecretKey(secretKey: string): void; + getSecretKey(): string; + setSessionToken(sessionToken: string): void; + getSessionToken(): string | undefined; + get(): Credentials; +} +export default Credentials; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/Credentials.mjs b/node_modules/minio/dist/esm/Credentials.mjs new file mode 100644 index 0000000..fa0f79f --- /dev/null +++ b/node_modules/minio/dist/esm/Credentials.mjs @@ -0,0 +1,38 @@ +export class Credentials { + constructor({ + accessKey, + secretKey, + sessionToken + }) { + this.accessKey = accessKey; + this.secretKey = secretKey; + this.sessionToken = sessionToken; + } + setAccessKey(accessKey) { + this.accessKey = accessKey; + } + getAccessKey() { + return this.accessKey; + } + setSecretKey(secretKey) { + this.secretKey = secretKey; + } + getSecretKey() { + return this.secretKey; + } + setSessionToken(sessionToken) { + this.sessionToken = sessionToken; + } + getSessionToken() { + return this.sessionToken; + } + get() { + return this; + } +} + +// deprecated default export, please use named exports. +// keep for backward compatibility. +// eslint-disable-next-line import/no-default-export +export default Credentials; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDcmVkZW50aWFscyIsImNvbnN0cnVjdG9yIiwiYWNjZXNzS2V5Iiwic2VjcmV0S2V5Iiwic2Vzc2lvblRva2VuIiwic2V0QWNjZXNzS2V5IiwiZ2V0QWNjZXNzS2V5Iiwic2V0U2VjcmV0S2V5IiwiZ2V0U2VjcmV0S2V5Iiwic2V0U2Vzc2l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O0VBRUFNLGVBQWVBLENBQUEsRUFBRztJQUNoQixPQUFPLElBQUksQ0FBQ04sWUFBWTtFQUMxQjtFQUVBTyxHQUFHQSxDQUFBLEVBQWdCO0lBQ2pCLE9BQU8sSUFBSTtFQUNiO0FBQ0Y7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsZUFBZVgsV0FBVyJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/esm/IamAwsProvider.d.mts b/node_modules/minio/dist/esm/IamAwsProvider.d.mts new file mode 100644 index 0000000..ba164ea --- /dev/null +++ b/node_modules/minio/dist/esm/IamAwsProvider.d.mts @@ -0,0 +1,27 @@ +/// +import * as http from 'node:http'; +import { CredentialProvider } from "./CredentialProvider.mjs"; +import { Credentials } from "./Credentials.mjs"; +export interface IamAwsProviderOptions { + customEndpoint?: string; + transportAgent?: http.Agent; +} +export declare class IamAwsProvider extends CredentialProvider { + private readonly customEndpoint?; + private _credentials; + private readonly transportAgent?; + private accessExpiresAt; + constructor({ + customEndpoint, + transportAgent + }: IamAwsProviderOptions); + getCredentials(): Promise; + private fetchCredentials; + private fetchCredentialsUsingTokenFile; + private fetchImdsToken; + private getIamRoleNamedUrl; + private getIamRoleName; + private requestCredentials; + private isAboutToExpire; +} +export default IamAwsProvider; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/IamAwsProvider.mjs b/node_modules/minio/dist/esm/IamAwsProvider.mjs new file mode 100644 index 0000000..e63d644 --- /dev/null +++ b/node_modules/minio/dist/esm/IamAwsProvider.mjs @@ -0,0 +1,189 @@ +import * as fs from "fs/promises"; +import * as http from "http"; +import * as https from "https"; +import { URL, URLSearchParams } from "url"; +import { CredentialProvider } from "./CredentialProvider.mjs"; +import { Credentials } from "./Credentials.mjs"; +import { parseXml } from "./internal/helper.mjs"; +import { request } from "./internal/request.mjs"; +import { readAsString } from "./internal/response.mjs"; +export class IamAwsProvider extends CredentialProvider { + accessExpiresAt = ''; + constructor({ + customEndpoint = undefined, + transportAgent = undefined + }) { + super({ + accessKey: '', + secretKey: '' + }); + this.customEndpoint = customEndpoint; + this.transportAgent = transportAgent; + + /** + * Internal Tracking variables + */ + this._credentials = null; + } + async getCredentials() { + if (!this._credentials || this.isAboutToExpire()) { + this._credentials = await this.fetchCredentials(); + } + return this._credentials; + } + async fetchCredentials() { + try { + // check for IRSA (https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) + const tokenFile = process.env.AWS_WEB_IDENTITY_TOKEN_FILE; + if (tokenFile) { + return await this.fetchCredentialsUsingTokenFile(tokenFile); + } + + // try with IAM role for EC2 instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) + let tokenHeader = 'Authorization'; + let token = process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN; + const relativeUri = process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI; + const fullUri = process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI; + let url; + if (relativeUri) { + url = new URL(relativeUri, 'http://169.254.170.2'); + } else if (fullUri) { + url = new URL(fullUri); + } else { + token = await this.fetchImdsToken(); + tokenHeader = 'X-aws-ec2-metadata-token'; + url = await this.getIamRoleNamedUrl(token); + } + return this.requestCredentials(url, tokenHeader, token); + } catch (err) { + throw new Error(`Failed to get Credentials: ${err}`, { + cause: err + }); + } + } + async fetchCredentialsUsingTokenFile(tokenFile) { + const token = await fs.readFile(tokenFile, { + encoding: 'utf8' + }); + const region = process.env.AWS_REGION; + const stsEndpoint = new URL(region ? `https://sts.${region}.amazonaws.com` : 'https://sts.amazonaws.com'); + const hostValue = stsEndpoint.hostname; + const portValue = stsEndpoint.port; + const qryParams = new URLSearchParams({ + Action: 'AssumeRoleWithWebIdentity', + Version: '2011-06-15' + }); + const roleArn = process.env.AWS_ROLE_ARN; + if (roleArn) { + qryParams.set('RoleArn', roleArn); + const roleSessionName = process.env.AWS_ROLE_SESSION_NAME; + qryParams.set('RoleSessionName', roleSessionName ? roleSessionName : Date.now().toString()); + } + qryParams.set('WebIdentityToken', token); + qryParams.sort(); + const requestOptions = { + hostname: hostValue, + port: portValue, + path: `${stsEndpoint.pathname}?${qryParams.toString()}`, + protocol: stsEndpoint.protocol, + method: 'POST', + headers: {}, + agent: this.transportAgent + }; + const transport = stsEndpoint.protocol === 'http:' ? http : https; + const res = await request(transport, requestOptions, null); + const body = await readAsString(res); + const assumeRoleResponse = parseXml(body); + const creds = assumeRoleResponse.AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult.Credentials; + this.accessExpiresAt = creds.Expiration; + return new Credentials({ + accessKey: creds.AccessKeyId, + secretKey: creds.SecretAccessKey, + sessionToken: creds.SessionToken + }); + } + async fetchImdsToken() { + const endpoint = this.customEndpoint ? this.customEndpoint : 'http://169.254.169.254'; + const url = new URL('/latest/api/token', endpoint); + const requestOptions = { + hostname: url.hostname, + port: url.port, + path: `${url.pathname}${url.search}`, + protocol: url.protocol, + method: 'PUT', + headers: { + 'X-aws-ec2-metadata-token-ttl-seconds': '21600' + }, + agent: this.transportAgent + }; + const transport = url.protocol === 'http:' ? http : https; + const res = await request(transport, requestOptions, null); + return await readAsString(res); + } + async getIamRoleNamedUrl(token) { + const endpoint = this.customEndpoint ? this.customEndpoint : 'http://169.254.169.254'; + const url = new URL('latest/meta-data/iam/security-credentials/', endpoint); + const roleName = await this.getIamRoleName(url, token); + return new URL(`${url.pathname}/${encodeURIComponent(roleName)}`, url.origin); + } + async getIamRoleName(url, token) { + const requestOptions = { + hostname: url.hostname, + port: url.port, + path: `${url.pathname}${url.search}`, + protocol: url.protocol, + method: 'GET', + headers: { + 'X-aws-ec2-metadata-token': token + }, + agent: this.transportAgent + }; + const transport = url.protocol === 'http:' ? http : https; + const res = await request(transport, requestOptions, null); + const body = await readAsString(res); + const roleNames = body.split(/\r\n|[\n\r\u2028\u2029]/); + if (roleNames.length === 0) { + throw new Error(`No IAM roles attached to EC2 service ${url}`); + } + return roleNames[0]; + } + async requestCredentials(url, tokenHeader, token) { + const headers = {}; + if (token) { + headers[tokenHeader] = token; + } + const requestOptions = { + hostname: url.hostname, + port: url.port, + path: `${url.pathname}${url.search}`, + protocol: url.protocol, + method: 'GET', + headers: headers, + agent: this.transportAgent + }; + const transport = url.protocol === 'http:' ? http : https; + const res = await request(transport, requestOptions, null); + const body = await readAsString(res); + const ecsCredentials = JSON.parse(body); + if (!ecsCredentials.Code || ecsCredentials.Code != 'Success') { + throw new Error(`${url} failed with code ${ecsCredentials.Code} and message ${ecsCredentials.Message}`); + } + this.accessExpiresAt = ecsCredentials.Expiration; + return new Credentials({ + accessKey: ecsCredentials.AccessKeyID, + secretKey: ecsCredentials.SecretAccessKey, + sessionToken: ecsCredentials.Token + }); + } + isAboutToExpire() { + const expiresAt = new Date(this.accessExpiresAt); + const provisionalExpiry = new Date(Date.now() + 1000 * 10); // 10 seconds leeway + return provisionalExpiry > expiresAt; + } +} + +// deprecated default export, please use named exports. +// keep for backward compatibility. +// eslint-disable-next-line import/no-default-export +export default IamAwsProvider; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJmcyIsImh0dHAiLCJodHRwcyIsIlVSTCIsIlVSTFNlYXJjaFBhcmFtcyIsIkNyZWRlbnRpYWxQcm92aWRlciIsIkNyZWRlbnRpYWxzIiwicGFyc2VYbWwiLCJyZXF1ZXN0IiwicmVhZEFzU3RyaW5nIiwiSWFtQXdzUHJvdmlkZXIiLCJhY2Nlc3NFeHBpcmVzQXQiLCJjb25zdHJ1Y3RvciIsImN1c3RvbUVuZHBvaW50IiwidW5kZWZpbmVkIiwidHJhbnNwb3J0QWdlbnQiLCJhY2Nlc3NLZXkiLCJzZWNyZXRLZXkiLCJfY3JlZGVudGlhbHMiLCJnZXRDcmVkZW50aWFscyIsImlzQWJvdXRUb0V4cGlyZSIsImZldGNoQ3JlZGVudGlhbHMiLCJ0b2tlbkZpbGUiLCJwcm9jZXNzIiwiZW52IiwiQVdTX1dFQl9JREVOVElUWV9UT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FLGNBQWMsQ0FBQ2QsVUFBVTtJQUNoRCxPQUFPLElBQUl0RSxXQUFXLENBQUM7TUFDckJVLFNBQVMsRUFBRTBFLGNBQWMsQ0FBQ0ssV0FBVztNQUNyQzlFLFNBQVMsRUFBRXlFLGNBQWMsQ0FBQ1osZUFBZTtNQUN6Q0MsWUFBWSxFQUFFVyxjQUFjLENBQUNNO0lBQy9CLENBQUMsQ0FBQztFQUNKO0VBRVE1RSxlQUFlQSxDQUFBLEVBQUc7SUFDeEIsTUFBTTZFLFNBQVMsR0FBRyxJQUFJdkMsSUFBSSxDQUFDLElBQUksQ0FBQy9DLGVBQWUsQ0FBQztJQUNoRCxNQUFNdUYsaUJBQWlCLEdBQUcsSUFBSXhDLElBQUksQ0FBQ0EsSUFBSSxDQUFDQyxHQUFHLENBQUMsQ0FBQyxHQUFHLElBQUksR0FBRyxFQUFFLENBQUMsRUFBQztJQUMzRCxPQUFPdUMsaUJBQWlCLEdBQUdELFNBQVM7RUFDdEM7QUFDRjs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxlQUFldkYsY0FBYyJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/esm/errors.d.mts b/node_modules/minio/dist/esm/errors.d.mts new file mode 100644 index 0000000..aa14700 --- /dev/null +++ b/node_modules/minio/dist/esm/errors.d.mts @@ -0,0 +1,82 @@ +/// +declare class ExtendableError extends Error { + constructor(message?: string, opt?: ErrorOptions); +} +/** + * AnonymousRequestError is generated for anonymous keys on specific + * APIs. NOTE: PresignedURL generation always requires access keys. + */ +export declare class AnonymousRequestError extends ExtendableError {} +/** + * InvalidArgumentError is generated for all invalid arguments. + */ +export declare class InvalidArgumentError extends ExtendableError {} +/** + * InvalidPortError is generated when a non integer value is provided + * for ports. + */ +export declare class InvalidPortError extends ExtendableError {} +/** + * InvalidEndpointError is generated when an invalid end point value is + * provided which does not follow domain standards. + */ +export declare class InvalidEndpointError extends ExtendableError {} +/** + * InvalidBucketNameError is generated when an invalid bucket name is + * provided which does not follow AWS S3 specifications. + * http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html + */ +export declare class InvalidBucketNameError extends ExtendableError {} +/** + * InvalidObjectNameError is generated when an invalid object name is + * provided which does not follow AWS S3 specifications. + * http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html + */ +export declare class InvalidObjectNameError extends ExtendableError {} +/** + * AccessKeyRequiredError generated by signature methods when access + * key is not found. + */ +export declare class AccessKeyRequiredError extends ExtendableError {} +/** + * SecretKeyRequiredError generated by signature methods when secret + * key is not found. + */ +export declare class SecretKeyRequiredError extends ExtendableError {} +/** + * ExpiresParamError generated when expires parameter value is not + * well within stipulated limits. + */ +export declare class ExpiresParamError extends ExtendableError {} +/** + * InvalidDateError generated when invalid date is found. + */ +export declare class InvalidDateError extends ExtendableError {} +/** + * InvalidPrefixError generated when object prefix provided is invalid + * or does not conform to AWS S3 object key restrictions. + */ +export declare class InvalidPrefixError extends ExtendableError {} +/** + * InvalidBucketPolicyError generated when the given bucket policy is invalid. + */ +export declare class InvalidBucketPolicyError extends ExtendableError {} +/** + * IncorrectSizeError generated when total data read mismatches with + * the input size. + */ +export declare class IncorrectSizeError extends ExtendableError {} +/** + * InvalidXMLError generated when an unknown XML is found. + */ +export declare class InvalidXMLError extends ExtendableError {} +/** + * S3Error is generated for errors returned from S3 server. + * see getErrorTransformer for details + */ +export declare class S3Error extends ExtendableError { + code?: string; + region?: string; +} +export declare class IsValidBucketNameError extends ExtendableError {} +export {}; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/errors.mjs b/node_modules/minio/dist/esm/errors.mjs new file mode 100644 index 0000000..2357c8d --- /dev/null +++ b/node_modules/minio/dist/esm/errors.mjs @@ -0,0 +1,117 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// + +class ExtendableError extends Error { + constructor(message, opt) { + // error Option {cause?: unknown} is a 'nice to have', + // don't use it internally + super(message, opt); + // set error name, otherwise it's always 'Error' + this.name = this.constructor.name; + } +} + +/** + * AnonymousRequestError is generated for anonymous keys on specific + * APIs. NOTE: PresignedURL generation always requires access keys. + */ +export class AnonymousRequestError extends ExtendableError {} + +/** + * InvalidArgumentError is generated for all invalid arguments. + */ +export class InvalidArgumentError extends ExtendableError {} + +/** + * InvalidPortError is generated when a non integer value is provided + * for ports. + */ +export class InvalidPortError extends ExtendableError {} + +/** + * InvalidEndpointError is generated when an invalid end point value is + * provided which does not follow domain standards. + */ +export class InvalidEndpointError extends ExtendableError {} + +/** + * InvalidBucketNameError is generated when an invalid bucket name is + * provided which does not follow AWS S3 specifications. + * http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html + */ +export class InvalidBucketNameError extends ExtendableError {} + +/** + * InvalidObjectNameError is generated when an invalid object name is + * provided which does not follow AWS S3 specifications. + * http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html + */ +export class InvalidObjectNameError extends ExtendableError {} + +/** + * AccessKeyRequiredError generated by signature methods when access + * key is not found. + */ +export class AccessKeyRequiredError extends ExtendableError {} + +/** + * SecretKeyRequiredError generated by signature methods when secret + * key is not found. + */ +export class SecretKeyRequiredError extends ExtendableError {} + +/** + * ExpiresParamError generated when expires parameter value is not + * well within stipulated limits. + */ +export class ExpiresParamError extends ExtendableError {} + +/** + * InvalidDateError generated when invalid date is found. + */ +export class InvalidDateError extends ExtendableError {} + +/** + * InvalidPrefixError generated when object prefix provided is invalid + * or does not conform to AWS S3 object key restrictions. + */ +export class InvalidPrefixError extends ExtendableError {} + +/** + * InvalidBucketPolicyError generated when the given bucket policy is invalid. + */ +export class InvalidBucketPolicyError extends ExtendableError {} + +/** + * IncorrectSizeError generated when total data read mismatches with + * the input size. + */ +export class IncorrectSizeError extends ExtendableError {} + +/** + * InvalidXMLError generated when an unknown XML is found. + */ +export class InvalidXMLError extends ExtendableError {} + +/** + * S3Error is generated for errors returned from S3 server. + * see getErrorTransformer for details + */ +export class S3Error extends ExtendableError {} +export class IsValidBucketNameError extends ExtendableError {} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJFeHRlbmRhYmxlRXJyb3IiLCJFcnJvciIsImNvbnN0cnVjdG9yIiwibWVzc2FnZSIsIm9wdCIsIm5hbWUiLCJBbm9ueW1vdXNSZXF1ZXN0RXJyb3IiLCJJbnZhbGlkQXJndW1lbnRFcnJvciIsIkludmFsaWRQb3J0RXJyb3IiLCJJbnZhbGlkRW5kcG9pbnRFcnJvciIsIkludmFsaWRCdWNrZXROYW1lRXJyb3IiLCJJbnZhbGlkT2JqZWN0TmFtZUVycm9yIiwiQWNjZXNzS2V5UmVxdWlyZWRFcnJvciIsIlNlY3JldEtleVJlcXVpcmVkRXJyb3IiLCJFeHBpcmVzUGFyYW1FcnJvciIsIkludmFsaWREYXRlRXJyb3IiLCJJbnZhbGlkUHJlZml4RXJyb3IiLCJJbnZhbGlkQnVja2V0UG9saWN5RXJyb3IiLCJJbmNvcnJlY3RTaXplRXJyb3IiLCJJbnZhbGlkWE1MRXJyb3IiLCJTM0Vycm9yIiwiSXNWYWxpZEJ1Y2tldE5hbWVFcnJvciJdLCJzb3VyY2VzIjpbImVycm9ycy50cyJdLCJzb3VyY2VzQ29udGVudCI6WyIvKlxuICogTWluSU8gSmF2YXNjcmlwdCBMaWJyYXJ5IGZvciBBbWF6b24gUzMgQ29tcGF0aWJsZSBDbG91ZCBTdG9yYWdlLCAoQykgMjAxNSBNaW5JTywgSW5jLlxuICpcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBBcGFjaG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UNBO0FBQ0E7QUFDQSxPQUFPLE1BQU1rQixrQkFBa0IsU0FBU2xCLGVBQWUsQ0FBQzs7QUFFeEQ7QUFDQTtBQUNBO0FBQ0EsT0FBTyxNQUFNbUIsZUFBZSxTQUFTbkIsZUFBZSxDQUFDOztBQUVyRDtBQUNBO0FBQ0E7QUFDQTtBQUNBLE9BQU8sTUFBTW9CLE9BQU8sU0FBU3BCLGVBQWUsQ0FBQztBQUs3QyxPQUFPLE1BQU1xQixzQkFBc0IsU0FBU3JCLGVBQWUsQ0FBQyJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/esm/helpers.d.mts b/node_modules/minio/dist/esm/helpers.d.mts new file mode 100644 index 0000000..7921bf0 --- /dev/null +++ b/node_modules/minio/dist/esm/helpers.d.mts @@ -0,0 +1,156 @@ +import type { Encryption, ObjectMetaData, RequestHeaders } from "./internal/type.mjs"; +import { RETENTION_MODES } from "./internal/type.mjs"; +export { ENCRYPTION_TYPES, LEGAL_HOLD_STATUS, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from "./internal/type.mjs"; +export declare const DEFAULT_REGION = "us-east-1"; +export declare const PRESIGN_EXPIRY_DAYS_MAX: number; +export interface ICopySourceOptions { + Bucket: string; + Object: string; + /** + * Valid versionId + */ + VersionID?: string; + /** + * Etag to match + */ + MatchETag?: string; + /** + * Etag to exclude + */ + NoMatchETag?: string; + /** + * Modified Date of the object/part. UTC Date in string format + */ + MatchModifiedSince?: string | null; + /** + * Modified Date of the object/part to exclude UTC Date in string format + */ + MatchUnmodifiedSince?: string | null; + /** + * true or false Object range to match + */ + MatchRange?: boolean; + Start?: number; + End?: number; + Encryption?: Encryption; +} +export declare class CopySourceOptions { + readonly Bucket: string; + readonly Object: string; + readonly VersionID: string; + MatchETag: string; + private readonly NoMatchETag; + private readonly MatchModifiedSince; + private readonly MatchUnmodifiedSince; + readonly MatchRange: boolean; + readonly Start: number; + readonly End: number; + private readonly Encryption?; + constructor({ + Bucket, + Object, + VersionID, + MatchETag, + NoMatchETag, + MatchModifiedSince, + MatchUnmodifiedSince, + MatchRange, + Start, + End, + Encryption + }: ICopySourceOptions); + validate(): boolean; + getHeaders(): RequestHeaders; +} +/** + * @deprecated use nodejs fs module + */ +export declare function removeDirAndFiles(dirPath: string, removeSelf?: boolean): void; +export interface ICopyDestinationOptions { + /** + * Bucket name + */ + Bucket: string; + /** + * Object Name for the destination (composed/copied) object defaults + */ + Object: string; + /** + * Encryption configuration defaults to {} + * @default {} + */ + Encryption?: Encryption; + UserMetadata?: ObjectMetaData; + /** + * query-string encoded string or Record Object + */ + UserTags?: Record | string; + LegalHold?: 'on' | 'off'; + /** + * UTC Date String + */ + RetainUntilDate?: string; + Mode?: RETENTION_MODES; + MetadataDirective?: 'COPY' | 'REPLACE'; + /** + * Extra headers for the target object + */ + Headers?: Record; +} +export declare class CopyDestinationOptions { + readonly Bucket: string; + readonly Object: string; + private readonly Encryption?; + private readonly UserMetadata?; + private readonly UserTags?; + private readonly LegalHold?; + private readonly RetainUntilDate?; + private readonly Mode?; + private readonly MetadataDirective?; + private readonly Headers?; + constructor({ + Bucket, + Object, + Encryption, + UserMetadata, + UserTags, + LegalHold, + RetainUntilDate, + Mode, + MetadataDirective, + Headers + }: ICopyDestinationOptions); + getHeaders(): RequestHeaders; + validate(): boolean; +} +/** + * maybe this should be a generic type for Records, leave it for later refactor + */ +export declare class SelectResults { + private records?; + private response?; + private stats?; + private progress?; + constructor({ + records, + // parsed data as stream + response, + // original response stream + stats, + // stats as xml + progress + }: { + records?: unknown; + response?: unknown; + stats?: string; + progress?: unknown; + }); + setStats(stats: string): void; + getStats(): string | undefined; + setProgress(progress: unknown): void; + getProgress(): unknown; + setResponse(response: unknown): void; + getResponse(): unknown; + setRecords(records: unknown): void; + getRecords(): unknown; +} \ No newline at end of file diff --git a/node_modules/minio/dist/esm/helpers.mjs b/node_modules/minio/dist/esm/helpers.mjs new file mode 100644 index 0000000..edac39c --- /dev/null +++ b/node_modules/minio/dist/esm/helpers.mjs @@ -0,0 +1,218 @@ +import * as fs from "fs"; +import * as path from "path"; +import * as querystring from 'query-string'; +import * as errors from "./errors.mjs"; +import { getEncryptionHeaders, isEmpty, isEmptyObject, isNumber, isObject, isString, isValidBucketName, isValidObjectName } from "./internal/helper.mjs"; +import { RETENTION_MODES } from "./internal/type.mjs"; +export { ENCRYPTION_TYPES, LEGAL_HOLD_STATUS, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from "./internal/type.mjs"; +export const DEFAULT_REGION = 'us-east-1'; +export const PRESIGN_EXPIRY_DAYS_MAX = 24 * 60 * 60 * 7; // 7 days in seconds + +export class CopySourceOptions { + constructor({ + Bucket, + Object, + VersionID = '', + MatchETag = '', + NoMatchETag = '', + MatchModifiedSince = null, + MatchUnmodifiedSince = null, + MatchRange = false, + Start = 0, + End = 0, + Encryption = undefined + }) { + this.Bucket = Bucket; + this.Object = Object; + this.VersionID = VersionID; + this.MatchETag = MatchETag; + this.NoMatchETag = NoMatchETag; + this.MatchModifiedSince = MatchModifiedSince; + this.MatchUnmodifiedSince = MatchUnmodifiedSince; + this.MatchRange = MatchRange; + this.Start = Start; + this.End = End; + this.Encryption = Encryption; + } + validate() { + if (!isValidBucketName(this.Bucket)) { + throw new errors.InvalidBucketNameError('Invalid Source bucket name: ' + this.Bucket); + } + if (!isValidObjectName(this.Object)) { + throw new errors.InvalidObjectNameError(`Invalid Source object name: ${this.Object}`); + } + if (this.MatchRange && this.Start !== -1 && this.End !== -1 && this.Start > this.End || this.Start < 0) { + throw new errors.InvalidObjectNameError('Source start must be non-negative, and start must be at most end.'); + } else if (this.MatchRange && !isNumber(this.Start) || !isNumber(this.End)) { + throw new errors.InvalidObjectNameError('MatchRange is specified. But Invalid Start and End values are specified.'); + } + return true; + } + getHeaders() { + const headerOptions = {}; + headerOptions['x-amz-copy-source'] = encodeURI(this.Bucket + '/' + this.Object); + if (!isEmpty(this.VersionID)) { + headerOptions['x-amz-copy-source'] = `${encodeURI(this.Bucket + '/' + this.Object)}?versionId=${this.VersionID}`; + } + if (!isEmpty(this.MatchETag)) { + headerOptions['x-amz-copy-source-if-match'] = this.MatchETag; + } + if (!isEmpty(this.NoMatchETag)) { + headerOptions['x-amz-copy-source-if-none-match'] = this.NoMatchETag; + } + if (!isEmpty(this.MatchModifiedSince)) { + headerOptions['x-amz-copy-source-if-modified-since'] = this.MatchModifiedSince; + } + if (!isEmpty(this.MatchUnmodifiedSince)) { + headerOptions['x-amz-copy-source-if-unmodified-since'] = this.MatchUnmodifiedSince; + } + return headerOptions; + } +} + +/** + * @deprecated use nodejs fs module + */ +export function removeDirAndFiles(dirPath, removeSelf = true) { + if (removeSelf) { + return fs.rmSync(dirPath, { + recursive: true, + force: true + }); + } + fs.readdirSync(dirPath).forEach(item => { + fs.rmSync(path.join(dirPath, item), { + recursive: true, + force: true + }); + }); +} +export class CopyDestinationOptions { + constructor({ + Bucket, + Object, + Encryption, + UserMetadata, + UserTags, + LegalHold, + RetainUntilDate, + Mode, + MetadataDirective, + Headers + }) { + this.Bucket = Bucket; + this.Object = Object; + this.Encryption = Encryption ?? undefined; // null input will become undefined, easy for runtime assert + this.UserMetadata = UserMetadata; + this.UserTags = UserTags; + this.LegalHold = LegalHold; + this.Mode = Mode; // retention mode + this.RetainUntilDate = RetainUntilDate; + this.MetadataDirective = MetadataDirective; + this.Headers = Headers; + } + getHeaders() { + const replaceDirective = 'REPLACE'; + const headerOptions = {}; + const userTags = this.UserTags; + if (!isEmpty(userTags)) { + headerOptions['X-Amz-Tagging-Directive'] = replaceDirective; + headerOptions['X-Amz-Tagging'] = isObject(userTags) ? querystring.stringify(userTags) : isString(userTags) ? userTags : ''; + } + if (this.Mode) { + headerOptions['X-Amz-Object-Lock-Mode'] = this.Mode; // GOVERNANCE or COMPLIANCE + } + + if (this.RetainUntilDate) { + headerOptions['X-Amz-Object-Lock-Retain-Until-Date'] = this.RetainUntilDate; // needs to be UTC. + } + + if (this.LegalHold) { + headerOptions['X-Amz-Object-Lock-Legal-Hold'] = this.LegalHold; // ON or OFF + } + + if (this.UserMetadata) { + for (const [key, value] of Object.entries(this.UserMetadata)) { + headerOptions[`X-Amz-Meta-${key}`] = value.toString(); + } + } + if (this.MetadataDirective) { + headerOptions[`X-Amz-Metadata-Directive`] = this.MetadataDirective; + } + if (this.Encryption) { + const encryptionHeaders = getEncryptionHeaders(this.Encryption); + for (const [key, value] of Object.entries(encryptionHeaders)) { + headerOptions[key] = value; + } + } + if (this.Headers) { + for (const [key, value] of Object.entries(this.Headers)) { + headerOptions[key] = value; + } + } + return headerOptions; + } + validate() { + if (!isValidBucketName(this.Bucket)) { + throw new errors.InvalidBucketNameError('Invalid Destination bucket name: ' + this.Bucket); + } + if (!isValidObjectName(this.Object)) { + throw new errors.InvalidObjectNameError(`Invalid Destination object name: ${this.Object}`); + } + if (!isEmpty(this.UserMetadata) && !isObject(this.UserMetadata)) { + throw new errors.InvalidObjectNameError(`Destination UserMetadata should be an object with key value pairs`); + } + if (!isEmpty(this.Mode) && ![RETENTION_MODES.GOVERNANCE, RETENTION_MODES.COMPLIANCE].includes(this.Mode)) { + throw new errors.InvalidObjectNameError(`Invalid Mode specified for destination object it should be one of [GOVERNANCE,COMPLIANCE]`); + } + if (this.Encryption !== undefined && isEmptyObject(this.Encryption)) { + throw new errors.InvalidObjectNameError(`Invalid Encryption configuration for destination object `); + } + return true; + } +} + +/** + * maybe this should be a generic type for Records, leave it for later refactor + */ +export class SelectResults { + constructor({ + records, + // parsed data as stream + response, + // original response stream + stats, + // stats as xml + progress // stats as xml + }) { + this.records = records; + this.response = response; + this.stats = stats; + this.progress = progress; + } + setStats(stats) { + this.stats = stats; + } + getStats() { + return this.stats; + } + setProgress(progress) { + this.progress = progress; + } + getProgress() { + return this.progress; + } + setResponse(response) { + this.response = response; + } + getResponse() { + return this.response; + } + setRecords(records) { + this.records = records; + } + getRecords() { + return this.records; + } +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJ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QUFRO0VBQ3RCO0VBRUFTLFVBQVVBLENBQUNWLE9BQWdCLEVBQUU7SUFDM0IsSUFBSSxDQUFDQSxPQUFPLEdBQUdBLE9BQU87RUFDeEI7RUFFQVcsVUFBVUEsQ0FBQSxFQUFZO0lBQ3BCLE9BQU8sSUFBSSxDQUFDWCxPQUFPO0VBQ3JCO0FBQ0YifQ== \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/async.d.mts b/node_modules/minio/dist/esm/internal/async.d.mts new file mode 100644 index 0000000..3a2e548 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/async.d.mts @@ -0,0 +1,9 @@ +/// +/// +import * as fs from 'node:fs'; +import * as stream from 'node:stream'; +export { promises as fsp } from 'node:fs'; +export declare const streamPromise: { + pipeline: typeof stream.pipeline.__promisify__; +}; +export declare const fstat: typeof fs.fstat.__promisify__; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/async.mjs b/node_modules/minio/dist/esm/internal/async.mjs new file mode 100644 index 0000000..668429a --- /dev/null +++ b/node_modules/minio/dist/esm/internal/async.mjs @@ -0,0 +1,14 @@ +// promise helper for stdlib + +import * as fs from "fs"; +import * as stream from "stream"; +import { promisify } from "util"; + +// TODO: use "node:fs/promise" directly after we stop testing on nodejs 12 +export { promises as fsp } from 'node:fs'; +export const streamPromise = { + // node:stream/promises Added in: v15.0.0 + pipeline: promisify(stream.pipeline) +}; +export const fstat = promisify(fs.fstat); +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJmcyIsInN0cmVhbSIsInByb21pc2lmeSIsInByb21pc2VzIiwiZnNwIiwic3RyZWFtUHJvbWlzZSIsInBpcGVsaW5lIiwiZnN0YXQiXSwic291cmNlcyI6WyJhc3luYy50cyJdLCJzb3VyY2VzQ29udGVudCI6WyIvLyBwcm9taXNlIGhlbHBlciBmb3Igc3RkbGliXG5cbmltcG9ydCAqIGFzIGZzIGZyb20gJ25vZGU6ZnMnXG5pbXBvcnQgKiBhcyBzdHJlYW0gZnJvbSAnbm9kZTpzdHJlYW0nXG5pbXBvcnQgeyBwcm9taXNpZnkgfSBmcm9tICdub2RlOnV0aWwnXG5cbi8vIFRPRE86IHVzZSBcIm5vZGU6ZnMvcHJvbWlzZVwiIGRpcmVjdGx5IGFmdGVyIHdlIHN0b3AgdGVzdGluZyBvbiBub2RlanMgMTJcbmV4cG9ydCB7IHByb21pc2VzIGFzIGZzcCB9IGZyb20gJ25vZGU6ZnMnXG5leHBvcnQgY29uc3Qgc3RyZWFtUHJvbWlzZSA9IHtcbiAgLy8gbm9kZTpzdHJlYW0vcHJvbWlzZXMgQWRkZWQgaW46IHYxNS4wLjBcbiAgcGlwZWxpbmU6IHByb21pc2lmeShzdHJlYW0ucGlwZWxpbmUpLFxufVxuXG5leHBvcnQgY29uc3QgZnN0YXQgPSBwcm9taXNpZnkoZnMuZnN0YXQpXG4iXSwibWFwcGluZ3MiOiJBQUFBOztBQUVBLE9BQU8sS0FBS0EsRUFBRTtBQUNkLE9BQU8sS0FBS0MsTUFBTTtBQUNsQixTQUFTQyxTQUFTOztBQUVsQjtBQUNBLFNBQVNDLFFBQVEsSUFBSUMsR0FBRyxRQUFRLFNBQVM7QUFDekMsT0FBTyxNQUFNQyxhQUFhLEdBQUc7RUFDM0I7RUFDQUMsUUFBUSxFQUFFSixTQUFTLENBQUNELE1BQU0sQ0FBQ0ssUUFBUTtBQUNyQyxDQUFDO0FBRUQsT0FBTyxNQUFNQyxLQUFLLEdBQUdMLFNBQVMsQ0FBQ0YsRUFBRSxDQUFDTyxLQUFLLENBQUMifQ== \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/callbackify.d.mts b/node_modules/minio/dist/esm/internal/callbackify.d.mts new file mode 100644 index 0000000..89800ca --- /dev/null +++ b/node_modules/minio/dist/esm/internal/callbackify.d.mts @@ -0,0 +1 @@ +export declare function callbackify(fn: (...args: any[]) => any): (this: any, ...args: any[]) => any; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/callbackify.mjs b/node_modules/minio/dist/esm/internal/callbackify.mjs new file mode 100644 index 0000000..43b0c46 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/callbackify.mjs @@ -0,0 +1,15 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ + +// Wrapper for an async function that supports callback style API. +// It will preserve 'this'. +export function callbackify(fn) { + return function (...args) { + const lastArg = args[args.length - 1]; + if (typeof lastArg === 'function') { + const callback = args.pop(); + return fn.apply(this, args).then(result => callback(null, result), err => callback(err)); + } + return fn.apply(this, args); + }; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjYWxsYmFja2lmeSIsImZuIiwiYXJncyIsImxhc3RBcmciLCJsZW5ndGgiLCJjYWxsYmFjayIsInBvcCIsImFwcGx5IiwidGhlbiIsInJlc3VsdCIsImVyciJdLCJzb3VyY2VzIjpbImNhbGxiYWNraWZ5LnRzIl0sInNvdXJjZXNDb250ZW50IjpbIi8qIGVzbGludC1kaXNhYmxlIEB0eXBlc2NyaXB0LWVzbGludC9uby1leHBsaWNpdC1hbnkgKi9cblxuLy8gV3JhcHBlciBmb3IgYW4gYXN5bmMgZnVuY3Rpb24gdGhhdCBzdXBwb3J0cyBjYWxsYmFjayBzdHlsZSBBUEkuXG4vLyBJdCB3aWxsIHByZXNlcnZlICd0aGlzJy5cbmV4cG9ydCBmdW5jdGlvbiBjYWxsYmFja2lmeShmbjogKC4uLmFyZ3M6IGFueVtdKSA9PiBhbnkpIHtcbiAgcmV0dXJuIGZ1bmN0aW9uICh0aGlzOiBhbnksIC4uLmFyZ3M6IGFueVtdKSB7XG4gICAgY29uc3QgbGFzdEFyZyA9IGFyZ3NbYXJncy5sZW5ndGggLSAxXVxuXG4gICAgaWYgKHR5cGVvZiBsYXN0QXJnID09PSAnZnVuY3Rpb24nKSB7XG4gICAgICBjb25zdCBjYWxsYmFjayA9IGFyZ3MucG9wKClcbiAgICAgIHJldHVybiBmbi5hcHBseSh0aGlzLCBhcmdzKS50aGVuKFxuICAgICAgICAocmVzdWx0OiBhbnkpID0+IGNhbGxiYWNrKG51bGwsIHJlc3VsdCksXG4gICAgICAgIChlcnI6IGFueSkgPT4gY2FsbGJhY2soZXJyKSxcbiAgICAgIClcbiAgICB9XG5cbiAgICByZXR1cm4gZm4uYXBwbHkodGhpcywgYXJncylcbiAgfVxufVxuIl0sIm1hcHBpbmdzIjoiQUFBQTs7QUFFQTtBQUNBO0FBQ0EsT0FBTyxTQUFTQSxXQUFXQSxDQUFDQyxFQUEyQixFQUFFO0VBQ3ZELE9BQU8sVUFBcUIsR0FBR0MsSUFBVyxFQUFFO0lBQzFDLE1BQU1DLE9BQU8sR0FBR0QsSUFBSSxDQUFDQSxJQUFJLENBQUNFLE1BQU0sR0FBRyxDQUFDLENBQUM7SUFFckMsSUFBSSxPQUFPRCxPQUFPLEtBQUssVUFBVSxFQUFFO01BQ2pDLE1BQU1FLFFBQVEsR0FBR0gsSUFBSSxDQUFDSSxHQUFHLENBQUMsQ0FBQztNQUMzQixPQUFPTCxFQUFFLENBQUNNLEtBQUssQ0FBQyxJQUFJLEVBQUVMLElBQUksQ0FBQyxDQUFDTSxJQUFJLENBQzdCQyxNQUFXLElBQUtKLFFBQVEsQ0FBQyxJQUFJLEVBQUVJLE1BQU0sQ0FBQyxFQUN0Q0MsR0FBUSxJQUFLTCxRQUFRLENBQUNLLEdBQUcsQ0FDNUIsQ0FBQztJQUNIO0lBRUEsT0FBT1QsRUFBRSxDQUFDTSxLQUFLLENBQUMsSUFBSSxFQUFFTCxJQUFJLENBQUM7RUFDN0IsQ0FBQztBQUNIIn0= \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/client.d.mts b/node_modules/minio/dist/esm/internal/client.d.mts new file mode 100644 index 0000000..01e7583 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/client.d.mts @@ -0,0 +1,394 @@ +/// +/// +/// +/// +import * as http from 'node:http'; +import * as https from 'node:https'; +import * as stream from 'node:stream'; +import { CredentialProvider } from "../CredentialProvider.mjs"; +import type { SelectResults } from "../helpers.mjs"; +import { CopyDestinationOptions, CopySourceOptions, LEGAL_HOLD_STATUS } from "../helpers.mjs"; +import type { NotificationEvent } from "../notification.mjs"; +import { NotificationConfig, NotificationPoller } from "../notification.mjs"; +import { CopyConditions } from "./copy-conditions.mjs"; +import { Extensions } from "./extensions.mjs"; +import { PostPolicy } from "./post-policy.mjs"; +import type { Region } from "./s3-endpoints.mjs"; +import type { Binary, BucketItem, BucketItemFromList, BucketItemStat, BucketStream, BucketVersioningConfiguration, CopyObjectResult, EncryptionConfig, GetObjectLegalHoldOptions, GetObjectOpts, GetObjectRetentionOpts, IncompleteUploadedBucketItem, IRequest, ItemBucketMetadata, LifecycleConfig, LifeCycleConfigParam, ListObjectQueryOpts, ListObjectV2Res, NotificationConfigResult, ObjectInfo, ObjectLockInfo, ObjectMetaData, ObjectRetentionInfo, PostPolicyResult, PreSignRequestParams, PutObjectLegalHoldOptions, RemoveObjectsParam, RemoveObjectsResponse, ReplicationConfig, ReplicationConfigOpts, RequestHeaders, ResultCallback, Retention, SelectOptions, StatObjectOpts, Tag, TaggingOpts, Tags, Transport, UploadedObjectInfo } from "./type.mjs"; +import type { ListMultipartResult, UploadedPart } from "./xml-parser.mjs"; +declare const requestOptionProperties: readonly ["agent", "ca", "cert", "ciphers", "clientCertEngine", "crl", "dhparam", "ecdhCurve", "family", "honorCipherOrder", "key", "passphrase", "pfx", "rejectUnauthorized", "secureOptions", "secureProtocol", "servername", "sessionIdContext"]; +export interface RetryOptions { + /** + * If this set to true, it will take precedence over all other retry options. + * @default false + */ + disableRetry?: boolean; + /** + * The maximum amount of retries for a request. + * @default 1 + */ + maximumRetryCount?: number; + /** + * The minimum duration (in milliseconds) for the exponential backoff algorithm. + * @default 100 + */ + baseDelayMs?: number; + /** + * The maximum duration (in milliseconds) for the exponential backoff algorithm. + * @default 60000 + */ + maximumDelayMs?: number; +} +export interface ClientOptions { + endPoint: string; + accessKey?: string; + secretKey?: string; + useSSL?: boolean; + port?: number; + region?: Region; + transport?: Transport; + sessionToken?: string; + partSize?: number; + pathStyle?: boolean; + credentialsProvider?: CredentialProvider; + s3AccelerateEndpoint?: string; + transportAgent?: http.Agent; + retryOptions?: RetryOptions; +} +export type RequestOption = Partial & { + method: string; + bucketName?: string; + objectName?: string; + query?: string; + pathStyle?: boolean; +}; +export type NoResultCallback = (error: unknown) => void; +export interface MakeBucketOpt { + ObjectLocking?: boolean; +} +export interface RemoveOptions { + versionId?: string; + governanceBypass?: boolean; + forceDelete?: boolean; +} +export declare class TypedClient { + protected transport: Transport; + protected host: string; + protected port: number; + protected protocol: string; + protected accessKey: string; + protected secretKey: string; + protected sessionToken?: string; + protected userAgent: string; + protected anonymous: boolean; + protected pathStyle: boolean; + protected regionMap: Record; + region?: string; + protected credentialsProvider?: CredentialProvider; + partSize: number; + protected overRidePartSize?: boolean; + protected retryOptions: RetryOptions; + protected maximumPartSize: number; + protected maxObjectSize: number; + enableSHA256: boolean; + protected s3AccelerateEndpoint?: string; + protected reqOptions: Record; + protected transportAgent: http.Agent; + private readonly clientExtensions; + constructor(params: ClientOptions); + /** + * Minio extensions that aren't necessary present for Amazon S3 compatible storage servers + */ + get extensions(): Extensions; + /** + * @param endPoint - valid S3 acceleration end point + */ + setS3TransferAccelerate(endPoint: string): void; + /** + * Sets the supported request options. + */ + setRequestOptions(options: Pick): void; + /** + * This is s3 Specific and does not hold validity in any other Object storage. + */ + private getAccelerateEndPointIfSet; + /** + * Set application specific information. + * Generates User-Agent in the following style. + * MinIO (OS; ARCH) LIB/VER APP/VER + */ + setAppInfo(appName: string, appVersion: string): void; + /** + * returns options object that can be used with http.request() + * Takes care of constructing virtual-host-style or path-style hostname + */ + protected getRequestOptions(opts: RequestOption & { + region: string; + }): IRequest & { + host: string; + headers: Record; + }; + setCredentialsProvider(credentialsProvider: CredentialProvider): Promise; + private checkAndRefreshCreds; + private logStream?; + /** + * log the request, response, error + */ + private logHTTP; + /** + * Enable tracing + */ + traceOn(stream?: stream.Writable): void; + /** + * Disable tracing + */ + traceOff(): void; + /** + * makeRequest is the primitive used by the apis for making S3 requests. + * payload can be empty string in case of no payload. + * statusCode is the expected statusCode. If response.statusCode does not match + * we parse the XML error and call the callback with the error message. + * + * A valid region is passed by the calls - listBuckets, makeBucket and getBucketRegion. + * + * @internal + */ + makeRequestAsync(options: RequestOption, payload?: Binary, expectedCodes?: number[], region?: string): Promise; + /** + * new request with promise + * + * No need to drain response, response body is not valid + */ + makeRequestAsyncOmit(options: RequestOption, payload?: Binary, statusCodes?: number[], region?: string): Promise>; + /** + * makeRequestStream will be used directly instead of makeRequest in case the payload + * is available as a stream. for ex. putObject + * + * @internal + */ + makeRequestStreamAsync(options: RequestOption, body: stream.Readable | Binary, sha256sum: string, statusCodes: number[], region: string): Promise; + /** + * gets the region of the bucket + * + * @param bucketName + * + */ + getBucketRegionAsync(bucketName: string): Promise; + /** + * makeRequest is the primitive used by the apis for making S3 requests. + * payload can be empty string in case of no payload. + * statusCode is the expected statusCode. If response.statusCode does not match + * we parse the XML error and call the callback with the error message. + * A valid region is passed by the calls - listBuckets, makeBucket and + * getBucketRegion. + * + * @deprecated use `makeRequestAsync` instead + */ + makeRequest(options: RequestOption, payload: Binary | undefined, expectedCodes: number[] | undefined, region: string | undefined, returnResponse: boolean, cb: (cb: unknown, result: http.IncomingMessage) => void): void; + /** + * makeRequestStream will be used directly instead of makeRequest in case the payload + * is available as a stream. for ex. putObject + * + * @deprecated use `makeRequestStreamAsync` instead + */ + makeRequestStream(options: RequestOption, stream: stream.Readable | Buffer, sha256sum: string, statusCodes: number[], region: string, returnResponse: boolean, cb: (cb: unknown, result: http.IncomingMessage) => void): void; + /** + * @deprecated use `getBucketRegionAsync` instead + */ + getBucketRegion(bucketName: string, cb: (err: unknown, region: string) => void): Promise; + /** + * Creates the bucket `bucketName`. + * + */ + makeBucket(bucketName: string, region?: Region, makeOpts?: MakeBucketOpt): Promise; + /** + * To check if a bucket already exists. + */ + bucketExists(bucketName: string): Promise; + removeBucket(bucketName: string): Promise; + /** + * @deprecated use promise style API + */ + removeBucket(bucketName: string, callback: NoResultCallback): void; + /** + * Callback is called with readable stream of the object content. + */ + getObject(bucketName: string, objectName: string, getOpts?: GetObjectOpts): Promise; + /** + * Callback is called with readable stream of the partial object content. + * @param bucketName + * @param objectName + * @param offset + * @param length - length of the object that will be read in the stream (optional, if not specified we read the rest of the file from the offset) + * @param getOpts + */ + getPartialObject(bucketName: string, objectName: string, offset: number, length?: number, getOpts?: GetObjectOpts): Promise; + /** + * download object content to a file. + * This method will create a temp file named `${filename}.${base64(etag)}.part.minio` when downloading. + * + * @param bucketName - name of the bucket + * @param objectName - name of the object + * @param filePath - path to which the object data will be written to + * @param getOpts - Optional object get option + */ + fGetObject(bucketName: string, objectName: string, filePath: string, getOpts?: GetObjectOpts): Promise; + /** + * Stat information of the object. + */ + statObject(bucketName: string, objectName: string, statOpts?: StatObjectOpts): Promise; + removeObject(bucketName: string, objectName: string, removeOpts?: RemoveOptions): Promise; + listIncompleteUploads(bucket: string, prefix: string, recursive: boolean): BucketStream; + /** + * Called by listIncompleteUploads to fetch a batch of incomplete uploads. + */ + listIncompleteUploadsQuery(bucketName: string, prefix: string, keyMarker: string, uploadIdMarker: string, delimiter: string): Promise; + /** + * Initiate a new multipart upload. + * @internal + */ + initiateNewMultipartUpload(bucketName: string, objectName: string, headers: RequestHeaders): Promise; + /** + * Internal Method to abort a multipart upload request in case of any errors. + * + * @param bucketName - Bucket Name + * @param objectName - Object Name + * @param uploadId - id of a multipart upload to cancel during compose object sequence. + */ + abortMultipartUpload(bucketName: string, objectName: string, uploadId: string): Promise; + findUploadId(bucketName: string, objectName: string): Promise; + /** + * this call will aggregate the parts on the server into a single object. + */ + completeMultipartUpload(bucketName: string, objectName: string, uploadId: string, etags: { + part: number; + etag?: string; + }[]): Promise<{ + etag: string; + versionId: string | null; + }>; + /** + * Get part-info of all parts of an incomplete upload specified by uploadId. + */ + protected listParts(bucketName: string, objectName: string, uploadId: string): Promise; + /** + * Called by listParts to fetch a batch of part-info + */ + private listPartsQuery; + listBuckets(): Promise; + /** + * Calculate part size given the object size. Part size will be atleast this.partSize + */ + calculatePartSize(size: number): number; + /** + * Uploads the object using contents from a file + */ + fPutObject(bucketName: string, objectName: string, filePath: string, metaData?: ObjectMetaData): Promise; + /** + * Uploading a stream, "Buffer" or "string". + * It's recommended to pass `size` argument with stream. + */ + putObject(bucketName: string, objectName: string, stream: stream.Readable | Buffer | string, size?: number, metaData?: ItemBucketMetadata): Promise; + /** + * method to upload buffer in one call + * @private + */ + private uploadBuffer; + /** + * upload stream with MultipartUpload + * @private + */ + private uploadStream; + removeBucketReplication(bucketName: string): Promise; + removeBucketReplication(bucketName: string, callback: NoResultCallback): void; + setBucketReplication(bucketName: string, replicationConfig: ReplicationConfigOpts): void; + setBucketReplication(bucketName: string, replicationConfig: ReplicationConfigOpts): Promise; + getBucketReplication(bucketName: string): void; + getBucketReplication(bucketName: string): Promise; + getObjectLegalHold(bucketName: string, objectName: string, getOpts?: GetObjectLegalHoldOptions, callback?: ResultCallback): Promise; + setObjectLegalHold(bucketName: string, objectName: string, setOpts?: PutObjectLegalHoldOptions): void; + /** + * Get Tags associated with a Bucket + */ + getBucketTagging(bucketName: string): Promise; + /** + * Get the tags associated with a bucket OR an object + */ + getObjectTagging(bucketName: string, objectName: string, getOpts?: GetObjectOpts): Promise; + /** + * Set the policy on a bucket or an object prefix. + */ + setBucketPolicy(bucketName: string, policy: string): Promise; + /** + * Get the policy on a bucket or an object prefix. + */ + getBucketPolicy(bucketName: string): Promise; + putObjectRetention(bucketName: string, objectName: string, retentionOpts?: Retention): Promise; + getObjectLockConfig(bucketName: string, callback: ResultCallback): void; + getObjectLockConfig(bucketName: string): void; + getObjectLockConfig(bucketName: string): Promise; + setObjectLockConfig(bucketName: string, lockConfigOpts: Omit): void; + setObjectLockConfig(bucketName: string, lockConfigOpts: Omit): Promise; + getBucketVersioning(bucketName: string): Promise; + setBucketVersioning(bucketName: string, versionConfig: BucketVersioningConfiguration): Promise; + private setTagging; + private removeTagging; + setBucketTagging(bucketName: string, tags: Tags): Promise; + removeBucketTagging(bucketName: string): Promise; + setObjectTagging(bucketName: string, objectName: string, tags: Tags, putOpts?: TaggingOpts): Promise; + removeObjectTagging(bucketName: string, objectName: string, removeOpts: TaggingOpts): Promise; + selectObjectContent(bucketName: string, objectName: string, selectOpts: SelectOptions): Promise; + private applyBucketLifecycle; + removeBucketLifecycle(bucketName: string): Promise; + setBucketLifecycle(bucketName: string, lifeCycleConfig: LifeCycleConfigParam): Promise; + getBucketLifecycle(bucketName: string): Promise; + setBucketEncryption(bucketName: string, encryptionConfig?: EncryptionConfig): Promise; + getBucketEncryption(bucketName: string): Promise; + removeBucketEncryption(bucketName: string): Promise; + getObjectRetention(bucketName: string, objectName: string, getOpts?: GetObjectRetentionOpts): Promise; + removeObjects(bucketName: string, objectsList: RemoveObjectsParam): Promise; + removeIncompleteUpload(bucketName: string, objectName: string): Promise; + private copyObjectV1; + private copyObjectV2; + copyObject(source: CopySourceOptions, dest: CopyDestinationOptions): Promise; + copyObject(targetBucketName: string, targetObjectName: string, sourceBucketNameAndObjectName: string, conditions?: CopyConditions): Promise; + uploadPart(partConfig: { + bucketName: string; + objectName: string; + uploadID: string; + partNumber: number; + headers: RequestHeaders; + }, payload?: Binary): Promise<{ + etag: string; + key: string; + part: number; + }>; + composeObject(destObjConfig: CopyDestinationOptions, sourceObjList: CopySourceOptions[], { + maxConcurrency + }?: { + maxConcurrency?: number | undefined; + }): Promise | CopyObjectResult>; + presignedUrl(method: string, bucketName: string, objectName: string, expires?: number | PreSignRequestParams | undefined, reqParams?: PreSignRequestParams | Date, requestDate?: Date): Promise; + presignedGetObject(bucketName: string, objectName: string, expires?: number, respHeaders?: PreSignRequestParams | Date, requestDate?: Date): Promise; + presignedPutObject(bucketName: string, objectName: string, expires?: number): Promise; + newPostPolicy(): PostPolicy; + presignedPostPolicy(postPolicy: PostPolicy): Promise; + listObjectsQuery(bucketName: string, prefix?: string, marker?: string, listQueryOpts?: ListObjectQueryOpts): Promise<{ + objects: ObjectInfo[]; + isTruncated?: boolean | undefined; + nextMarker?: string | undefined; + versionIdMarker?: string | undefined; + keyMarker?: string | undefined; + }>; + listObjects(bucketName: string, prefix?: string, recursive?: boolean, listOpts?: ListObjectQueryOpts | undefined): BucketStream; + listObjectsV2Query(bucketName: string, prefix: string, continuationToken: string, delimiter: string, maxKeys: number, startAfter: string): Promise; + listObjectsV2(bucketName: string, prefix?: string, recursive?: boolean, startAfter?: string): BucketStream; + setBucketNotification(bucketName: string, config: NotificationConfig): Promise; + removeAllBucketNotification(bucketName: string): Promise; + getBucketNotification(bucketName: string): Promise; + listenBucketNotification(bucketName: string, prefix: string, suffix: string, events: NotificationEvent[]): NotificationPoller; +} +export {}; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/client.mjs b/node_modules/minio/dist/esm/internal/client.mjs new file mode 100644 index 0000000..e9f9669 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/client.mjs @@ -0,0 +1,3007 @@ +import * as crypto from "crypto"; +import * as fs from "fs"; +import * as http from "http"; +import * as https from "https"; +import * as path from "path"; +import * as stream from "stream"; +import * as async from 'async'; +import BlockStream2 from 'block-stream2'; +import { isBrowser } from 'browser-or-node'; +import _ from 'lodash'; +import * as qs from 'query-string'; +import xml2js from 'xml2js'; +import { CredentialProvider } from "../CredentialProvider.mjs"; +import * as errors from "../errors.mjs"; +import { CopyDestinationOptions, CopySourceOptions, DEFAULT_REGION, LEGAL_HOLD_STATUS, PRESIGN_EXPIRY_DAYS_MAX, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from "../helpers.mjs"; +import { NotificationConfig, NotificationPoller } from "../notification.mjs"; +import { postPresignSignatureV4, presignSignatureV4, signV4 } from "../signing.mjs"; +import { fsp, streamPromise } from "./async.mjs"; +import { CopyConditions } from "./copy-conditions.mjs"; +import { Extensions } from "./extensions.mjs"; +import { calculateEvenSplits, extractMetadata, getContentLength, getScope, getSourceVersionId, getVersionId, hashBinary, insertContentType, isAmazonEndpoint, isBoolean, isDefined, isEmpty, isNumber, isObject, isPlainObject, isReadableStream, isString, isValidBucketName, isValidEndpoint, isValidObjectName, isValidPort, isValidPrefix, isVirtualHostStyle, makeDateLong, PART_CONSTRAINTS, partsRequired, prependXAMZMeta, readableStream, sanitizeETag, toMd5, toSha256, uriEscape, uriResourceEscape } from "./helper.mjs"; +import { joinHostPort } from "./join-host-port.mjs"; +import { PostPolicy } from "./post-policy.mjs"; +import { requestWithRetry } from "./request.mjs"; +import { drainResponse, readAsBuffer, readAsString } from "./response.mjs"; +import { getS3Endpoint } from "./s3-endpoints.mjs"; +import { parseBucketNotification, parseCompleteMultipart, parseInitiateMultipart, parseListObjects, parseListObjectsV2, parseObjectLegalHoldConfig, parseSelectObjectContentResponse, uploadPartParser } from "./xml-parser.mjs"; +import * as xmlParsers from "./xml-parser.mjs"; +const xml = new xml2js.Builder({ + renderOpts: { + pretty: false + }, + headless: true +}); + +// will be replaced by bundler. +const Package = { + version: "8.0.7" || 'development' +}; +const requestOptionProperties = ['agent', 'ca', 'cert', 'ciphers', 'clientCertEngine', 'crl', 'dhparam', 'ecdhCurve', 'family', 'honorCipherOrder', 'key', 'passphrase', 'pfx', 'rejectUnauthorized', 'secureOptions', 'secureProtocol', 'servername', 'sessionIdContext']; +export class TypedClient { + partSize = 64 * 1024 * 1024; + maximumPartSize = 5 * 1024 * 1024 * 1024; + maxObjectSize = 5 * 1024 * 1024 * 1024 * 1024; + constructor(params) { + // @ts-expect-error deprecated property + if (params.secure !== undefined) { + throw new Error('"secure" option deprecated, "useSSL" should be used instead'); + } + // Default values if not specified. + if (params.useSSL === undefined) { + params.useSSL = true; + } + if (!params.port) { + params.port = 0; + } + // Validate input params. + if (!isValidEndpoint(params.endPoint)) { + throw new errors.InvalidEndpointError(`Invalid endPoint : ${params.endPoint}`); + } + if (!isValidPort(params.port)) { + throw new errors.InvalidArgumentError(`Invalid port : ${params.port}`); + } + if (!isBoolean(params.useSSL)) { + throw new errors.InvalidArgumentError(`Invalid useSSL flag type : ${params.useSSL}, expected to be of type "boolean"`); + } + + // Validate region only if its set. + if (params.region) { + if (!isString(params.region)) { + throw new errors.InvalidArgumentError(`Invalid region : ${params.region}`); + } + } + const host = params.endPoint.toLowerCase(); + let port = params.port; + let protocol; + let transport; + let transportAgent; + // Validate if configuration is not using SSL + // for constructing relevant endpoints. + if (params.useSSL) { + // Defaults to secure. + transport = https; + protocol = 'https:'; + port = port || 443; + transportAgent = https.globalAgent; + } else { + transport = http; + protocol = 'http:'; + port = port || 80; + transportAgent = http.globalAgent; + } + + // if custom transport is set, use it. + if (params.transport) { + if (!isObject(params.transport)) { + throw new errors.InvalidArgumentError(`Invalid transport type : ${params.transport}, expected to be type "object"`); + } + transport = params.transport; + } + + // if custom transport agent is set, use it. + if (params.transportAgent) { + if (!isObject(params.transportAgent)) { + throw new errors.InvalidArgumentError(`Invalid transportAgent type: ${params.transportAgent}, expected to be type "object"`); + } + transportAgent = params.transportAgent; + } + + // User Agent should always following the below style. + // Please open an issue to discuss any new changes here. + // + // MinIO (OS; ARCH) LIB/VER APP/VER + // + const libraryComments = `(${process.platform}; ${process.arch})`; + const libraryAgent = `MinIO ${libraryComments} minio-js/${Package.version}`; + // User agent block ends. + + this.transport = transport; + this.transportAgent = transportAgent; + this.host = host; + this.port = port; + this.protocol = protocol; + this.userAgent = `${libraryAgent}`; + + // Default path style is true + if (params.pathStyle === undefined) { + this.pathStyle = true; + } else { + this.pathStyle = params.pathStyle; + } + this.accessKey = params.accessKey ?? ''; + this.secretKey = params.secretKey ?? ''; + this.sessionToken = params.sessionToken; + this.anonymous = !this.accessKey || !this.secretKey; + if (params.credentialsProvider) { + this.anonymous = false; + this.credentialsProvider = params.credentialsProvider; + } + this.regionMap = {}; + if (params.region) { + this.region = params.region; + } + if (params.partSize) { + this.partSize = params.partSize; + this.overRidePartSize = true; + } + if (this.partSize < 5 * 1024 * 1024) { + throw new errors.InvalidArgumentError(`Part size should be greater than 5MB`); + } + if (this.partSize > 5 * 1024 * 1024 * 1024) { + throw new errors.InvalidArgumentError(`Part size should be less than 5GB`); + } + + // SHA256 is enabled only for authenticated http requests. If the request is authenticated + // and the connection is https we use x-amz-content-sha256=UNSIGNED-PAYLOAD + // header for signature calculation. + this.enableSHA256 = !this.anonymous && !params.useSSL; + this.s3AccelerateEndpoint = params.s3AccelerateEndpoint || undefined; + this.reqOptions = {}; + this.clientExtensions = new Extensions(this); + if (params.retryOptions) { + if (!isObject(params.retryOptions)) { + throw new errors.InvalidArgumentError(`Invalid retryOptions type: ${params.retryOptions}, expected to be type "object"`); + } + this.retryOptions = params.retryOptions; + } else { + this.retryOptions = { + disableRetry: false + }; + } + } + /** + * Minio extensions that aren't necessary present for Amazon S3 compatible storage servers + */ + get extensions() { + return this.clientExtensions; + } + + /** + * @param endPoint - valid S3 acceleration end point + */ + setS3TransferAccelerate(endPoint) { + this.s3AccelerateEndpoint = endPoint; + } + + /** + * Sets the supported request options. + */ + setRequestOptions(options) { + if (!isObject(options)) { + throw new TypeError('request options should be of type "object"'); + } + this.reqOptions = _.pick(options, requestOptionProperties); + } + + /** + * This is s3 Specific and does not hold validity in any other Object storage. + */ + getAccelerateEndPointIfSet(bucketName, objectName) { + if (!isEmpty(this.s3AccelerateEndpoint) && !isEmpty(bucketName) && !isEmpty(objectName)) { + // http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html + // Disable transfer acceleration for non-compliant bucket names. + if (bucketName.includes('.')) { + throw new Error(`Transfer Acceleration is not supported for non compliant bucket:${bucketName}`); + } + // If transfer acceleration is requested set new host. + // For more details about enabling transfer acceleration read here. + // http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html + return this.s3AccelerateEndpoint; + } + return false; + } + + /** + * Set application specific information. + * Generates User-Agent in the following style. + * MinIO (OS; ARCH) LIB/VER APP/VER + */ + setAppInfo(appName, appVersion) { + if (!isString(appName)) { + throw new TypeError(`Invalid appName: ${appName}`); + } + if (appName.trim() === '') { + throw new errors.InvalidArgumentError('Input appName cannot be empty.'); + } + if (!isString(appVersion)) { + throw new TypeError(`Invalid appVersion: ${appVersion}`); + } + if (appVersion.trim() === '') { + throw new errors.InvalidArgumentError('Input appVersion cannot be empty.'); + } + this.userAgent = `${this.userAgent} ${appName}/${appVersion}`; + } + + /** + * returns options object that can be used with http.request() + * Takes care of constructing virtual-host-style or path-style hostname + */ + getRequestOptions(opts) { + const method = opts.method; + const region = opts.region; + const bucketName = opts.bucketName; + let objectName = opts.objectName; + const headers = opts.headers; + const query = opts.query; + let reqOptions = { + method, + headers: {}, + protocol: this.protocol, + // If custom transportAgent was supplied earlier, we'll inject it here + agent: this.transportAgent + }; + + // Verify if virtual host supported. + let virtualHostStyle; + if (bucketName) { + virtualHostStyle = isVirtualHostStyle(this.host, this.protocol, bucketName, this.pathStyle); + } + let path = '/'; + let host = this.host; + let port; + if (this.port) { + port = this.port; + } + if (objectName) { + objectName = uriResourceEscape(objectName); + } + + // For Amazon S3 endpoint, get endpoint based on region. + if (isAmazonEndpoint(host)) { + const accelerateEndPoint = this.getAccelerateEndPointIfSet(bucketName, objectName); + if (accelerateEndPoint) { + host = `${accelerateEndPoint}`; + } else { + host = getS3Endpoint(region); + } + } + if (virtualHostStyle && !opts.pathStyle) { + // For all hosts which support virtual host style, `bucketName` + // is part of the hostname in the following format: + // + // var host = 'bucketName.example.com' + // + if (bucketName) { + host = `${bucketName}.${host}`; + } + if (objectName) { + path = `/${objectName}`; + } + } else { + // For all S3 compatible storage services we will fallback to + // path style requests, where `bucketName` is part of the URI + // path. + if (bucketName) { + path = `/${bucketName}`; + } + if (objectName) { + path = `/${bucketName}/${objectName}`; + } + } + if (query) { + path += `?${query}`; + } + reqOptions.headers.host = host; + if (reqOptions.protocol === 'http:' && port !== 80 || reqOptions.protocol === 'https:' && port !== 443) { + reqOptions.headers.host = joinHostPort(host, port); + } + reqOptions.headers['user-agent'] = this.userAgent; + if (headers) { + // have all header keys in lower case - to make signing easy + for (const [k, v] of Object.entries(headers)) { + reqOptions.headers[k.toLowerCase()] = v; + } + } + + // Use any request option specified in minioClient.setRequestOptions() + reqOptions = Object.assign({}, this.reqOptions, reqOptions); + return { + ...reqOptions, + headers: _.mapValues(_.pickBy(reqOptions.headers, isDefined), v => v.toString()), + host, + port, + path + }; + } + async setCredentialsProvider(credentialsProvider) { + if (!(credentialsProvider instanceof CredentialProvider)) { + throw new Error('Unable to get credentials. Expected instance of CredentialProvider'); + } + this.credentialsProvider = credentialsProvider; + await this.checkAndRefreshCreds(); + } + async checkAndRefreshCreds() { + if (this.credentialsProvider) { + try { + const credentialsConf = await this.credentialsProvider.getCredentials(); + this.accessKey = credentialsConf.getAccessKey(); + this.secretKey = credentialsConf.getSecretKey(); + this.sessionToken = credentialsConf.getSessionToken(); + } catch (e) { + throw new Error(`Unable to get credentials: ${e}`, { + cause: e + }); + } + } + } + /** + * log the request, response, error + */ + logHTTP(reqOptions, response, err) { + // if no logStream available return. + if (!this.logStream) { + return; + } + if (!isObject(reqOptions)) { + throw new TypeError('reqOptions should be of type "object"'); + } + if (response && !isReadableStream(response)) { + throw new TypeError('response should be of type "Stream"'); + } + if (err && !(err instanceof Error)) { + throw new TypeError('err should be of type "Error"'); + } + const logStream = this.logStream; + const logHeaders = headers => { + Object.entries(headers).forEach(([k, v]) => { + if (k == 'authorization') { + if (isString(v)) { + const redactor = new RegExp('Signature=([0-9a-f]+)'); + v = v.replace(redactor, 'Signature=**REDACTED**'); + } + } + logStream.write(`${k}: ${v}\n`); + }); + logStream.write('\n'); + }; + logStream.write(`REQUEST: ${reqOptions.method} ${reqOptions.path}\n`); + logHeaders(reqOptions.headers); + if (response) { + this.logStream.write(`RESPONSE: ${response.statusCode}\n`); + logHeaders(response.headers); + } + if (err) { + logStream.write('ERROR BODY:\n'); + const errJSON = JSON.stringify(err, null, '\t'); + logStream.write(`${errJSON}\n`); + } + } + + /** + * Enable tracing + */ + traceOn(stream) { + if (!stream) { + stream = process.stdout; + } + this.logStream = stream; + } + + /** + * Disable tracing + */ + traceOff() { + this.logStream = undefined; + } + + /** + * makeRequest is the primitive used by the apis for making S3 requests. + * payload can be empty string in case of no payload. + * statusCode is the expected statusCode. If response.statusCode does not match + * we parse the XML error and call the callback with the error message. + * + * A valid region is passed by the calls - listBuckets, makeBucket and getBucketRegion. + * + * @internal + */ + async makeRequestAsync(options, payload = '', expectedCodes = [200], region = '') { + if (!isObject(options)) { + throw new TypeError('options should be of type "object"'); + } + if (!isString(payload) && !isObject(payload)) { + // Buffer is of type 'object' + throw new TypeError('payload should be of type "string" or "Buffer"'); + } + expectedCodes.forEach(statusCode => { + if (!isNumber(statusCode)) { + throw new TypeError('statusCode should be of type "number"'); + } + }); + if (!isString(region)) { + throw new TypeError('region should be of type "string"'); + } + if (!options.headers) { + options.headers = {}; + } + if (options.method === 'POST' || options.method === 'PUT' || options.method === 'DELETE') { + options.headers['content-length'] = payload.length.toString(); + } + const sha256sum = this.enableSHA256 ? toSha256(payload) : ''; + return this.makeRequestStreamAsync(options, payload, sha256sum, expectedCodes, region); + } + + /** + * new request with promise + * + * No need to drain response, response body is not valid + */ + async makeRequestAsyncOmit(options, payload = '', statusCodes = [200], region = '') { + const res = await this.makeRequestAsync(options, payload, statusCodes, region); + await drainResponse(res); + return res; + } + + /** + * makeRequestStream will be used directly instead of makeRequest in case the payload + * is available as a stream. for ex. putObject + * + * @internal + */ + async makeRequestStreamAsync(options, body, sha256sum, statusCodes, region) { + if (!isObject(options)) { + throw new TypeError('options should be of type "object"'); + } + if (!(Buffer.isBuffer(body) || typeof body === 'string' || isReadableStream(body))) { + throw new errors.InvalidArgumentError(`stream should be a Buffer, string or readable Stream, got ${typeof body} instead`); + } + if (!isString(sha256sum)) { + throw new TypeError('sha256sum should be of type "string"'); + } + statusCodes.forEach(statusCode => { + if (!isNumber(statusCode)) { + throw new TypeError('statusCode should be of type "number"'); + } + }); + if (!isString(region)) { + throw new TypeError('region should be of type "string"'); + } + // sha256sum will be empty for anonymous or https requests + if (!this.enableSHA256 && sha256sum.length !== 0) { + throw new errors.InvalidArgumentError(`sha256sum expected to be empty for anonymous or https requests`); + } + // sha256sum should be valid for non-anonymous http requests. + if (this.enableSHA256 && sha256sum.length !== 64) { + throw new errors.InvalidArgumentError(`Invalid sha256sum : ${sha256sum}`); + } + await this.checkAndRefreshCreds(); + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + region = region || (await this.getBucketRegionAsync(options.bucketName)); + const reqOptions = this.getRequestOptions({ + ...options, + region + }); + if (!this.anonymous) { + // For non-anonymous https requests sha256sum is 'UNSIGNED-PAYLOAD' for signature calculation. + if (!this.enableSHA256) { + sha256sum = 'UNSIGNED-PAYLOAD'; + } + const date = new Date(); + reqOptions.headers['x-amz-date'] = makeDateLong(date); + reqOptions.headers['x-amz-content-sha256'] = sha256sum; + if (this.sessionToken) { + reqOptions.headers['x-amz-security-token'] = this.sessionToken; + } + reqOptions.headers.authorization = signV4(reqOptions, this.accessKey, this.secretKey, region, date, sha256sum); + } + const response = await requestWithRetry(this.transport, reqOptions, body, this.retryOptions.disableRetry === true ? 0 : this.retryOptions.maximumRetryCount, this.retryOptions.baseDelayMs, this.retryOptions.maximumDelayMs); + if (!response.statusCode) { + throw new Error("BUG: response doesn't have a statusCode"); + } + if (!statusCodes.includes(response.statusCode)) { + // For an incorrect region, S3 server always sends back 400. + // But we will do cache invalidation for all errors so that, + // in future, if AWS S3 decides to send a different status code or + // XML error code we will still work fine. + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + delete this.regionMap[options.bucketName]; + const err = await xmlParsers.parseResponseError(response); + this.logHTTP(reqOptions, response, err); + throw err; + } + this.logHTTP(reqOptions, response); + return response; + } + + /** + * gets the region of the bucket + * + * @param bucketName + * + */ + async getBucketRegionAsync(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name : ${bucketName}`); + } + + // Region is set with constructor, return the region right here. + if (this.region) { + return this.region; + } + const cached = this.regionMap[bucketName]; + if (cached) { + return cached; + } + const extractRegionAsync = async response => { + const body = await readAsString(response); + const region = xmlParsers.parseBucketRegion(body) || DEFAULT_REGION; + this.regionMap[bucketName] = region; + return region; + }; + const method = 'GET'; + const query = 'location'; + // `getBucketLocation` behaves differently in following ways for + // different environments. + // + // - For nodejs env we default to path style requests. + // - For browser env path style requests on buckets yields CORS + // error. To circumvent this problem we make a virtual host + // style request signed with 'us-east-1'. This request fails + // with an error 'AuthorizationHeaderMalformed', additionally + // the error XML also provides Region of the bucket. To validate + // this region is proper we retry the same request with the newly + // obtained region. + const pathStyle = this.pathStyle && !isBrowser; + let region; + try { + const res = await this.makeRequestAsync({ + method, + bucketName, + query, + pathStyle + }, '', [200], DEFAULT_REGION); + return extractRegionAsync(res); + } catch (e) { + // make alignment with mc cli + if (e instanceof errors.S3Error) { + const errCode = e.code; + const errRegion = e.region; + if (errCode === 'AccessDenied' && !errRegion) { + return DEFAULT_REGION; + } + } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + if (!(e.name === 'AuthorizationHeaderMalformed')) { + throw e; + } + // @ts-expect-error we set extra properties on error object + region = e.Region; + if (!region) { + throw e; + } + } + const res = await this.makeRequestAsync({ + method, + bucketName, + query, + pathStyle + }, '', [200], region); + return await extractRegionAsync(res); + } + + /** + * makeRequest is the primitive used by the apis for making S3 requests. + * payload can be empty string in case of no payload. + * statusCode is the expected statusCode. If response.statusCode does not match + * we parse the XML error and call the callback with the error message. + * A valid region is passed by the calls - listBuckets, makeBucket and + * getBucketRegion. + * + * @deprecated use `makeRequestAsync` instead + */ + makeRequest(options, payload = '', expectedCodes = [200], region = '', returnResponse, cb) { + let prom; + if (returnResponse) { + prom = this.makeRequestAsync(options, payload, expectedCodes, region); + } else { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error compatible for old behaviour + prom = this.makeRequestAsyncOmit(options, payload, expectedCodes, region); + } + prom.then(result => cb(null, result), err => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + cb(err); + }); + } + + /** + * makeRequestStream will be used directly instead of makeRequest in case the payload + * is available as a stream. for ex. putObject + * + * @deprecated use `makeRequestStreamAsync` instead + */ + makeRequestStream(options, stream, sha256sum, statusCodes, region, returnResponse, cb) { + const executor = async () => { + const res = await this.makeRequestStreamAsync(options, stream, sha256sum, statusCodes, region); + if (!returnResponse) { + await drainResponse(res); + } + return res; + }; + executor().then(result => cb(null, result), + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + err => cb(err)); + } + + /** + * @deprecated use `getBucketRegionAsync` instead + */ + getBucketRegion(bucketName, cb) { + return this.getBucketRegionAsync(bucketName).then(result => cb(null, result), + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + err => cb(err)); + } + + // Bucket operations + + /** + * Creates the bucket `bucketName`. + * + */ + async makeBucket(bucketName, region = '', makeOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + // Backward Compatibility + if (isObject(region)) { + makeOpts = region; + region = ''; + } + if (!isString(region)) { + throw new TypeError('region should be of type "string"'); + } + if (makeOpts && !isObject(makeOpts)) { + throw new TypeError('makeOpts should be of type "object"'); + } + let payload = ''; + + // Region already set in constructor, validate if + // caller requested bucket location is same. + if (region && this.region) { + if (region !== this.region) { + throw new errors.InvalidArgumentError(`Configured region ${this.region}, requested ${region}`); + } + } + // sending makeBucket request with XML containing 'us-east-1' fails. For + // default region server expects the request without body + if (region && region !== DEFAULT_REGION) { + payload = xml.buildObject({ + CreateBucketConfiguration: { + $: { + xmlns: 'http://s3.amazonaws.com/doc/2006-03-01/' + }, + LocationConstraint: region + } + }); + } + const method = 'PUT'; + const headers = {}; + if (makeOpts && makeOpts.ObjectLocking) { + headers['x-amz-bucket-object-lock-enabled'] = true; + } + + // For custom region clients default to custom region specified in client constructor + const finalRegion = this.region || region || DEFAULT_REGION; + const requestOpt = { + method, + bucketName, + headers + }; + try { + await this.makeRequestAsyncOmit(requestOpt, payload, [200], finalRegion); + } catch (err) { + if (region === '' || region === DEFAULT_REGION) { + if (err instanceof errors.S3Error) { + const errCode = err.code; + const errRegion = err.region; + if (errCode === 'AuthorizationHeaderMalformed' && errRegion !== '') { + // Retry with region returned as part of error + await this.makeRequestAsyncOmit(requestOpt, payload, [200], errCode); + } + } + } + throw err; + } + } + + /** + * To check if a bucket already exists. + */ + async bucketExists(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'HEAD'; + try { + await this.makeRequestAsyncOmit({ + method, + bucketName + }); + } catch (err) { + // @ts-ignore + if (err.code === 'NoSuchBucket' || err.code === 'NotFound') { + return false; + } + throw err; + } + return true; + } + + /** + * @deprecated use promise style API + */ + + async removeBucket(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'DELETE'; + await this.makeRequestAsyncOmit({ + method, + bucketName + }, '', [204]); + delete this.regionMap[bucketName]; + } + + /** + * Callback is called with readable stream of the object content. + */ + async getObject(bucketName, objectName, getOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + return this.getPartialObject(bucketName, objectName, 0, 0, getOpts); + } + + /** + * Callback is called with readable stream of the partial object content. + * @param bucketName + * @param objectName + * @param offset + * @param length - length of the object that will be read in the stream (optional, if not specified we read the rest of the file from the offset) + * @param getOpts + */ + async getPartialObject(bucketName, objectName, offset, length = 0, getOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!isNumber(offset)) { + throw new TypeError('offset should be of type "number"'); + } + if (!isNumber(length)) { + throw new TypeError('length should be of type "number"'); + } + let range = ''; + if (offset || length) { + if (offset) { + range = `bytes=${+offset}-`; + } else { + range = 'bytes=0-'; + offset = 0; + } + if (length) { + range += `${+length + offset - 1}`; + } + } + let query = ''; + let headers = { + ...(range !== '' && { + range + }) + }; + if (getOpts) { + const sseHeaders = { + ...(getOpts.SSECustomerAlgorithm && { + 'X-Amz-Server-Side-Encryption-Customer-Algorithm': getOpts.SSECustomerAlgorithm + }), + ...(getOpts.SSECustomerKey && { + 'X-Amz-Server-Side-Encryption-Customer-Key': getOpts.SSECustomerKey + }), + ...(getOpts.SSECustomerKeyMD5 && { + 'X-Amz-Server-Side-Encryption-Customer-Key-MD5': getOpts.SSECustomerKeyMD5 + }) + }; + query = qs.stringify(getOpts); + headers = { + ...prependXAMZMeta(sseHeaders), + ...headers + }; + } + const expectedStatusCodes = [200]; + if (range) { + expectedStatusCodes.push(206); + } + const method = 'GET'; + return await this.makeRequestAsync({ + method, + bucketName, + objectName, + headers, + query + }, '', expectedStatusCodes); + } + + /** + * download object content to a file. + * This method will create a temp file named `${filename}.${base64(etag)}.part.minio` when downloading. + * + * @param bucketName - name of the bucket + * @param objectName - name of the object + * @param filePath - path to which the object data will be written to + * @param getOpts - Optional object get option + */ + async fGetObject(bucketName, objectName, filePath, getOpts) { + // Input validation. + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!isString(filePath)) { + throw new TypeError('filePath should be of type "string"'); + } + const downloadToTmpFile = async () => { + let partFileStream; + const objStat = await this.statObject(bucketName, objectName, getOpts); + const encodedEtag = Buffer.from(objStat.etag).toString('base64'); + const partFile = `${filePath}.${encodedEtag}.part.minio`; + await fsp.mkdir(path.dirname(filePath), { + recursive: true + }); + let offset = 0; + try { + const stats = await fsp.stat(partFile); + if (objStat.size === stats.size) { + return partFile; + } + offset = stats.size; + partFileStream = fs.createWriteStream(partFile, { + flags: 'a' + }); + } catch (e) { + if (e instanceof Error && e.code === 'ENOENT') { + // file not exist + partFileStream = fs.createWriteStream(partFile, { + flags: 'w' + }); + } else { + // other error, maybe access deny + throw e; + } + } + const downloadStream = await this.getPartialObject(bucketName, objectName, offset, 0, getOpts); + await streamPromise.pipeline(downloadStream, partFileStream); + const stats = await fsp.stat(partFile); + if (stats.size === objStat.size) { + return partFile; + } + throw new Error('Size mismatch between downloaded file and the object'); + }; + const partFile = await downloadToTmpFile(); + await fsp.rename(partFile, filePath); + } + + /** + * Stat information of the object. + */ + async statObject(bucketName, objectName, statOpts) { + const statOptDef = statOpts || {}; + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!isObject(statOptDef)) { + throw new errors.InvalidArgumentError('statOpts should be of type "object"'); + } + const query = qs.stringify(statOptDef); + const method = 'HEAD'; + const res = await this.makeRequestAsyncOmit({ + method, + bucketName, + objectName, + query + }); + return { + size: parseInt(res.headers['content-length']), + metaData: extractMetadata(res.headers), + lastModified: new Date(res.headers['last-modified']), + versionId: getVersionId(res.headers), + etag: sanitizeETag(res.headers.etag) + }; + } + async removeObject(bucketName, objectName, removeOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (removeOpts && !isObject(removeOpts)) { + throw new errors.InvalidArgumentError('removeOpts should be of type "object"'); + } + const method = 'DELETE'; + const headers = {}; + if (removeOpts !== null && removeOpts !== void 0 && removeOpts.governanceBypass) { + headers['X-Amz-Bypass-Governance-Retention'] = true; + } + if (removeOpts !== null && removeOpts !== void 0 && removeOpts.forceDelete) { + headers['x-minio-force-delete'] = true; + } + const queryParams = {}; + if (removeOpts !== null && removeOpts !== void 0 && removeOpts.versionId) { + queryParams.versionId = `${removeOpts.versionId}`; + } + const query = qs.stringify(queryParams); + await this.makeRequestAsyncOmit({ + method, + bucketName, + objectName, + headers, + query + }, '', [200, 204]); + } + + // Calls implemented below are related to multipart. + + listIncompleteUploads(bucket, prefix, recursive) { + if (prefix === undefined) { + prefix = ''; + } + if (recursive === undefined) { + recursive = false; + } + if (!isValidBucketName(bucket)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucket); + } + if (!isValidPrefix(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`); + } + if (!isBoolean(recursive)) { + throw new TypeError('recursive should be of type "boolean"'); + } + const delimiter = recursive ? '' : '/'; + let keyMarker = ''; + let uploadIdMarker = ''; + const uploads = []; + let ended = false; + + // TODO: refactor this with async/await and `stream.Readable.from` + const readStream = new stream.Readable({ + objectMode: true + }); + readStream._read = () => { + // push one upload info per _read() + if (uploads.length) { + return readStream.push(uploads.shift()); + } + if (ended) { + return readStream.push(null); + } + this.listIncompleteUploadsQuery(bucket, prefix, keyMarker, uploadIdMarker, delimiter).then(result => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + result.prefixes.forEach(prefix => uploads.push(prefix)); + async.eachSeries(result.uploads, (upload, cb) => { + // for each incomplete upload add the sizes of its uploaded parts + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + this.listParts(bucket, upload.key, upload.uploadId).then(parts => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + upload.size = parts.reduce((acc, item) => acc + item.size, 0); + uploads.push(upload); + cb(); + }, err => cb(err)); + }, err => { + if (err) { + readStream.emit('error', err); + return; + } + if (result.isTruncated) { + keyMarker = result.nextKeyMarker; + uploadIdMarker = result.nextUploadIdMarker; + } else { + ended = true; + } + + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + readStream._read(); + }); + }, e => { + readStream.emit('error', e); + }); + }; + return readStream; + } + + /** + * Called by listIncompleteUploads to fetch a batch of incomplete uploads. + */ + async listIncompleteUploadsQuery(bucketName, prefix, keyMarker, uploadIdMarker, delimiter) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isString(prefix)) { + throw new TypeError('prefix should be of type "string"'); + } + if (!isString(keyMarker)) { + throw new TypeError('keyMarker should be of type "string"'); + } + if (!isString(uploadIdMarker)) { + throw new TypeError('uploadIdMarker should be of type "string"'); + } + if (!isString(delimiter)) { + throw new TypeError('delimiter should be of type "string"'); + } + const queries = []; + queries.push(`prefix=${uriEscape(prefix)}`); + queries.push(`delimiter=${uriEscape(delimiter)}`); + if (keyMarker) { + queries.push(`key-marker=${uriEscape(keyMarker)}`); + } + if (uploadIdMarker) { + queries.push(`upload-id-marker=${uploadIdMarker}`); + } + const maxUploads = 1000; + queries.push(`max-uploads=${maxUploads}`); + queries.sort(); + queries.unshift('uploads'); + let query = ''; + if (queries.length > 0) { + query = `${queries.join('&')}`; + } + const method = 'GET'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const body = await readAsString(res); + return xmlParsers.parseListMultipart(body); + } + + /** + * Initiate a new multipart upload. + * @internal + */ + async initiateNewMultipartUpload(bucketName, objectName, headers) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!isObject(headers)) { + throw new errors.InvalidObjectNameError('contentType should be of type "object"'); + } + const method = 'POST'; + const query = 'uploads'; + const res = await this.makeRequestAsync({ + method, + bucketName, + objectName, + query, + headers + }); + const body = await readAsBuffer(res); + return parseInitiateMultipart(body.toString()); + } + + /** + * Internal Method to abort a multipart upload request in case of any errors. + * + * @param bucketName - Bucket Name + * @param objectName - Object Name + * @param uploadId - id of a multipart upload to cancel during compose object sequence. + */ + async abortMultipartUpload(bucketName, objectName, uploadId) { + const method = 'DELETE'; + const query = `uploadId=${uploadId}`; + const requestOptions = { + method, + bucketName, + objectName: objectName, + query + }; + await this.makeRequestAsyncOmit(requestOptions, '', [204]); + } + async findUploadId(bucketName, objectName) { + var _latestUpload; + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + let latestUpload; + let keyMarker = ''; + let uploadIdMarker = ''; + for (;;) { + const result = await this.listIncompleteUploadsQuery(bucketName, objectName, keyMarker, uploadIdMarker, ''); + for (const upload of result.uploads) { + if (upload.key === objectName) { + if (!latestUpload || upload.initiated.getTime() > latestUpload.initiated.getTime()) { + latestUpload = upload; + } + } + } + if (result.isTruncated) { + keyMarker = result.nextKeyMarker; + uploadIdMarker = result.nextUploadIdMarker; + continue; + } + break; + } + return (_latestUpload = latestUpload) === null || _latestUpload === void 0 ? void 0 : _latestUpload.uploadId; + } + + /** + * this call will aggregate the parts on the server into a single object. + */ + async completeMultipartUpload(bucketName, objectName, uploadId, etags) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!isString(uploadId)) { + throw new TypeError('uploadId should be of type "string"'); + } + if (!isObject(etags)) { + throw new TypeError('etags should be of type "Array"'); + } + if (!uploadId) { + throw new errors.InvalidArgumentError('uploadId cannot be empty'); + } + const method = 'POST'; + const query = `uploadId=${uriEscape(uploadId)}`; + const builder = new xml2js.Builder(); + const payload = builder.buildObject({ + CompleteMultipartUpload: { + $: { + xmlns: 'http://s3.amazonaws.com/doc/2006-03-01/' + }, + Part: etags.map(etag => { + return { + PartNumber: etag.part, + ETag: etag.etag + }; + }) + } + }); + const res = await this.makeRequestAsync({ + method, + bucketName, + objectName, + query + }, payload); + const body = await readAsBuffer(res); + const result = parseCompleteMultipart(body.toString()); + if (!result) { + throw new Error('BUG: failed to parse server response'); + } + if (result.errCode) { + // Multipart Complete API returns an error XML after a 200 http status + throw new errors.S3Error(result.errMessage); + } + return { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + etag: result.etag, + versionId: getVersionId(res.headers) + }; + } + + /** + * Get part-info of all parts of an incomplete upload specified by uploadId. + */ + async listParts(bucketName, objectName, uploadId) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!isString(uploadId)) { + throw new TypeError('uploadId should be of type "string"'); + } + if (!uploadId) { + throw new errors.InvalidArgumentError('uploadId cannot be empty'); + } + const parts = []; + let marker = 0; + let result; + do { + result = await this.listPartsQuery(bucketName, objectName, uploadId, marker); + marker = result.marker; + parts.push(...result.parts); + } while (result.isTruncated); + return parts; + } + + /** + * Called by listParts to fetch a batch of part-info + */ + async listPartsQuery(bucketName, objectName, uploadId, marker) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!isString(uploadId)) { + throw new TypeError('uploadId should be of type "string"'); + } + if (!isNumber(marker)) { + throw new TypeError('marker should be of type "number"'); + } + if (!uploadId) { + throw new errors.InvalidArgumentError('uploadId cannot be empty'); + } + let query = `uploadId=${uriEscape(uploadId)}`; + if (marker) { + query += `&part-number-marker=${marker}`; + } + const method = 'GET'; + const res = await this.makeRequestAsync({ + method, + bucketName, + objectName, + query + }); + return xmlParsers.parseListParts(await readAsString(res)); + } + async listBuckets() { + const method = 'GET'; + const regionConf = this.region || DEFAULT_REGION; + const httpRes = await this.makeRequestAsync({ + method + }, '', [200], regionConf); + const xmlResult = await readAsString(httpRes); + return xmlParsers.parseListBucket(xmlResult); + } + + /** + * Calculate part size given the object size. Part size will be atleast this.partSize + */ + calculatePartSize(size) { + if (!isNumber(size)) { + throw new TypeError('size should be of type "number"'); + } + if (size > this.maxObjectSize) { + throw new TypeError(`size should not be more than ${this.maxObjectSize}`); + } + if (this.overRidePartSize) { + return this.partSize; + } + let partSize = this.partSize; + for (;;) { + // while(true) {...} throws linting error. + // If partSize is big enough to accomodate the object size, then use it. + if (partSize * 10000 > size) { + return partSize; + } + // Try part sizes as 64MB, 80MB, 96MB etc. + partSize += 16 * 1024 * 1024; + } + } + + /** + * Uploads the object using contents from a file + */ + async fPutObject(bucketName, objectName, filePath, metaData) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!isString(filePath)) { + throw new TypeError('filePath should be of type "string"'); + } + if (metaData && !isObject(metaData)) { + throw new TypeError('metaData should be of type "object"'); + } + + // Inserts correct `content-type` attribute based on metaData and filePath + metaData = insertContentType(metaData || {}, filePath); + const stat = await fsp.stat(filePath); + return await this.putObject(bucketName, objectName, fs.createReadStream(filePath), stat.size, metaData); + } + + /** + * Uploading a stream, "Buffer" or "string". + * It's recommended to pass `size` argument with stream. + */ + async putObject(bucketName, objectName, stream, size, metaData) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + + // We'll need to shift arguments to the left because of metaData + // and size being optional. + if (isObject(size)) { + metaData = size; + } + // Ensures Metadata has appropriate prefix for A3 API + const headers = prependXAMZMeta(metaData); + if (typeof stream === 'string' || stream instanceof Buffer) { + // Adapts the non-stream interface into a stream. + size = stream.length; + stream = readableStream(stream); + } else if (!isReadableStream(stream)) { + throw new TypeError('third argument should be of type "stream.Readable" or "Buffer" or "string"'); + } + if (isNumber(size) && size < 0) { + throw new errors.InvalidArgumentError(`size cannot be negative, given size: ${size}`); + } + + // Get the part size and forward that to the BlockStream. Default to the + // largest block size possible if necessary. + if (!isNumber(size)) { + size = this.maxObjectSize; + } + + // Get the part size and forward that to the BlockStream. Default to the + // largest block size possible if necessary. + if (size === undefined) { + const statSize = await getContentLength(stream); + if (statSize !== null) { + size = statSize; + } + } + if (!isNumber(size)) { + // Backward compatibility + size = this.maxObjectSize; + } + if (size === 0) { + return this.uploadBuffer(bucketName, objectName, headers, Buffer.from('')); + } + const partSize = this.calculatePartSize(size); + if (typeof stream === 'string' || Buffer.isBuffer(stream) || size <= partSize) { + const buf = isReadableStream(stream) ? await readAsBuffer(stream) : Buffer.from(stream); + return this.uploadBuffer(bucketName, objectName, headers, buf); + } + return this.uploadStream(bucketName, objectName, headers, stream, partSize); + } + + /** + * method to upload buffer in one call + * @private + */ + async uploadBuffer(bucketName, objectName, headers, buf) { + const { + md5sum, + sha256sum + } = hashBinary(buf, this.enableSHA256); + headers['Content-Length'] = buf.length; + if (!this.enableSHA256) { + headers['Content-MD5'] = md5sum; + } + const res = await this.makeRequestStreamAsync({ + method: 'PUT', + bucketName, + objectName, + headers + }, buf, sha256sum, [200], ''); + await drainResponse(res); + return { + etag: sanitizeETag(res.headers.etag), + versionId: getVersionId(res.headers) + }; + } + + /** + * upload stream with MultipartUpload + * @private + */ + async uploadStream(bucketName, objectName, headers, body, partSize) { + // A map of the previously uploaded chunks, for resuming a file upload. This + // will be null if we aren't resuming an upload. + const oldParts = {}; + + // Keep track of the etags for aggregating the chunks together later. Each + // etag represents a single chunk of the file. + const eTags = []; + const previousUploadId = await this.findUploadId(bucketName, objectName); + let uploadId; + if (!previousUploadId) { + uploadId = await this.initiateNewMultipartUpload(bucketName, objectName, headers); + } else { + uploadId = previousUploadId; + const oldTags = await this.listParts(bucketName, objectName, previousUploadId); + oldTags.forEach(e => { + oldParts[e.part] = e; + }); + } + const chunkier = new BlockStream2({ + size: partSize, + zeroPadding: false + }); + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const [_, o] = await Promise.all([new Promise((resolve, reject) => { + body.pipe(chunkier).on('error', reject); + chunkier.on('end', resolve).on('error', reject); + }), (async () => { + let partNumber = 1; + for await (const chunk of chunkier) { + const md5 = crypto.createHash('md5').update(chunk).digest(); + const oldPart = oldParts[partNumber]; + if (oldPart) { + if (oldPart.etag === md5.toString('hex')) { + eTags.push({ + part: partNumber, + etag: oldPart.etag + }); + partNumber++; + continue; + } + } + partNumber++; + + // now start to upload missing part + const options = { + method: 'PUT', + query: qs.stringify({ + partNumber, + uploadId + }), + headers: { + 'Content-Length': chunk.length, + 'Content-MD5': md5.toString('base64') + }, + bucketName, + objectName + }; + const response = await this.makeRequestAsyncOmit(options, chunk); + let etag = response.headers.etag; + if (etag) { + etag = etag.replace(/^"/, '').replace(/"$/, ''); + } else { + etag = ''; + } + eTags.push({ + part: partNumber, + etag + }); + } + return await this.completeMultipartUpload(bucketName, objectName, uploadId, eTags); + })()]); + return o; + } + async removeBucketReplication(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'DELETE'; + const query = 'replication'; + await this.makeRequestAsyncOmit({ + method, + bucketName, + query + }, '', [200, 204], ''); + } + async setBucketReplication(bucketName, replicationConfig) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isObject(replicationConfig)) { + throw new errors.InvalidArgumentError('replicationConfig should be of type "object"'); + } else { + if (_.isEmpty(replicationConfig.role)) { + throw new errors.InvalidArgumentError('Role cannot be empty'); + } else if (replicationConfig.role && !isString(replicationConfig.role)) { + throw new errors.InvalidArgumentError('Invalid value for role', replicationConfig.role); + } + if (_.isEmpty(replicationConfig.rules)) { + throw new errors.InvalidArgumentError('Minimum one replication rule must be specified'); + } + } + const method = 'PUT'; + const query = 'replication'; + const headers = {}; + const replicationParamsConfig = { + ReplicationConfiguration: { + Role: replicationConfig.role, + Rule: replicationConfig.rules + } + }; + const builder = new xml2js.Builder({ + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(replicationParamsConfig); + headers['Content-MD5'] = toMd5(payload); + await this.makeRequestAsyncOmit({ + method, + bucketName, + query, + headers + }, payload); + } + async getBucketReplication(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'GET'; + const query = 'replication'; + const httpRes = await this.makeRequestAsync({ + method, + bucketName, + query + }, '', [200, 204]); + const xmlResult = await readAsString(httpRes); + return xmlParsers.parseReplicationConfig(xmlResult); + } + async getObjectLegalHold(bucketName, objectName, getOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (getOpts) { + if (!isObject(getOpts)) { + throw new TypeError('getOpts should be of type "Object"'); + } else if (Object.keys(getOpts).length > 0 && getOpts.versionId && !isString(getOpts.versionId)) { + throw new TypeError('versionId should be of type string.:', getOpts.versionId); + } + } + const method = 'GET'; + let query = 'legal-hold'; + if (getOpts !== null && getOpts !== void 0 && getOpts.versionId) { + query += `&versionId=${getOpts.versionId}`; + } + const httpRes = await this.makeRequestAsync({ + method, + bucketName, + objectName, + query + }, '', [200]); + const strRes = await readAsString(httpRes); + return parseObjectLegalHoldConfig(strRes); + } + async setObjectLegalHold(bucketName, objectName, setOpts = { + status: LEGAL_HOLD_STATUS.ENABLED + }) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!isObject(setOpts)) { + throw new TypeError('setOpts should be of type "Object"'); + } else { + if (![LEGAL_HOLD_STATUS.ENABLED, LEGAL_HOLD_STATUS.DISABLED].includes(setOpts === null || setOpts === void 0 ? void 0 : setOpts.status)) { + throw new TypeError('Invalid status: ' + setOpts.status); + } + if (setOpts.versionId && !setOpts.versionId.length) { + throw new TypeError('versionId should be of type string.:' + setOpts.versionId); + } + } + const method = 'PUT'; + let query = 'legal-hold'; + if (setOpts.versionId) { + query += `&versionId=${setOpts.versionId}`; + } + const config = { + Status: setOpts.status + }; + const builder = new xml2js.Builder({ + rootName: 'LegalHold', + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(config); + const headers = {}; + headers['Content-MD5'] = toMd5(payload); + await this.makeRequestAsyncOmit({ + method, + bucketName, + objectName, + query, + headers + }, payload); + } + + /** + * Get Tags associated with a Bucket + */ + async getBucketTagging(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + const method = 'GET'; + const query = 'tagging'; + const requestOptions = { + method, + bucketName, + query + }; + const response = await this.makeRequestAsync(requestOptions); + const body = await readAsString(response); + return xmlParsers.parseTagging(body); + } + + /** + * Get the tags associated with a bucket OR an object + */ + async getObjectTagging(bucketName, objectName, getOpts) { + const method = 'GET'; + let query = 'tagging'; + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidBucketNameError('Invalid object name: ' + objectName); + } + if (getOpts && !isObject(getOpts)) { + throw new errors.InvalidArgumentError('getOpts should be of type "object"'); + } + if (getOpts && getOpts.versionId) { + query = `${query}&versionId=${getOpts.versionId}`; + } + const requestOptions = { + method, + bucketName, + query + }; + if (objectName) { + requestOptions['objectName'] = objectName; + } + const response = await this.makeRequestAsync(requestOptions); + const body = await readAsString(response); + return xmlParsers.parseTagging(body); + } + + /** + * Set the policy on a bucket or an object prefix. + */ + async setBucketPolicy(bucketName, policy) { + // Validate arguments. + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!isString(policy)) { + throw new errors.InvalidBucketPolicyError(`Invalid bucket policy: ${policy} - must be "string"`); + } + const query = 'policy'; + let method = 'DELETE'; + if (policy) { + method = 'PUT'; + } + await this.makeRequestAsyncOmit({ + method, + bucketName, + query + }, policy, [204], ''); + } + + /** + * Get the policy on a bucket or an object prefix. + */ + async getBucketPolicy(bucketName) { + // Validate arguments. + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + const method = 'GET'; + const query = 'policy'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + return await readAsString(res); + } + async putObjectRetention(bucketName, objectName, retentionOpts = {}) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!isObject(retentionOpts)) { + throw new errors.InvalidArgumentError('retentionOpts should be of type "object"'); + } else { + if (retentionOpts.governanceBypass && !isBoolean(retentionOpts.governanceBypass)) { + throw new errors.InvalidArgumentError(`Invalid value for governanceBypass: ${retentionOpts.governanceBypass}`); + } + if (retentionOpts.mode && ![RETENTION_MODES.COMPLIANCE, RETENTION_MODES.GOVERNANCE].includes(retentionOpts.mode)) { + throw new errors.InvalidArgumentError(`Invalid object retention mode: ${retentionOpts.mode}`); + } + if (retentionOpts.retainUntilDate && !isString(retentionOpts.retainUntilDate)) { + throw new errors.InvalidArgumentError(`Invalid value for retainUntilDate: ${retentionOpts.retainUntilDate}`); + } + if (retentionOpts.versionId && !isString(retentionOpts.versionId)) { + throw new errors.InvalidArgumentError(`Invalid value for versionId: ${retentionOpts.versionId}`); + } + } + const method = 'PUT'; + let query = 'retention'; + const headers = {}; + if (retentionOpts.governanceBypass) { + headers['X-Amz-Bypass-Governance-Retention'] = true; + } + const builder = new xml2js.Builder({ + rootName: 'Retention', + renderOpts: { + pretty: false + }, + headless: true + }); + const params = {}; + if (retentionOpts.mode) { + params.Mode = retentionOpts.mode; + } + if (retentionOpts.retainUntilDate) { + params.RetainUntilDate = retentionOpts.retainUntilDate; + } + if (retentionOpts.versionId) { + query += `&versionId=${retentionOpts.versionId}`; + } + const payload = builder.buildObject(params); + headers['Content-MD5'] = toMd5(payload); + await this.makeRequestAsyncOmit({ + method, + bucketName, + objectName, + query, + headers + }, payload, [200, 204]); + } + async getObjectLockConfig(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'GET'; + const query = 'object-lock'; + const httpRes = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const xmlResult = await readAsString(httpRes); + return xmlParsers.parseObjectLockConfig(xmlResult); + } + async setObjectLockConfig(bucketName, lockConfigOpts) { + const retentionModes = [RETENTION_MODES.COMPLIANCE, RETENTION_MODES.GOVERNANCE]; + const validUnits = [RETENTION_VALIDITY_UNITS.DAYS, RETENTION_VALIDITY_UNITS.YEARS]; + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (lockConfigOpts.mode && !retentionModes.includes(lockConfigOpts.mode)) { + throw new TypeError(`lockConfigOpts.mode should be one of ${retentionModes}`); + } + if (lockConfigOpts.unit && !validUnits.includes(lockConfigOpts.unit)) { + throw new TypeError(`lockConfigOpts.unit should be one of ${validUnits}`); + } + if (lockConfigOpts.validity && !isNumber(lockConfigOpts.validity)) { + throw new TypeError(`lockConfigOpts.validity should be a number`); + } + const method = 'PUT'; + const query = 'object-lock'; + const config = { + ObjectLockEnabled: 'Enabled' + }; + const configKeys = Object.keys(lockConfigOpts); + const isAllKeysSet = ['unit', 'mode', 'validity'].every(lck => configKeys.includes(lck)); + // Check if keys are present and all keys are present. + if (configKeys.length > 0) { + if (!isAllKeysSet) { + throw new TypeError(`lockConfigOpts.mode,lockConfigOpts.unit,lockConfigOpts.validity all the properties should be specified.`); + } else { + config.Rule = { + DefaultRetention: {} + }; + if (lockConfigOpts.mode) { + config.Rule.DefaultRetention.Mode = lockConfigOpts.mode; + } + if (lockConfigOpts.unit === RETENTION_VALIDITY_UNITS.DAYS) { + config.Rule.DefaultRetention.Days = lockConfigOpts.validity; + } else if (lockConfigOpts.unit === RETENTION_VALIDITY_UNITS.YEARS) { + config.Rule.DefaultRetention.Years = lockConfigOpts.validity; + } + } + } + const builder = new xml2js.Builder({ + rootName: 'ObjectLockConfiguration', + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(config); + const headers = {}; + headers['Content-MD5'] = toMd5(payload); + await this.makeRequestAsyncOmit({ + method, + bucketName, + query, + headers + }, payload); + } + async getBucketVersioning(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'GET'; + const query = 'versioning'; + const httpRes = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const xmlResult = await readAsString(httpRes); + return await xmlParsers.parseBucketVersioningConfig(xmlResult); + } + async setBucketVersioning(bucketName, versionConfig) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!Object.keys(versionConfig).length) { + throw new errors.InvalidArgumentError('versionConfig should be of type "object"'); + } + const method = 'PUT'; + const query = 'versioning'; + const builder = new xml2js.Builder({ + rootName: 'VersioningConfiguration', + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(versionConfig); + await this.makeRequestAsyncOmit({ + method, + bucketName, + query + }, payload); + } + async setTagging(taggingParams) { + const { + bucketName, + objectName, + tags, + putOpts + } = taggingParams; + const method = 'PUT'; + let query = 'tagging'; + if (putOpts && putOpts !== null && putOpts !== void 0 && putOpts.versionId) { + query = `${query}&versionId=${putOpts.versionId}`; + } + const tagsList = []; + for (const [key, value] of Object.entries(tags)) { + tagsList.push({ + Key: key, + Value: value + }); + } + const taggingConfig = { + Tagging: { + TagSet: { + Tag: tagsList + } + } + }; + const headers = {}; + const builder = new xml2js.Builder({ + headless: true, + renderOpts: { + pretty: false + } + }); + const payloadBuf = Buffer.from(builder.buildObject(taggingConfig)); + const requestOptions = { + method, + bucketName, + query, + headers, + ...(objectName && { + objectName: objectName + }) + }; + headers['Content-MD5'] = toMd5(payloadBuf); + await this.makeRequestAsyncOmit(requestOptions, payloadBuf); + } + async removeTagging({ + bucketName, + objectName, + removeOpts + }) { + const method = 'DELETE'; + let query = 'tagging'; + if (removeOpts && Object.keys(removeOpts).length && removeOpts.versionId) { + query = `${query}&versionId=${removeOpts.versionId}`; + } + const requestOptions = { + method, + bucketName, + objectName, + query + }; + if (objectName) { + requestOptions['objectName'] = objectName; + } + await this.makeRequestAsync(requestOptions, '', [200, 204]); + } + async setBucketTagging(bucketName, tags) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isPlainObject(tags)) { + throw new errors.InvalidArgumentError('tags should be of type "object"'); + } + if (Object.keys(tags).length > 10) { + throw new errors.InvalidArgumentError('maximum tags allowed is 10"'); + } + await this.setTagging({ + bucketName, + tags + }); + } + async removeBucketTagging(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + await this.removeTagging({ + bucketName + }); + } + async setObjectTagging(bucketName, objectName, tags, putOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidBucketNameError('Invalid object name: ' + objectName); + } + if (!isPlainObject(tags)) { + throw new errors.InvalidArgumentError('tags should be of type "object"'); + } + if (Object.keys(tags).length > 10) { + throw new errors.InvalidArgumentError('Maximum tags allowed is 10"'); + } + await this.setTagging({ + bucketName, + objectName, + tags, + putOpts + }); + } + async removeObjectTagging(bucketName, objectName, removeOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidBucketNameError('Invalid object name: ' + objectName); + } + if (removeOpts && Object.keys(removeOpts).length && !isObject(removeOpts)) { + throw new errors.InvalidArgumentError('removeOpts should be of type "object"'); + } + await this.removeTagging({ + bucketName, + objectName, + removeOpts + }); + } + async selectObjectContent(bucketName, objectName, selectOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!_.isEmpty(selectOpts)) { + if (!isString(selectOpts.expression)) { + throw new TypeError('sqlExpression should be of type "string"'); + } + if (!_.isEmpty(selectOpts.inputSerialization)) { + if (!isObject(selectOpts.inputSerialization)) { + throw new TypeError('inputSerialization should be of type "object"'); + } + } else { + throw new TypeError('inputSerialization is required'); + } + if (!_.isEmpty(selectOpts.outputSerialization)) { + if (!isObject(selectOpts.outputSerialization)) { + throw new TypeError('outputSerialization should be of type "object"'); + } + } else { + throw new TypeError('outputSerialization is required'); + } + } else { + throw new TypeError('valid select configuration is required'); + } + const method = 'POST'; + const query = `select&select-type=2`; + const config = [{ + Expression: selectOpts.expression + }, { + ExpressionType: selectOpts.expressionType || 'SQL' + }, { + InputSerialization: [selectOpts.inputSerialization] + }, { + OutputSerialization: [selectOpts.outputSerialization] + }]; + + // Optional + if (selectOpts.requestProgress) { + config.push({ + RequestProgress: selectOpts === null || selectOpts === void 0 ? void 0 : selectOpts.requestProgress + }); + } + // Optional + if (selectOpts.scanRange) { + config.push({ + ScanRange: selectOpts.scanRange + }); + } + const builder = new xml2js.Builder({ + rootName: 'SelectObjectContentRequest', + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(config); + const res = await this.makeRequestAsync({ + method, + bucketName, + objectName, + query + }, payload); + const body = await readAsBuffer(res); + return parseSelectObjectContentResponse(body); + } + async applyBucketLifecycle(bucketName, policyConfig) { + const method = 'PUT'; + const query = 'lifecycle'; + const headers = {}; + const builder = new xml2js.Builder({ + rootName: 'LifecycleConfiguration', + headless: true, + renderOpts: { + pretty: false + } + }); + const payload = builder.buildObject(policyConfig); + headers['Content-MD5'] = toMd5(payload); + await this.makeRequestAsyncOmit({ + method, + bucketName, + query, + headers + }, payload); + } + async removeBucketLifecycle(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'DELETE'; + const query = 'lifecycle'; + await this.makeRequestAsyncOmit({ + method, + bucketName, + query + }, '', [204]); + } + async setBucketLifecycle(bucketName, lifeCycleConfig) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (_.isEmpty(lifeCycleConfig)) { + await this.removeBucketLifecycle(bucketName); + } else { + await this.applyBucketLifecycle(bucketName, lifeCycleConfig); + } + } + async getBucketLifecycle(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'GET'; + const query = 'lifecycle'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const body = await readAsString(res); + return xmlParsers.parseLifecycleConfig(body); + } + async setBucketEncryption(bucketName, encryptionConfig) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!_.isEmpty(encryptionConfig) && encryptionConfig.Rule.length > 1) { + throw new errors.InvalidArgumentError('Invalid Rule length. Only one rule is allowed.: ' + encryptionConfig.Rule); + } + let encryptionObj = encryptionConfig; + if (_.isEmpty(encryptionConfig)) { + encryptionObj = { + // Default MinIO Server Supported Rule + Rule: [{ + ApplyServerSideEncryptionByDefault: { + SSEAlgorithm: 'AES256' + } + }] + }; + } + const method = 'PUT'; + const query = 'encryption'; + const builder = new xml2js.Builder({ + rootName: 'ServerSideEncryptionConfiguration', + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(encryptionObj); + const headers = {}; + headers['Content-MD5'] = toMd5(payload); + await this.makeRequestAsyncOmit({ + method, + bucketName, + query, + headers + }, payload); + } + async getBucketEncryption(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'GET'; + const query = 'encryption'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const body = await readAsString(res); + return xmlParsers.parseBucketEncryptionConfig(body); + } + async removeBucketEncryption(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'DELETE'; + const query = 'encryption'; + await this.makeRequestAsyncOmit({ + method, + bucketName, + query + }, '', [204]); + } + async getObjectRetention(bucketName, objectName, getOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (getOpts && !isObject(getOpts)) { + throw new errors.InvalidArgumentError('getOpts should be of type "object"'); + } else if (getOpts !== null && getOpts !== void 0 && getOpts.versionId && !isString(getOpts.versionId)) { + throw new errors.InvalidArgumentError('versionId should be of type "string"'); + } + const method = 'GET'; + let query = 'retention'; + if (getOpts !== null && getOpts !== void 0 && getOpts.versionId) { + query += `&versionId=${getOpts.versionId}`; + } + const res = await this.makeRequestAsync({ + method, + bucketName, + objectName, + query + }); + const body = await readAsString(res); + return xmlParsers.parseObjectRetentionConfig(body); + } + async removeObjects(bucketName, objectsList) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!Array.isArray(objectsList)) { + throw new errors.InvalidArgumentError('objectsList should be a list'); + } + const runDeleteObjects = async batch => { + const delObjects = batch.map(value => { + return isObject(value) ? { + Key: value.name, + VersionId: value.versionId + } : { + Key: value + }; + }); + const remObjects = { + Delete: { + Quiet: true, + Object: delObjects + } + }; + const payload = Buffer.from(new xml2js.Builder({ + headless: true + }).buildObject(remObjects)); + const headers = { + 'Content-MD5': toMd5(payload) + }; + const res = await this.makeRequestAsync({ + method: 'POST', + bucketName, + query: 'delete', + headers + }, payload); + const body = await readAsString(res); + return xmlParsers.removeObjectsParser(body); + }; + const maxEntries = 1000; // max entries accepted in server for DeleteMultipleObjects API. + // Client side batching + const batches = []; + for (let i = 0; i < objectsList.length; i += maxEntries) { + batches.push(objectsList.slice(i, i + maxEntries)); + } + const batchResults = await Promise.all(batches.map(runDeleteObjects)); + return batchResults.flat(); + } + async removeIncompleteUpload(bucketName, objectName) { + if (!isValidBucketName(bucketName)) { + throw new errors.IsValidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + const removeUploadId = await this.findUploadId(bucketName, objectName); + const method = 'DELETE'; + const query = `uploadId=${removeUploadId}`; + await this.makeRequestAsyncOmit({ + method, + bucketName, + objectName, + query + }, '', [204]); + } + async copyObjectV1(targetBucketName, targetObjectName, sourceBucketNameAndObjectName, conditions) { + if (typeof conditions == 'function') { + conditions = null; + } + if (!isValidBucketName(targetBucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + targetBucketName); + } + if (!isValidObjectName(targetObjectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${targetObjectName}`); + } + if (!isString(sourceBucketNameAndObjectName)) { + throw new TypeError('sourceBucketNameAndObjectName should be of type "string"'); + } + if (sourceBucketNameAndObjectName === '') { + throw new errors.InvalidPrefixError(`Empty source prefix`); + } + if (conditions != null && !(conditions instanceof CopyConditions)) { + throw new TypeError('conditions should be of type "CopyConditions"'); + } + const headers = {}; + headers['x-amz-copy-source'] = uriResourceEscape(sourceBucketNameAndObjectName); + if (conditions) { + if (conditions.modified !== '') { + headers['x-amz-copy-source-if-modified-since'] = conditions.modified; + } + if (conditions.unmodified !== '') { + headers['x-amz-copy-source-if-unmodified-since'] = conditions.unmodified; + } + if (conditions.matchETag !== '') { + headers['x-amz-copy-source-if-match'] = conditions.matchETag; + } + if (conditions.matchETagExcept !== '') { + headers['x-amz-copy-source-if-none-match'] = conditions.matchETagExcept; + } + } + const method = 'PUT'; + const res = await this.makeRequestAsync({ + method, + bucketName: targetBucketName, + objectName: targetObjectName, + headers + }); + const body = await readAsString(res); + return xmlParsers.parseCopyObject(body); + } + async copyObjectV2(sourceConfig, destConfig) { + if (!(sourceConfig instanceof CopySourceOptions)) { + throw new errors.InvalidArgumentError('sourceConfig should of type CopySourceOptions '); + } + if (!(destConfig instanceof CopyDestinationOptions)) { + throw new errors.InvalidArgumentError('destConfig should of type CopyDestinationOptions '); + } + if (!destConfig.validate()) { + return Promise.reject(); + } + if (!destConfig.validate()) { + return Promise.reject(); + } + const headers = Object.assign({}, sourceConfig.getHeaders(), destConfig.getHeaders()); + const bucketName = destConfig.Bucket; + const objectName = destConfig.Object; + const method = 'PUT'; + const res = await this.makeRequestAsync({ + method, + bucketName, + objectName, + headers + }); + const body = await readAsString(res); + const copyRes = xmlParsers.parseCopyObject(body); + const resHeaders = res.headers; + const sizeHeaderValue = resHeaders && resHeaders['content-length']; + const size = typeof sizeHeaderValue === 'number' ? sizeHeaderValue : undefined; + return { + Bucket: destConfig.Bucket, + Key: destConfig.Object, + LastModified: copyRes.lastModified, + MetaData: extractMetadata(resHeaders), + VersionId: getVersionId(resHeaders), + SourceVersionId: getSourceVersionId(resHeaders), + Etag: sanitizeETag(resHeaders.etag), + Size: size + }; + } + async copyObject(...allArgs) { + if (typeof allArgs[0] === 'string') { + const [targetBucketName, targetObjectName, sourceBucketNameAndObjectName, conditions] = allArgs; + return await this.copyObjectV1(targetBucketName, targetObjectName, sourceBucketNameAndObjectName, conditions); + } + const [source, dest] = allArgs; + return await this.copyObjectV2(source, dest); + } + async uploadPart(partConfig, payload) { + const { + bucketName, + objectName, + uploadID, + partNumber, + headers + } = partConfig; + const method = 'PUT'; + const query = `uploadId=${uploadID}&partNumber=${partNumber}`; + const requestOptions = { + method, + bucketName, + objectName: objectName, + query, + headers + }; + const res = await this.makeRequestAsync(requestOptions, payload); + const body = await readAsString(res); + const partRes = uploadPartParser(body); + const partEtagVal = sanitizeETag(res.headers.etag) || sanitizeETag(partRes.ETag); + return { + etag: partEtagVal, + key: objectName, + part: partNumber + }; + } + async composeObject(destObjConfig, sourceObjList, { + maxConcurrency = 10 + } = {}) { + const sourceFilesLength = sourceObjList.length; + if (!Array.isArray(sourceObjList)) { + throw new errors.InvalidArgumentError('sourceConfig should an array of CopySourceOptions '); + } + if (!(destObjConfig instanceof CopyDestinationOptions)) { + throw new errors.InvalidArgumentError('destConfig should of type CopyDestinationOptions '); + } + if (sourceFilesLength < 1 || sourceFilesLength > PART_CONSTRAINTS.MAX_PARTS_COUNT) { + throw new errors.InvalidArgumentError(`"There must be as least one and up to ${PART_CONSTRAINTS.MAX_PARTS_COUNT} source objects.`); + } + for (let i = 0; i < sourceFilesLength; i++) { + const sObj = sourceObjList[i]; + if (!sObj.validate()) { + return false; + } + } + if (!destObjConfig.validate()) { + return false; + } + const getStatOptions = srcConfig => { + let statOpts = {}; + if (!_.isEmpty(srcConfig.VersionID)) { + statOpts = { + versionId: srcConfig.VersionID + }; + } + return statOpts; + }; + const srcObjectSizes = []; + let totalSize = 0; + let totalParts = 0; + const sourceObjStats = sourceObjList.map(srcItem => this.statObject(srcItem.Bucket, srcItem.Object, getStatOptions(srcItem))); + const srcObjectInfos = await Promise.all(sourceObjStats); + const validatedStats = srcObjectInfos.map((resItemStat, index) => { + const srcConfig = sourceObjList[index]; + let srcCopySize = resItemStat.size; + // Check if a segment is specified, and if so, is the + // segment within object bounds? + if (srcConfig && srcConfig.MatchRange) { + // Since range is specified, + // 0 <= src.srcStart <= src.srcEnd + // so only invalid case to check is: + const srcStart = srcConfig.Start; + const srcEnd = srcConfig.End; + if (srcEnd >= srcCopySize || srcStart < 0) { + throw new errors.InvalidArgumentError(`CopySrcOptions ${index} has invalid segment-to-copy [${srcStart}, ${srcEnd}] (size is ${srcCopySize})`); + } + srcCopySize = srcEnd - srcStart + 1; + } + + // Only the last source may be less than `absMinPartSize` + if (srcCopySize < PART_CONSTRAINTS.ABS_MIN_PART_SIZE && index < sourceFilesLength - 1) { + throw new errors.InvalidArgumentError(`CopySrcOptions ${index} is too small (${srcCopySize}) and it is not the last part.`); + } + + // Is data to copy too large? + totalSize += srcCopySize; + if (totalSize > PART_CONSTRAINTS.MAX_MULTIPART_PUT_OBJECT_SIZE) { + throw new errors.InvalidArgumentError(`Cannot compose an object of size ${totalSize} (> 5TiB)`); + } + + // record source size + srcObjectSizes[index] = srcCopySize; + + // calculate parts needed for current source + totalParts += partsRequired(srcCopySize); + // Do we need more parts than we are allowed? + if (totalParts > PART_CONSTRAINTS.MAX_PARTS_COUNT) { + throw new errors.InvalidArgumentError(`Your proposed compose object requires more than ${PART_CONSTRAINTS.MAX_PARTS_COUNT} parts`); + } + return resItemStat; + }); + if (totalParts === 1 && totalSize <= PART_CONSTRAINTS.MAX_PART_SIZE || totalSize === 0) { + return await this.copyObject(sourceObjList[0], destObjConfig); // use copyObjectV2 + } + + // preserve etag to avoid modification of object while copying. + for (let i = 0; i < sourceFilesLength; i++) { + ; + sourceObjList[i].MatchETag = validatedStats[i].etag; + } + const splitPartSizeList = validatedStats.map((resItemStat, idx) => { + return calculateEvenSplits(srcObjectSizes[idx], sourceObjList[idx]); + }); + const getUploadPartConfigList = uploadId => { + const uploadPartConfigList = []; + splitPartSizeList.forEach((splitSize, splitIndex) => { + if (splitSize) { + const { + startIndex: startIdx, + endIndex: endIdx, + objInfo: objConfig + } = splitSize; + const partIndex = splitIndex + 1; // part index starts from 1. + const totalUploads = Array.from(startIdx); + const headers = sourceObjList[splitIndex].getHeaders(); + totalUploads.forEach((splitStart, upldCtrIdx) => { + const splitEnd = endIdx[upldCtrIdx]; + const sourceObj = `${objConfig.Bucket}/${objConfig.Object}`; + headers['x-amz-copy-source'] = `${sourceObj}`; + headers['x-amz-copy-source-range'] = `bytes=${splitStart}-${splitEnd}`; + const uploadPartConfig = { + bucketName: destObjConfig.Bucket, + objectName: destObjConfig.Object, + uploadID: uploadId, + partNumber: partIndex, + headers: headers, + sourceObj: sourceObj + }; + uploadPartConfigList.push(uploadPartConfig); + }); + } + }); + return uploadPartConfigList; + }; + const uploadAllParts = async uploadList => { + const partUploads = []; + + // Process upload parts in batches to avoid too many concurrent requests + for (const batch of _.chunk(uploadList, maxConcurrency)) { + const batchResults = await Promise.all(batch.map(item => this.uploadPart(item))); + partUploads.push(...batchResults); + } + + // Process results here if needed + return partUploads; + }; + const performUploadParts = async uploadId => { + const uploadList = getUploadPartConfigList(uploadId); + const partsRes = await uploadAllParts(uploadList); + return partsRes.map(partCopy => ({ + etag: partCopy.etag, + part: partCopy.part + })); + }; + const newUploadHeaders = destObjConfig.getHeaders(); + const uploadId = await this.initiateNewMultipartUpload(destObjConfig.Bucket, destObjConfig.Object, newUploadHeaders); + try { + const partsDone = await performUploadParts(uploadId); + return await this.completeMultipartUpload(destObjConfig.Bucket, destObjConfig.Object, uploadId, partsDone); + } catch (err) { + return await this.abortMultipartUpload(destObjConfig.Bucket, destObjConfig.Object, uploadId); + } + } + async presignedUrl(method, bucketName, objectName, expires, reqParams, requestDate) { + var _requestDate; + if (this.anonymous) { + throw new errors.AnonymousRequestError(`Presigned ${method} url cannot be generated for anonymous requests`); + } + if (!expires) { + expires = PRESIGN_EXPIRY_DAYS_MAX; + } + if (!reqParams) { + reqParams = {}; + } + if (!requestDate) { + requestDate = new Date(); + } + + // Type assertions + if (expires && typeof expires !== 'number') { + throw new TypeError('expires should be of type "number"'); + } + if (reqParams && typeof reqParams !== 'object') { + throw new TypeError('reqParams should be of type "object"'); + } + if (requestDate && !(requestDate instanceof Date) || requestDate && isNaN((_requestDate = requestDate) === null || _requestDate === void 0 ? void 0 : _requestDate.getTime())) { + throw new TypeError('requestDate should be of type "Date" and valid'); + } + const query = reqParams ? qs.stringify(reqParams) : undefined; + try { + const region = await this.getBucketRegionAsync(bucketName); + await this.checkAndRefreshCreds(); + const reqOptions = this.getRequestOptions({ + method, + region, + bucketName, + objectName, + query + }); + return presignSignatureV4(reqOptions, this.accessKey, this.secretKey, this.sessionToken, region, requestDate, expires); + } catch (err) { + if (err instanceof errors.InvalidBucketNameError) { + throw new errors.InvalidArgumentError(`Unable to get bucket region for ${bucketName}.`); + } + throw err; + } + } + async presignedGetObject(bucketName, objectName, expires, respHeaders, requestDate) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + const validRespHeaders = ['response-content-type', 'response-content-language', 'response-expires', 'response-cache-control', 'response-content-disposition', 'response-content-encoding']; + validRespHeaders.forEach(header => { + // @ts-ignore + if (respHeaders !== undefined && respHeaders[header] !== undefined && !isString(respHeaders[header])) { + throw new TypeError(`response header ${header} should be of type "string"`); + } + }); + return this.presignedUrl('GET', bucketName, objectName, expires, respHeaders, requestDate); + } + async presignedPutObject(bucketName, objectName, expires) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + return this.presignedUrl('PUT', bucketName, objectName, expires); + } + newPostPolicy() { + return new PostPolicy(); + } + async presignedPostPolicy(postPolicy) { + if (this.anonymous) { + throw new errors.AnonymousRequestError('Presigned POST policy cannot be generated for anonymous requests'); + } + if (!isObject(postPolicy)) { + throw new TypeError('postPolicy should be of type "object"'); + } + const bucketName = postPolicy.formData.bucket; + try { + const region = await this.getBucketRegionAsync(bucketName); + const date = new Date(); + const dateStr = makeDateLong(date); + await this.checkAndRefreshCreds(); + if (!postPolicy.policy.expiration) { + // 'expiration' is mandatory field for S3. + // Set default expiration date of 7 days. + const expires = new Date(); + expires.setSeconds(PRESIGN_EXPIRY_DAYS_MAX); + postPolicy.setExpires(expires); + } + postPolicy.policy.conditions.push(['eq', '$x-amz-date', dateStr]); + postPolicy.formData['x-amz-date'] = dateStr; + postPolicy.policy.conditions.push(['eq', '$x-amz-algorithm', 'AWS4-HMAC-SHA256']); + postPolicy.formData['x-amz-algorithm'] = 'AWS4-HMAC-SHA256'; + postPolicy.policy.conditions.push(['eq', '$x-amz-credential', this.accessKey + '/' + getScope(region, date)]); + postPolicy.formData['x-amz-credential'] = this.accessKey + '/' + getScope(region, date); + if (this.sessionToken) { + postPolicy.policy.conditions.push(['eq', '$x-amz-security-token', this.sessionToken]); + postPolicy.formData['x-amz-security-token'] = this.sessionToken; + } + const policyBase64 = Buffer.from(JSON.stringify(postPolicy.policy)).toString('base64'); + postPolicy.formData.policy = policyBase64; + postPolicy.formData['x-amz-signature'] = postPresignSignatureV4(region, date, this.secretKey, policyBase64); + const opts = { + region: region, + bucketName: bucketName, + method: 'POST' + }; + const reqOptions = this.getRequestOptions(opts); + const portStr = this.port == 80 || this.port === 443 ? '' : `:${this.port.toString()}`; + const urlStr = `${reqOptions.protocol}//${reqOptions.host}${portStr}${reqOptions.path}`; + return { + postURL: urlStr, + formData: postPolicy.formData + }; + } catch (err) { + if (err instanceof errors.InvalidBucketNameError) { + throw new errors.InvalidArgumentError(`Unable to get bucket region for ${bucketName}.`); + } + throw err; + } + } + // list a batch of objects + async listObjectsQuery(bucketName, prefix, marker, listQueryOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isString(prefix)) { + throw new TypeError('prefix should be of type "string"'); + } + if (marker && !isString(marker)) { + throw new TypeError('marker should be of type "string"'); + } + if (listQueryOpts && !isObject(listQueryOpts)) { + throw new TypeError('listQueryOpts should be of type "object"'); + } + let { + Delimiter, + MaxKeys, + IncludeVersion, + versionIdMarker, + keyMarker + } = listQueryOpts; + if (!isString(Delimiter)) { + throw new TypeError('Delimiter should be of type "string"'); + } + if (!isNumber(MaxKeys)) { + throw new TypeError('MaxKeys should be of type "number"'); + } + const queries = []; + // escape every value in query string, except maxKeys + queries.push(`prefix=${uriEscape(prefix)}`); + queries.push(`delimiter=${uriEscape(Delimiter)}`); + queries.push(`encoding-type=url`); + if (IncludeVersion) { + queries.push(`versions`); + } + if (IncludeVersion) { + // v1 version listing.. + if (keyMarker) { + queries.push(`key-marker=${keyMarker}`); + } + if (versionIdMarker) { + queries.push(`version-id-marker=${versionIdMarker}`); + } + } else if (marker) { + marker = uriEscape(marker); + queries.push(`marker=${marker}`); + } + + // no need to escape maxKeys + if (MaxKeys) { + if (MaxKeys >= 1000) { + MaxKeys = 1000; + } + queries.push(`max-keys=${MaxKeys}`); + } + queries.sort(); + let query = ''; + if (queries.length > 0) { + query = `${queries.join('&')}`; + } + const method = 'GET'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const body = await readAsString(res); + const listQryList = parseListObjects(body); + return listQryList; + } + listObjects(bucketName, prefix, recursive, listOpts) { + if (prefix === undefined) { + prefix = ''; + } + if (recursive === undefined) { + recursive = false; + } + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidPrefix(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`); + } + if (!isString(prefix)) { + throw new TypeError('prefix should be of type "string"'); + } + if (!isBoolean(recursive)) { + throw new TypeError('recursive should be of type "boolean"'); + } + if (listOpts && !isObject(listOpts)) { + throw new TypeError('listOpts should be of type "object"'); + } + let marker = ''; + let keyMarker = ''; + let versionIdMarker = ''; + let objects = []; + let ended = false; + const readStream = new stream.Readable({ + objectMode: true + }); + readStream._read = async () => { + // push one object per _read() + if (objects.length) { + readStream.push(objects.shift()); + return; + } + if (ended) { + return readStream.push(null); + } + try { + const listQueryOpts = { + Delimiter: recursive ? '' : '/', + // if recursive is false set delimiter to '/' + MaxKeys: 1000, + IncludeVersion: listOpts === null || listOpts === void 0 ? void 0 : listOpts.IncludeVersion, + // version listing specific options + keyMarker: keyMarker, + versionIdMarker: versionIdMarker + }; + const result = await this.listObjectsQuery(bucketName, prefix, marker, listQueryOpts); + if (result.isTruncated) { + marker = result.nextMarker || undefined; + if (result.keyMarker) { + keyMarker = result.keyMarker; + } + if (result.versionIdMarker) { + versionIdMarker = result.versionIdMarker; + } + } else { + ended = true; + } + if (result.objects) { + objects = result.objects; + } + // @ts-ignore + readStream._read(); + } catch (err) { + readStream.emit('error', err); + } + }; + return readStream; + } + async listObjectsV2Query(bucketName, prefix, continuationToken, delimiter, maxKeys, startAfter) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isString(prefix)) { + throw new TypeError('prefix should be of type "string"'); + } + if (!isString(continuationToken)) { + throw new TypeError('continuationToken should be of type "string"'); + } + if (!isString(delimiter)) { + throw new TypeError('delimiter should be of type "string"'); + } + if (!isNumber(maxKeys)) { + throw new TypeError('maxKeys should be of type "number"'); + } + if (!isString(startAfter)) { + throw new TypeError('startAfter should be of type "string"'); + } + const queries = []; + queries.push(`list-type=2`); + queries.push(`encoding-type=url`); + queries.push(`prefix=${uriEscape(prefix)}`); + queries.push(`delimiter=${uriEscape(delimiter)}`); + if (continuationToken) { + queries.push(`continuation-token=${uriEscape(continuationToken)}`); + } + if (startAfter) { + queries.push(`start-after=${uriEscape(startAfter)}`); + } + if (maxKeys) { + if (maxKeys >= 1000) { + maxKeys = 1000; + } + queries.push(`max-keys=${maxKeys}`); + } + queries.sort(); + let query = ''; + if (queries.length > 0) { + query = `${queries.join('&')}`; + } + const method = 'GET'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const body = await readAsString(res); + return parseListObjectsV2(body); + } + listObjectsV2(bucketName, prefix, recursive, startAfter) { + if (prefix === undefined) { + prefix = ''; + } + if (recursive === undefined) { + recursive = false; + } + if (startAfter === undefined) { + startAfter = ''; + } + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidPrefix(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`); + } + if (!isString(prefix)) { + throw new TypeError('prefix should be of type "string"'); + } + if (!isBoolean(recursive)) { + throw new TypeError('recursive should be of type "boolean"'); + } + if (!isString(startAfter)) { + throw new TypeError('startAfter should be of type "string"'); + } + const delimiter = recursive ? '' : '/'; + const prefixStr = prefix; + const startAfterStr = startAfter; + let continuationToken = ''; + let objects = []; + let ended = false; + const readStream = new stream.Readable({ + objectMode: true + }); + readStream._read = async () => { + if (objects.length) { + readStream.push(objects.shift()); + return; + } + if (ended) { + return readStream.push(null); + } + try { + const result = await this.listObjectsV2Query(bucketName, prefixStr, continuationToken, delimiter, 1000, startAfterStr); + if (result.isTruncated) { + continuationToken = result.nextContinuationToken; + } else { + ended = true; + } + objects = result.objects; + // @ts-ignore + readStream._read(); + } catch (err) { + readStream.emit('error', err); + } + }; + return readStream; + } + async setBucketNotification(bucketName, config) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isObject(config)) { + throw new TypeError('notification config should be of type "Object"'); + } + const method = 'PUT'; + const query = 'notification'; + const builder = new xml2js.Builder({ + rootName: 'NotificationConfiguration', + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(config); + await this.makeRequestAsyncOmit({ + method, + bucketName, + query + }, payload); + } + async removeAllBucketNotification(bucketName) { + await this.setBucketNotification(bucketName, new NotificationConfig()); + } + async getBucketNotification(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'GET'; + const query = 'notification'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const body = await readAsString(res); + return parseBucketNotification(body); + } + listenBucketNotification(bucketName, prefix, suffix, events) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!isString(prefix)) { + throw new TypeError('prefix must be of type string'); + } + if (!isString(suffix)) { + throw new TypeError('suffix must be of type string'); + } + if (!Array.isArray(events)) { + throw new TypeError('events must be of type Array'); + } + const listener = new NotificationPoller(this, bucketName, prefix, suffix, events); + listener.start(); + return listener; + } +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjcnlwdG8iLCJmcyIsImh0dHAiLCJodHRwcyIsInBhdGgiLCJzdHJlYW0iLCJhc3luYyIsIkJsb2NrU3RyZWFtMiIsImlzQnJvd3NlciIsIl8iLCJxcyIsInhtbDJqcyIsIkNyZWRlbnRpYWxQcm92aWRlciIsImVycm9ycyIsIkNvcHlEZXN0aW5hdGlvbk9wdGlvbnMiLCJDb3B5U291cmNlT3B0aW9ucyIsIkRFRkFVTFRfUkVHSU9OIiwiTEVHQUxfSE9MRF9TVEFUVVMiLCJQUkVTSUdOX0VYUElSWV9EQVlTX01BWCIsIlJFVEVOVElPTl9NT0RFUyIsIlJFVEVOVElPTl9WQUxJRElUWV9VTklUUyIsIk5vdGlmaWNhdGlvbkNvbmZpZyIsIk5vdGlmaWNhdGlvblBvbGxlciIsInBvc3RQcmVzaWduU2lnbmF0dXJlVjQiLCJwcmVzaWduU2lnbmF0dXJlVjQiLCJzaWduVjQiLCJmc3AiLCJzdHJlYW1Qcm9taXNlIiwiQ29weUNvbmRpdGlvbnMiLCJFeHRlbnNpb25zIiwiY2FsY3VsYXRlRXZlblNwbGl0cyIsImV4dHJhY3RNZXRhZGF0YSIsImdldENvbnRlbnRMZW5ndGgiLCJnZXRTY29wZSIsImdldFNvdXJjZVZlcnNpb25JZCIsImdldFZlcnNpb25JZCIsImhhc2hCaW5hcnkiLCJpbnNlcnRDb250ZW50VHlwZSIsImlzQW1hem9uRW5kcG9pbnQiLCJp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WFjaFNlcmllcyhcbiAgICAgICAgICAgIHJlc3VsdC51cGxvYWRzLFxuICAgICAgICAgICAgKHVwbG9hZCwgY2IpID0+IHtcbiAgICAgICAgICAgICAgLy8gZm9yIGVhY2ggaW5jb21wbGV0ZSB1cGxvYWQgYWRkIHRoZSBzaXplcyBvZiBpdHMgdXBsb2FkZWQgcGFydHNcbiAgICAgICAgICAgICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIEB0eXBlc2NyaXB0LWVzbGludC9iYW4tdHMtY29tbWVudFxuICAgICAgICAgICAgICAvLyBAdHMtaWdub3JlXG4gICAgICAgICAgICAgIHRoaXMubGlzdFBhcnRzKGJ1Y2tldCwgdXBsb2FkLmtleSwgdXBsb2FkLnVwbG9hZElkKS50aGVuKFxuICAgICAgICAgICAgICAgIChwYXJ0czogUGFydFtdKSA9PiB7XG4gICAgICAgICAgICAgICAgICAvLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgQHR5cGVzY3JpcHQtZXNsaW50L2Jhbi10cy1jb21tZW50XG4gICAgICAgICAgICAgICAgICAvLyBAdHMtaWdub3JlXG4gICAgICAgICAgICAgICAgICB1cGxvYWQuc2l6ZSA9IHBhcnRzLnJlZHVjZSgoYWNjLCBpdGVtKSA9PiBhY2MgKyBpdGVtLnNpemUsIDApXG4gICAgICAgICAgICAgICAgICB1cGxvYWRzLnB1c2godXBsb2FkKVxuICAgICAgICAgICAgICAgICAgY2IoKVxuICAgICAgICAgICAgICAgIH0sXG4gICAgICAgICAgICAgICAgKGVycjogRXJyb3IpID0+IGNiKGVyciksXG4gICAgICAgICAgICAgIClcbiAgICAgICAgICAgIH0sXG4gICAgICAgICAgICAoZXJyKSA9PiB7XG4gICAgICAgICAgICAgIGlmIChlcnIpIHtcbiAgICAgICAgICAgICAgICByZWFkU3RyZWFtLmVtaXQoJ2Vycm9yJywgZXJyKVxuICAgICAgICAgICAgICAgIHJldHVyblxuICAgICAgICAgICAgICB9XG4gICAgICAgICA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Bhd2FpdCAoY29uc3QgY2h1bmsgb2YgY2h1bmtpZXIpIHtcbiAgICAgICAgICBjb25zdCBtZDUgPSBjcnlwdG8uY3JlYXRlSGFzaCgnbWQ1JykudXBkYXRlKGNodW5rKS5kaWdlc3QoKVxuXG4gICAgICAgICAgY29uc3Qgb2xkUGFydCA9IG9sZFBhcnRzW3BhcnROdW1iZXJdXG4gICAgICAgICAgaWYgKG9sZFBhcnQpIHtcbiAgICAgICAgICAgIGlmIChvbGRQYXJ0LmV0YWcgPT09IG1kNS50b1N0cmluZygnaGV4JykpIHtcbiAgICAgICAgICAgICAgZVRhZ3MucHVzaCh7IHBhcnQ6IHBhcnROdW1iZXIsIGV0YWc6IG9sZFBhcnQuZXRhZyB9KVxuICAgICAgICAgICAgICBwYXJ0TnVtYmVyKytcbiAgICAgICAgICAgICAgY29udGludWVcbiAgICAgICAgICAgIH1cbiAgICAgICAgICB9XG5cbiAgICAgICAgICBwYXJ0TnVtYmVyKytcblxuICAgICAgICAgIC8vIG5vdyBzdGFydCB0byB1cGxvYWQgbWlzc2luZyBwYXJ0XG4gICAgICAgICAgY29uc3Qgb3B0aW9uczogUmVxdWVzdE9wdGlvbiA9IHtcbiAgICAgICAgICAgIG1ldGhvZDogJ1BVVCcsXG4gICAgICAgICAgICBxdWVyeTogcXMuc3RyaW5naWZ5KHsgcGFydE51bWJlciwgdXBsb2FkSWQgfSksXG4gICAgICAgICAgICBoZWFkZXJzOiB7XG4gICAgICAgICAgICAgICdDb250ZW50LUxlbmd0aCc6IGNodW5rLmxlbmd0aCxcbiAgICAgICAgICAgICAgJ0NvbnRlbnQtTUQ1JzogbWQ1LnRvU3RyaW5nKCdiYXNlNjQnKSxcbiAgICAgICAgICAgIH0sXG4gICAgICAgICAgICBidWNrZXROYW1lLFxuICAgICAgICAgICAgb2JqZWN0TmFtZSxcbiAgICAgICAgICB9XG5cbiAgICAgICAgICBjb25zdCByZXNwb25zZSA9IGF3YWl0IHRoaXMubWFrZVJlcXVlc3R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xuICAgICAgICAgIGlmIChyZXN1bHQudmVyc2lvbklkTWFya2VyKSB7XG4gICAgICAgICAgICB2ZXJzaW9uSWRNYXJrZXIgPSByZXN1bHQudmVyc2lvbklkTWFya2VyXG4gICAgICAgICAgfVxuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIGVuZGVkID0gdHJ1ZVxuICAgICAgICB9XG4gICAgICAgIGlmIChyZXN1bHQub2JqZWN0cykge1xuICAgICAgICAgIG9iamVjdHMgPSByZXN1bHQub2JqZWN0c1xuICAgICAgICB9XG4gICAgICAgIC8vIEB0cy1pZ25vcmVcbiAgICAgICAgcmVhZFN0cmVhbS5fcmVhZCgpXG4gICAgICB9IGNhdGNoIChlcnIpIHtcbiAgICAgICAgcmVhZFN0cmVhbS5lbWl0KCdlcnJvcicsIGVycilcbiAgICAgIH1cbiAgICB9XG4gICAgcmV0dXJuIHJlYWRTdHJlYW1cbiAgfVxuXG4gIGFzeW5jIGxpc3RPYmplY3RzVjJRdWVyeShcbiAgICBidWNrZXROYW1lOiBzdHJpbmcsXG4gICAgcHJlZml4OiBzdHJpbmcsXG4gICAgY29udGludWF0aW9uVG9rZW46IHN0cmluZyxcbiAgICBkZWxpbWl0ZXI6IHN0cmluZyxcbiAgICBtYXhLZXlzOiBudW1iZXIsXG4gICAgc3RhcnRBZnRlcjogc3RyaW5nLFxuICApOiBQcm9taXNlPExpc3RPYmplY3RWMlJlcz4ge1xuICAgIGlmICghaXNWYWxpZEJ1Y2tldE5hbWUoYnVja2V0TmFtZSkpIHtcbiAgICAgIHRocm93IG5ldyBlcnJvcnMuSW52YWxpZEJ1Y2tldE5hbWVFcnJvcignSW52YWxpZCBidWNrZXQgbmFtZTogJyArIGJ1Y2tldE5hbWUpXG4gICAgfVxuICAgIGlmICghaXNTdHJpbmcocHJlZml4KSkge1xuICAgICAgdGhyb3cgbmV3IFR5cGVFcnJvcigncHJlZml4IHNob3VsZCBiZSBvZiB0eXBlIFwic3RyaW5nXCInKVxuICAgIH1c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JlYWRhYmxlKHsgb2JqZWN0TW9kZTogdHJ1ZSB9KVxuICAgIHJlYWRTdHJlYW0uX3JlYWQgPSBhc3luYyAoKSA9PiB7XG4gICAgICBpZiAob2JqZWN0cy5sZW5ndGgpIHtcbiAgICAgICAgcmVhZFN0cmVhbS5wdXNoKG9iamVjdHMuc2hpZnQoKSlcbiAgICAgICAgcmV0dXJuXG4gICAgICB9XG4gICAgICBpZiAoZW5kZWQpIHtcbiAgICAgICAgcmV0dXJuIHJlYWRTdHJlYW0ucHVzaChudWxsKVxuICAgICAgfVxuXG4gICAgICB0cnkge1xuICAgICAgICBjb25zdCByZXN1bHQgPSBhd2FpdCB0aGlzLmxpc3RPYmplY3RzVjJRdWVyeShcbiAgICAgICAgICBidWNrZXROYW1lLFxuICAgICAgICAgIHByZWZpeFN0cixcbiAgICAgICAgICBjb250aW51YXRpb25Ub2tlbixcbiAgICAgICAgICBkZWxpbWl0ZXIsXG4gICAgICAgICAgMTAwMCxcbiAgICAgICAgICBzdGFydEFmdGVyU3RyLFxuICAgICAgICApXG4gICAgICAgIGlmIChyZXN1bHQuaXNUcnVuY2F0ZWQpIHtcbiAgICAgICAgICBjb250aW51YXRpb25Ub2tlbiA9IHJlc3VsdC5uZXh0Q29udGludWF0aW9uVG9rZW5cbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICBlbmRlZCA9IHRydWVcbiAgICAgICAgfVxuICAgICAgICBvYmplY3RzID0gcmVzdWx0Lm9iamVjdHNcbiAgICAgICAgLy8gQHRzLWlnbm9yZVxuICAgICAgICByZWFkU3RyZWFtLl9yZWFkKClcbiAgICAgIH0gY2F0Y2ggKGVycikge1xuICAgICAgICByZWFkU3RyZWFtLmVtaXQoJ2Vycm9yJywgZXJyKVxuICAgICAgfVxuICAgIH1cbiAgICByZXR1cm4gcmVhZFN0cmVhbVxuICB9XG5cbiAgYXN5bmMgc2V0QnVja2V0Tm90aWZpY2F0aW9uKGJ1Y2tldE5hbWU6IHN0cmluZywgY29u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wQyxPQUFPMUgsdUJBQXVCLENBQUMySCxJQUFJLENBQUM7RUFDdEM7RUFFQXdiLHdCQUF3QkEsQ0FDdEJsZixVQUFrQixFQUNsQmtKLE1BQWMsRUFDZGlXLE1BQWMsRUFDZEMsTUFBMkIsRUFDUDtJQUNwQixJQUFJLENBQUM1a0IsaUJBQWlCLENBQUN3RixVQUFVLENBQUMsRUFBRTtNQUNsQyxNQUFNLElBQUkxSCxNQUFNLENBQUMrTCxzQkFBc0IsQ0FBRSx3QkFBdUJyRSxVQUFXLEVBQUMsQ0FBQztJQUMvRTtJQUNBLElBQUksQ0FBQ3pGLFFBQVEsQ0FBQzJPLE1BQU0sQ0FBQyxFQUFFO01BQ3JCLE1BQU0sSUFBSXJKLFNBQVMsQ0FBQywrQkFBK0IsQ0FBQztJQUN0RDtJQUNBLElBQUksQ0FBQ3RGLFFBQVEsQ0FBQzRrQixNQUFNLENBQUMsRUFBRTtNQUNyQixNQUFNLElBQUl0ZixTQUFTLENBQUMsK0JBQStCLENBQUM7SUFDdEQ7SUFDQSxJQUFJLENBQUMyVixLQUFLLENBQUNDLE9BQU8sQ0FBQzJKLE1BQU0sQ0FBQyxFQUFFO01BQzFCLE1BQU0sSUFBSXZmLFNBQVMsQ0FBQyw4QkFBOEIsQ0FBQztJQUNyRDtJQUNBLE1BQU13ZixRQUFRLEdBQUcsSUFBSXRtQixrQkFBa0IsQ0FBQyxJQUFJLEVBQUVpSCxVQUFVLEVBQUVrSixNQUFNLEVBQUVpVyxNQUFNLEVBQUVDLE1BQU0sQ0FBQztJQUNqRkMsUUFBUSxDQUFDQyxLQUFLLENBQUMsQ0FBQztJQUNoQixPQUFPRCxRQUFRO0VBQ2pCO0FBQ0YifQ== \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/copy-conditions.d.mts b/node_modules/minio/dist/esm/internal/copy-conditions.d.mts new file mode 100644 index 0000000..f5d6e8b --- /dev/null +++ b/node_modules/minio/dist/esm/internal/copy-conditions.d.mts @@ -0,0 +1,10 @@ +export declare class CopyConditions { + modified: string; + unmodified: string; + matchETag: string; + matchETagExcept: string; + setModified(date: Date): void; + setUnmodified(date: Date): void; + setMatchETag(etag: string): void; + setMatchETagExcept(etag: string): void; +} \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/copy-conditions.mjs b/node_modules/minio/dist/esm/internal/copy-conditions.mjs new file mode 100644 index 0000000..c94ee0f --- /dev/null +++ b/node_modules/minio/dist/esm/internal/copy-conditions.mjs @@ -0,0 +1,25 @@ +export class CopyConditions { + modified = ''; + unmodified = ''; + matchETag = ''; + matchETagExcept = ''; + setModified(date) { + if (!(date instanceof Date)) { + throw new TypeError('date must be of type Date'); + } + this.modified = date.toUTCString(); + } + setUnmodified(date) { + if (!(date instanceof Date)) { + throw new TypeError('date must be of type Date'); + } + this.unmodified = date.toUTCString(); + } + setMatchETag(etag) { + this.matchETag = etag; + } + setMatchETagExcept(etag) { + this.matchETagExcept = etag; + } +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDb3B5Q29uZGl0aW9ucyIsIm1vZGlmaWVkIiwidW5tb2RpZmllZCIsIm1hdGNoRVRhZyIsIm1hdGNoRVRhZ0V4Y2VwdCIsInNldE1vZGlmaWVkIiwiZGF0ZSIsIkRhdGUiLCJUeXBlRXJyb3IiLCJ0b1VUQ1N0cmluZyIsInNldFVubW9kaWZpZWQiLCJzZXRNYXRjaEVUYWciLCJldGFnIiwic2V0TWF0Y2hFVGFnRXhjZXB0Il0sInNvdXJjZXMiOlsiY29weS1jb25kaXRpb25zLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBjbGFzcyBDb3B5Q29uZGl0aW9ucyB7XG4gIHB1YmxpYyBtb2RpZmllZCA9ICcnXG4gIHB1YmxpYyB1bm1vZGlmaWVkID0gJydcbiAgcHVibGljIG1hdGNoRVRhZyA9ICcnXG4gIHB1YmxpYyBtYXRjaEVUYWdFeGNlcHQg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QUFRLEdBQUdLLElBQUksQ0FBQ0csV0FBVyxDQUFDLENBQUM7RUFDcEM7RUFFQUMsYUFBYUEsQ0FBQ0osSUFBVSxFQUFRO0lBQzlCLElBQUksRUFBRUEsSUFBSSxZQUFZQyxJQUFJLENBQUMsRUFBRTtNQUMzQixNQUFNLElBQUlDLFNBQVMsQ0FBQywyQkFBMkIsQ0FBQztJQUNsRDtJQUVBLElBQUksQ0FBQ04sVUFBVSxHQUFHSSxJQUFJLENBQUNHLFdBQVcsQ0FBQyxDQUFDO0VBQ3RDO0VBRUFFLFlBQVlBLENBQUNDLElBQVksRUFBUTtJQUMvQixJQUFJLENBQUNULFNBQVMsR0FBR1MsSUFBSTtFQUN2QjtFQUVBQyxrQkFBa0JBLENBQUNELElBQVksRUFBUTtJQUNyQyxJQUFJLENBQUNSLGVBQWUsR0FBR1EsSUFBSTtFQUM3QjtBQUNGIn0= \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/extensions.d.mts b/node_modules/minio/dist/esm/internal/extensions.d.mts new file mode 100644 index 0000000..59a9dc1 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/extensions.d.mts @@ -0,0 +1,18 @@ +import type { TypedClient } from "./client.mjs"; +import type { BucketItemWithMetadata, BucketStream } from "./type.mjs"; +export declare class Extensions { + private readonly client; + constructor(client: TypedClient); + /** + * List the objects in the bucket using S3 ListObjects V2 With Metadata + * + * @param bucketName - name of the bucket + * @param prefix - the prefix of the objects that should be listed (optional, default `''`) + * @param recursive - `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'. (optional, default `false`) + * @param startAfter - Specifies the key to start after when listing objects in a bucket. (optional, default `''`) + * @returns stream emitting the objects in the bucket, the object is of the format: + */ + listObjectsV2WithMetadata(bucketName: string, prefix?: string, recursive?: boolean, startAfter?: string): BucketStream; + private listObjectsV2WithMetadataGen; + private listObjectsV2WithMetadataQuery; +} \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/extensions.mjs b/node_modules/minio/dist/esm/internal/extensions.mjs new file mode 100644 index 0000000..96c7120 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/extensions.mjs @@ -0,0 +1,114 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2020 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as stream from "stream"; +import * as errors from "../errors.mjs"; +import { isBoolean, isString, isValidBucketName, isValidPrefix, uriEscape } from "./helper.mjs"; +import { readAsString } from "./response.mjs"; +import { parseListObjectsV2WithMetadata } from "./xml-parser.mjs"; +export class Extensions { + constructor(client) { + this.client = client; + } + + /** + * List the objects in the bucket using S3 ListObjects V2 With Metadata + * + * @param bucketName - name of the bucket + * @param prefix - the prefix of the objects that should be listed (optional, default `''`) + * @param recursive - `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'. (optional, default `false`) + * @param startAfter - Specifies the key to start after when listing objects in a bucket. (optional, default `''`) + * @returns stream emitting the objects in the bucket, the object is of the format: + */ + listObjectsV2WithMetadata(bucketName, prefix, recursive, startAfter) { + if (prefix === undefined) { + prefix = ''; + } + if (recursive === undefined) { + recursive = false; + } + if (startAfter === undefined) { + startAfter = ''; + } + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!isValidPrefix(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`); + } + if (!isString(prefix)) { + throw new TypeError('prefix should be of type "string"'); + } + if (!isBoolean(recursive)) { + throw new TypeError('recursive should be of type "boolean"'); + } + if (!isString(startAfter)) { + throw new TypeError('startAfter should be of type "string"'); + } + + // if recursive is false set delimiter to '/' + const delimiter = recursive ? '' : '/'; + return stream.Readable.from(this.listObjectsV2WithMetadataGen(bucketName, prefix, delimiter, startAfter), { + objectMode: true + }); + } + async *listObjectsV2WithMetadataGen(bucketName, prefix, delimiter, startAfter) { + let ended = false; + let continuationToken = ''; + do { + const result = await this.listObjectsV2WithMetadataQuery(bucketName, prefix, continuationToken, delimiter, startAfter); + ended = !result.isTruncated; + continuationToken = result.nextContinuationToken; + for (const obj of result.objects) { + yield obj; + } + } while (!ended); + } + async listObjectsV2WithMetadataQuery(bucketName, prefix, continuationToken, delimiter, startAfter) { + const queries = []; + + // Call for listing objects v2 API + queries.push(`list-type=2`); + queries.push(`encoding-type=url`); + // escape every value in query string, except maxKeys + queries.push(`prefix=${uriEscape(prefix)}`); + queries.push(`delimiter=${uriEscape(delimiter)}`); + queries.push(`metadata=true`); + if (continuationToken) { + continuationToken = uriEscape(continuationToken); + queries.push(`continuation-token=${continuationToken}`); + } + // Set start-after + if (startAfter) { + startAfter = uriEscape(startAfter); + queries.push(`start-after=${startAfter}`); + } + queries.push(`max-keys=1000`); + queries.sort(); + let query = ''; + if (queries.length > 0) { + query = `${queries.join('&')}`; + } + const method = 'GET'; + const res = await this.client.makeRequestAsync({ + method, + bucketName, + query + }); + return parseListObjectsV2WithMetadata(await readAsString(res)); + } +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJzdHJlYW0iLCJlcnJvcnMiLCJpc0Jvb2xlYW4iLCJpc1N0cmluZyIsImlzVmFsaWRCdWNrZXROYW1lIiwiaXNWYWxpZFByZWZpeCIsInVyaUVzY2FwZSIsInJlYWRBc1N0cmluZyIsInBhcnNlTGlzdE9iamVjdHNWMldpdGhNZXRhZGF0YSIsIkV4dGVuc2lvbnMiLCJjb25zdHJ1Y3RvciIsImNsaWVudCIsImxpc3RPYmplY3RzVjJXaXRoTWV0YWRhdGEiLCJidWNrZXROYW1lIiwicHJlZml4IiwicmVjdXJzaXZlI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BQzdFLE9BQU83Qiw4QkFBOEIsQ0FBQyxNQUFNRCxZQUFZLENBQUNrQyxHQUFHLENBQUMsQ0FBQztFQUNoRTtBQUNGIn0= \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/helper.d.mts b/node_modules/minio/dist/esm/internal/helper.d.mts new file mode 100644 index 0000000..c8b1666 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/helper.d.mts @@ -0,0 +1,177 @@ +/// +/// +import * as stream from 'node:stream'; +import _ from 'lodash'; +import type { Binary, Encryption, ObjectMetaData, RequestHeaders, ResponseHeader } from "./type.mjs"; +export declare function hashBinary(buf: Buffer, enableSHA256: boolean): { + md5sum: string; + sha256sum: string; +}; +export declare function uriEscape(uriStr: string): string; +export declare function uriResourceEscape(string: string): string; +export declare function getScope(region: string, date: Date, serviceName?: string): string; +/** + * isAmazonEndpoint - true if endpoint is 's3.amazonaws.com' or 's3.cn-north-1.amazonaws.com.cn' + */ +export declare function isAmazonEndpoint(endpoint: string): boolean; +/** + * isVirtualHostStyle - verify if bucket name is support with virtual + * hosts. bucketNames with periods should be always treated as path + * style if the protocol is 'https:', this is due to SSL wildcard + * limitation. For all other buckets and Amazon S3 endpoint we will + * default to virtual host style. + */ +export declare function isVirtualHostStyle(endpoint: string, protocol: string, bucket: string, pathStyle: boolean): boolean; +export declare function isValidIP(ip: string): boolean; +/** + * @returns if endpoint is valid domain. + */ +export declare function isValidEndpoint(endpoint: string): boolean; +/** + * @returns if input host is a valid domain. + */ +export declare function isValidDomain(host: string): boolean; +/** + * Probes contentType using file extensions. + * + * @example + * ``` + * // return 'image/png' + * probeContentType('file.png') + * ``` + */ +export declare function probeContentType(path: string): string; +/** + * is input port valid. + */ +export declare function isValidPort(port: unknown): port is number; +export declare function isValidBucketName(bucket: unknown): boolean; +/** + * check if objectName is a valid object name + */ +export declare function isValidObjectName(objectName: unknown): boolean; +/** + * check if prefix is valid + */ +export declare function isValidPrefix(prefix: unknown): prefix is string; +/** + * check if typeof arg number + */ +export declare function isNumber(arg: unknown): arg is number; +export type AnyFunction = (...args: any[]) => any; +/** + * check if typeof arg function + */ +export declare function isFunction(arg: unknown): arg is AnyFunction; +/** + * check if typeof arg string + */ +export declare function isString(arg: unknown): arg is string; +/** + * check if typeof arg object + */ +export declare function isObject(arg: unknown): arg is object; +/** + * check if typeof arg is plain object + */ +export declare function isPlainObject(arg: unknown): arg is Record; +/** + * check if object is readable stream + */ +export declare function isReadableStream(arg: unknown): arg is stream.Readable; +/** + * check if arg is boolean + */ +export declare function isBoolean(arg: unknown): arg is boolean; +export declare function isEmpty(o: unknown): o is null | undefined; +export declare function isEmptyObject(o: Record): boolean; +export declare function isDefined(o: T): o is Exclude; +/** + * check if arg is a valid date + */ +export declare function isValidDate(arg: unknown): arg is Date; +/** + * Create a Date string with format: 'YYYYMMDDTHHmmss' + Z + */ +export declare function makeDateLong(date?: Date): string; +/** + * Create a Date string with format: 'YYYYMMDD' + */ +export declare function makeDateShort(date?: Date): string; +/** + * pipesetup sets up pipe() from left to right os streams array + * pipesetup will also make sure that error emitted at any of the upstream Stream + * will be emitted at the last stream. This makes error handling simple + */ +export declare function pipesetup(...streams: [stream.Readable, ...stream.Duplex[], stream.Writable]): stream.Readable | stream.Duplex | stream.Writable; +/** + * return a Readable stream that emits data + */ +export declare function readableStream(data: unknown): stream.Readable; +/** + * Process metadata to insert appropriate value to `content-type` attribute + */ +export declare function insertContentType(metaData: ObjectMetaData, filePath: string): ObjectMetaData; +/** + * Function prepends metadata with the appropriate prefix if it is not already on + */ +export declare function prependXAMZMeta(metaData?: ObjectMetaData): RequestHeaders; +/** + * Checks if it is a valid header according to the AmazonS3 API + */ +export declare function isAmzHeader(key: string): boolean; +/** + * Checks if it is a supported Header + */ +export declare function isSupportedHeader(key: string): boolean; +/** + * Checks if it is a storage header + */ +export declare function isStorageClassHeader(key: string): boolean; +export declare function extractMetadata(headers: ResponseHeader): _.Dictionary; +export declare function getVersionId(headers?: ResponseHeader): string | null; +export declare function getSourceVersionId(headers?: ResponseHeader): string | null; +export declare function sanitizeETag(etag?: string): string; +export declare function toMd5(payload: Binary): string; +export declare function toSha256(payload: Binary): string; +/** + * toArray returns a single element array with param being the element, + * if param is just a string, and returns 'param' back if it is an array + * So, it makes sure param is always an array + */ +export declare function toArray(param: T | T[]): Array; +export declare function sanitizeObjectKey(objectName: string): string; +export declare function sanitizeSize(size?: string): number | undefined; +export declare const PART_CONSTRAINTS: { + ABS_MIN_PART_SIZE: number; + MIN_PART_SIZE: number; + MAX_PARTS_COUNT: number; + MAX_PART_SIZE: number; + MAX_SINGLE_PUT_OBJECT_SIZE: number; + MAX_MULTIPART_PUT_OBJECT_SIZE: number; +}; +/** + * Return Encryption headers + * @param encConfig + * @returns an object with key value pairs that can be used in headers. + */ +export declare function getEncryptionHeaders(encConfig: Encryption): RequestHeaders; +export declare function partsRequired(size: number): number; +/** + * calculateEvenSplits - computes splits for a source and returns + * start and end index slices. Splits happen evenly to be sure that no + * part is less than 5MiB, as that could fail the multipart request if + * it is not the last part. + */ +export declare function calculateEvenSplits(size: number, objInfo: T): { + startIndex: number[]; + objInfo: T; + endIndex: number[]; +} | null; +export declare function parseXml(xml: string): any; +/** + * get content size of object content to upload + */ +export declare function getContentLength(s: stream.Readable | Buffer | string): Promise; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/helper.mjs b/node_modules/minio/dist/esm/internal/helper.mjs new file mode 100644 index 0000000..4e86405 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/helper.mjs @@ -0,0 +1,552 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as crypto from "crypto"; +import * as stream from "stream"; +import { XMLParser } from 'fast-xml-parser'; +import ipaddr from 'ipaddr.js'; +import _ from 'lodash'; +import * as mime from 'mime-types'; +import { fsp, fstat } from "./async.mjs"; +import { ENCRYPTION_TYPES } from "./type.mjs"; +const MetaDataHeaderPrefix = 'x-amz-meta-'; +export function hashBinary(buf, enableSHA256) { + let sha256sum = ''; + if (enableSHA256) { + sha256sum = crypto.createHash('sha256').update(buf).digest('hex'); + } + const md5sum = crypto.createHash('md5').update(buf).digest('base64'); + return { + md5sum, + sha256sum + }; +} + +// S3 percent-encodes some extra non-standard characters in a URI . So comply with S3. +const encodeAsHex = c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; +export function uriEscape(uriStr) { + return encodeURIComponent(uriStr).replace(/[!'()*]/g, encodeAsHex); +} +export function uriResourceEscape(string) { + return uriEscape(string).replace(/%2F/g, '/'); +} +export function getScope(region, date, serviceName = 's3') { + return `${makeDateShort(date)}/${region}/${serviceName}/aws4_request`; +} + +/** + * isAmazonEndpoint - true if endpoint is 's3.amazonaws.com' or 's3.cn-north-1.amazonaws.com.cn' + */ +export function isAmazonEndpoint(endpoint) { + return endpoint === 's3.amazonaws.com' || endpoint === 's3.cn-north-1.amazonaws.com.cn'; +} + +/** + * isVirtualHostStyle - verify if bucket name is support with virtual + * hosts. bucketNames with periods should be always treated as path + * style if the protocol is 'https:', this is due to SSL wildcard + * limitation. For all other buckets and Amazon S3 endpoint we will + * default to virtual host style. + */ +export function isVirtualHostStyle(endpoint, protocol, bucket, pathStyle) { + if (protocol === 'https:' && bucket.includes('.')) { + return false; + } + return isAmazonEndpoint(endpoint) || !pathStyle; +} +export function isValidIP(ip) { + return ipaddr.isValid(ip); +} + +/** + * @returns if endpoint is valid domain. + */ +export function isValidEndpoint(endpoint) { + return isValidDomain(endpoint) || isValidIP(endpoint); +} + +/** + * @returns if input host is a valid domain. + */ +export function isValidDomain(host) { + if (!isString(host)) { + return false; + } + // See RFC 1035, RFC 3696. + if (host.length === 0 || host.length > 255) { + return false; + } + // Host cannot start or end with a '-' + if (host[0] === '-' || host.slice(-1) === '-') { + return false; + } + // Host cannot start or end with a '_' + if (host[0] === '_' || host.slice(-1) === '_') { + return false; + } + // Host cannot start with a '.' + if (host[0] === '.') { + return false; + } + const nonAlphaNumerics = '`~!@#$%^&*()+={}[]|\\"\';:> 63) { + return false; + } + // bucket with successive periods is invalid. + if (bucket.includes('..')) { + return false; + } + // bucket cannot have ip address style. + if (/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/.test(bucket)) { + return false; + } + // bucket should begin with alphabet/number and end with alphabet/number, + // with alphabet/number/.- in the middle. + if (/^[a-z0-9][a-z0-9.-]+[a-z0-9]$/.test(bucket)) { + return true; + } + return false; +} + +/** + * check if objectName is a valid object name + */ +export function isValidObjectName(objectName) { + if (!isValidPrefix(objectName)) { + return false; + } + return objectName.length !== 0; +} + +/** + * check if prefix is valid + */ +export function isValidPrefix(prefix) { + if (!isString(prefix)) { + return false; + } + if (prefix.length > 1024) { + return false; + } + return true; +} + +/** + * check if typeof arg number + */ +export function isNumber(arg) { + return typeof arg === 'number'; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any + +/** + * check if typeof arg function + */ +export function isFunction(arg) { + return typeof arg === 'function'; +} + +/** + * check if typeof arg string + */ +export function isString(arg) { + return typeof arg === 'string'; +} + +/** + * check if typeof arg object + */ +export function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +/** + * check if typeof arg is plain object + */ +export function isPlainObject(arg) { + return Object.prototype.toString.call(arg) === '[object Object]'; +} +/** + * check if object is readable stream + */ +export function isReadableStream(arg) { + // eslint-disable-next-line @typescript-eslint/unbound-method + return isObject(arg) && isFunction(arg._read); +} + +/** + * check if arg is boolean + */ +export function isBoolean(arg) { + return typeof arg === 'boolean'; +} +export function isEmpty(o) { + return _.isEmpty(o); +} +export function isEmptyObject(o) { + return Object.values(o).filter(x => x !== undefined).length !== 0; +} +export function isDefined(o) { + return o !== null && o !== undefined; +} + +/** + * check if arg is a valid date + */ +export function isValidDate(arg) { + // @ts-expect-error checknew Date(Math.NaN) + return arg instanceof Date && !isNaN(arg); +} + +/** + * Create a Date string with format: 'YYYYMMDDTHHmmss' + Z + */ +export function makeDateLong(date) { + date = date || new Date(); + + // Gives format like: '2017-08-07T16:28:59.889Z' + const s = date.toISOString(); + return s.slice(0, 4) + s.slice(5, 7) + s.slice(8, 13) + s.slice(14, 16) + s.slice(17, 19) + 'Z'; +} + +/** + * Create a Date string with format: 'YYYYMMDD' + */ +export function makeDateShort(date) { + date = date || new Date(); + + // Gives format like: '2017-08-07T16:28:59.889Z' + const s = date.toISOString(); + return s.slice(0, 4) + s.slice(5, 7) + s.slice(8, 10); +} + +/** + * pipesetup sets up pipe() from left to right os streams array + * pipesetup will also make sure that error emitted at any of the upstream Stream + * will be emitted at the last stream. This makes error handling simple + */ +export function pipesetup(...streams) { + // @ts-expect-error ts can't narrow this + return streams.reduce((src, dst) => { + src.on('error', err => dst.emit('error', err)); + return src.pipe(dst); + }); +} + +/** + * return a Readable stream that emits data + */ +export function readableStream(data) { + const s = new stream.Readable(); + s._read = () => {}; + s.push(data); + s.push(null); + return s; +} + +/** + * Process metadata to insert appropriate value to `content-type` attribute + */ +export function insertContentType(metaData, filePath) { + // check if content-type attribute present in metaData + for (const key in metaData) { + if (key.toLowerCase() === 'content-type') { + return metaData; + } + } + + // if `content-type` attribute is not present in metadata, then infer it from the extension in filePath + return { + ...metaData, + 'content-type': probeContentType(filePath) + }; +} + +/** + * Function prepends metadata with the appropriate prefix if it is not already on + */ +export function prependXAMZMeta(metaData) { + if (!metaData) { + return {}; + } + return _.mapKeys(metaData, (value, key) => { + if (isAmzHeader(key) || isSupportedHeader(key) || isStorageClassHeader(key)) { + return key; + } + return MetaDataHeaderPrefix + key; + }); +} + +/** + * Checks if it is a valid header according to the AmazonS3 API + */ +export function isAmzHeader(key) { + const temp = key.toLowerCase(); + return temp.startsWith(MetaDataHeaderPrefix) || temp === 'x-amz-acl' || temp.startsWith('x-amz-server-side-encryption-') || temp === 'x-amz-server-side-encryption'; +} + +/** + * Checks if it is a supported Header + */ +export function isSupportedHeader(key) { + const supported_headers = ['content-type', 'cache-control', 'content-encoding', 'content-disposition', 'content-language', 'x-amz-website-redirect-location', 'if-none-match', 'if-match']; + return supported_headers.includes(key.toLowerCase()); +} + +/** + * Checks if it is a storage header + */ +export function isStorageClassHeader(key) { + return key.toLowerCase() === 'x-amz-storage-class'; +} +export function extractMetadata(headers) { + return _.mapKeys(_.pickBy(headers, (value, key) => isSupportedHeader(key) || isStorageClassHeader(key) || isAmzHeader(key)), (value, key) => { + const lower = key.toLowerCase(); + if (lower.startsWith(MetaDataHeaderPrefix)) { + return lower.slice(MetaDataHeaderPrefix.length); + } + return key; + }); +} +export function getVersionId(headers = {}) { + return headers['x-amz-version-id'] || null; +} +export function getSourceVersionId(headers = {}) { + return headers['x-amz-copy-source-version-id'] || null; +} +export function sanitizeETag(etag = '') { + const replaceChars = { + '"': '', + '"': '', + '"': '', + '"': '', + '"': '' + }; + return etag.replace(/^("|"|")|("|"|")$/g, m => replaceChars[m]); +} +export function toMd5(payload) { + // use string from browser and buffer from nodejs + // browser support is tested only against minio server + return crypto.createHash('md5').update(Buffer.from(payload)).digest().toString('base64'); +} +export function toSha256(payload) { + return crypto.createHash('sha256').update(payload).digest('hex'); +} + +/** + * toArray returns a single element array with param being the element, + * if param is just a string, and returns 'param' back if it is an array + * So, it makes sure param is always an array + */ +export function toArray(param) { + if (!Array.isArray(param)) { + return [param]; + } + return param; +} +export function sanitizeObjectKey(objectName) { + // + symbol characters are not decoded as spaces in JS. so replace them first and decode to get the correct result. + const asStrName = (objectName ? objectName.toString() : '').replace(/\+/g, ' '); + return decodeURIComponent(asStrName); +} +export function sanitizeSize(size) { + return size ? Number.parseInt(size) : undefined; +} +export const PART_CONSTRAINTS = { + // absMinPartSize - absolute minimum part size (5 MiB) + ABS_MIN_PART_SIZE: 1024 * 1024 * 5, + // MIN_PART_SIZE - minimum part size 16MiB per object after which + MIN_PART_SIZE: 1024 * 1024 * 16, + // MAX_PARTS_COUNT - maximum number of parts for a single multipart session. + MAX_PARTS_COUNT: 10000, + // MAX_PART_SIZE - maximum part size 5GiB for a single multipart upload + // operation. + MAX_PART_SIZE: 1024 * 1024 * 1024 * 5, + // MAX_SINGLE_PUT_OBJECT_SIZE - maximum size 5GiB of object per PUT + // operation. + MAX_SINGLE_PUT_OBJECT_SIZE: 1024 * 1024 * 1024 * 5, + // MAX_MULTIPART_PUT_OBJECT_SIZE - maximum size 5TiB of object for + // Multipart operation. + MAX_MULTIPART_PUT_OBJECT_SIZE: 1024 * 1024 * 1024 * 1024 * 5 +}; +const GENERIC_SSE_HEADER = 'X-Amz-Server-Side-Encryption'; +const ENCRYPTION_HEADERS = { + // sseGenericHeader is the AWS SSE header used for SSE-S3 and SSE-KMS. + sseGenericHeader: GENERIC_SSE_HEADER, + // sseKmsKeyID is the AWS SSE-KMS key id. + sseKmsKeyID: GENERIC_SSE_HEADER + '-Aws-Kms-Key-Id' +}; + +/** + * Return Encryption headers + * @param encConfig + * @returns an object with key value pairs that can be used in headers. + */ +export function getEncryptionHeaders(encConfig) { + const encType = encConfig.type; + if (!isEmpty(encType)) { + if (encType === ENCRYPTION_TYPES.SSEC) { + return { + [ENCRYPTION_HEADERS.sseGenericHeader]: 'AES256' + }; + } else if (encType === ENCRYPTION_TYPES.KMS) { + return { + [ENCRYPTION_HEADERS.sseGenericHeader]: encConfig.SSEAlgorithm, + [ENCRYPTION_HEADERS.sseKmsKeyID]: encConfig.KMSMasterKeyID + }; + } + } + return {}; +} +export function partsRequired(size) { + const maxPartSize = PART_CONSTRAINTS.MAX_MULTIPART_PUT_OBJECT_SIZE / (PART_CONSTRAINTS.MAX_PARTS_COUNT - 1); + let requiredPartSize = size / maxPartSize; + if (size % maxPartSize > 0) { + requiredPartSize++; + } + requiredPartSize = Math.trunc(requiredPartSize); + return requiredPartSize; +} + +/** + * calculateEvenSplits - computes splits for a source and returns + * start and end index slices. Splits happen evenly to be sure that no + * part is less than 5MiB, as that could fail the multipart request if + * it is not the last part. + */ +export function calculateEvenSplits(size, objInfo) { + if (size === 0) { + return null; + } + const reqParts = partsRequired(size); + const startIndexParts = []; + const endIndexParts = []; + let start = objInfo.Start; + if (isEmpty(start) || start === -1) { + start = 0; + } + const divisorValue = Math.trunc(size / reqParts); + const reminderValue = size % reqParts; + let nextStart = start; + for (let i = 0; i < reqParts; i++) { + let curPartSize = divisorValue; + if (i < reminderValue) { + curPartSize++; + } + const currentStart = nextStart; + const currentEnd = currentStart + curPartSize - 1; + nextStart = currentEnd + 1; + startIndexParts.push(currentStart); + endIndexParts.push(currentEnd); + } + return { + startIndex: startIndexParts, + endIndex: endIndexParts, + objInfo: objInfo + }; +} +const fxp = new XMLParser({ + numberParseOptions: { + eNotation: false, + hex: true, + leadingZeros: true + } +}); + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function parseXml(xml) { + const result = fxp.parse(xml); + if (result.Error) { + throw result.Error; + } + return result; +} + +/** + * get content size of object content to upload + */ +export async function getContentLength(s) { + // use length property of string | Buffer + if (typeof s === 'string' || Buffer.isBuffer(s)) { + return s.length; + } + + // property of `fs.ReadStream` + const filePath = s.path; + if (filePath && typeof filePath === 'string') { + const stat = await fsp.lstat(filePath); + return stat.size; + } + + // property of `fs.ReadStream` + const fd = s.fd; + if (fd && typeof fd === 'number') { + const stat = await fstat(fd); + return stat.size; + } + return null; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjcnlwdG8iLCJzdHJlYW0iLCJYTUxQYXJzZXIiLCJpcGFkZHIiLCJfIiwibWltZSIsImZzcCIsImZzdGF0IiwiRU5DUllQVElPTl9UWVBFUyIsIk1ldGFEYXRhSGVhZGVyUHJlZml4IiwiaGFzaEJpbmFyeSIsImJ1ZiIsImVuYWJsZVNIQTI1NiIsInNoY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3BCO0VBRUEsT0FBT0YsTUFBTTtBQUNmOztBQUVBO0FBQ0E7QUFDQTtBQUNBLE9BQU8sZUFBZUcsZ0JBQWdCQSxDQUFDeEcsQ0FBb0MsRUFBMEI7RUFDbkc7RUFDQSxJQUFJLE9BQU9BLENBQUMsS0FBSyxRQUFRLElBQUl5QyxNQUFNLENBQUNnRSxRQUFRLENBQUN6RyxDQUFDLENBQUMsRUFBRTtJQUMvQyxPQUFPQSxDQUFDLENBQUN6QyxNQUFNO0VBQ2pCOztFQUVBO0VBQ0EsTUFBTTBELFFBQVEsR0FBSWpCLENBQUMsQ0FBd0NwQyxJQUEwQjtFQUNyRixJQUFJcUQsUUFBUSxJQUFJLE9BQU9BLFFBQVEsS0FBSyxRQUFRLEVBQUU7SUFDNUMsTUFBTXlGLElBQUksR0FBRyxNQUFNN0wsR0FBRyxDQUFDOEwsS0FBSyxDQUFDMUYsUUFBUSxDQUFDO0lBQ3RDLE9BQU95RixJQUFJLENBQUN0RCxJQUFJO0VBQ2xCOztFQUVBO0VBQ0EsTUFBTXdELEVBQUUsR0FBSTVHLENBQUMsQ0FBd0M0RyxFQUErQjtFQUNwRixJQUFJQSxFQUFFLElBQUksT0FBT0EsRUFBRSxLQUFLLFFBQVEsRUFBRTtJQUNoQyxNQUFNRixJQUFJLEdBQUcsTUFBTTVMLEtBQUssQ0FBQzhMLEVBQUUsQ0FBQztJQUM1QixPQUFPRixJQUFJLENBQUN0RCxJQUFJO0VBQ2xCO0VBRUEsT0FBTyxJQUFJO0FBQ2IifQ== \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/join-host-port.d.mts b/node_modules/minio/dist/esm/internal/join-host-port.d.mts new file mode 100644 index 0000000..51bf708 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/join-host-port.d.mts @@ -0,0 +1,11 @@ +/** + * joinHostPort combines host and port into a network address of the + * form "host:port". If host contains a colon, as found in literal + * IPv6 addresses, then JoinHostPort returns "[host]:port". + * + * @param host + * @param port + * @returns Cleaned up host + * @internal + */ +export declare function joinHostPort(host: string, port?: number): string; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/join-host-port.mjs b/node_modules/minio/dist/esm/internal/join-host-port.mjs new file mode 100644 index 0000000..202151d --- /dev/null +++ b/node_modules/minio/dist/esm/internal/join-host-port.mjs @@ -0,0 +1,23 @@ +/** + * joinHostPort combines host and port into a network address of the + * form "host:port". If host contains a colon, as found in literal + * IPv6 addresses, then JoinHostPort returns "[host]:port". + * + * @param host + * @param port + * @returns Cleaned up host + * @internal + */ +export function joinHostPort(host, port) { + if (port === undefined) { + return host; + } + + // We assume that host is a literal IPv6 address if host has + // colons. + if (host.includes(':')) { + return `[${host}]:${port.toString()}`; + } + return `${host}:${port.toString()}`; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJqb2luSG9zdFBvcnQiLCJob3N0IiwicG9ydCIsInVuZGVmaW5lZCIsImluY2x1ZGVzIiwidG9TdHJpbmciXSwic291cmNlcyI6WyJqb2luLWhvc3QtcG9ydC50cyJdLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIGpvaW5Ib3N0UG9ydCBjb21iaW5lcyBob3N0IGFuZCBwb3J0IGludG8gYSBuZXR3b3JrIGFkZHJlc3Mgb2YgdGhlXG4gKiBmb3JtIFwiaG9zdDpwb3J0XCIuIElmIGhvc3QgY29udGFpbnMgYSBjb2xvbiwgYXMgZm91bmQgaW4gbGl0ZXJhbFxuICogSVB2NiBhZGRyZXNzZXMsIHRoZW4gSm9pbkhvc3RQb3J0IHJldHVybnMgXCJbaG9zdF06cG9ydFwiLlxuICpcbiAqIEBwYXJhbSBob3N0XG4gKiBAcGFyYW0gcG9ydFxuICogQHJldHVybnMgQ2xlYW5lZCB1cCBob3N0XG4gKiBAaW50ZXJuYWxcbiAqL1xuZXhwb3J0IGZ1bmN0aW9uIGpvaW5Ib3N0UG9ydChob3N0OiBzdHJpbmcsIHBvcnQ/OiBudW1iZXIpOiBzdHJpbmcge1xuICBpZiAocG9ydCA9PT0gdW5kZWZpbmVkKSB7XG4gICAgcmV0dXJuIGhvc3RcbiAgfVxuXG4gIC8vIFdlIGFzc3VtZSB0aGF0IGhvc3QgaXMgYSBsaXRlcmFsIElQdjYgYWRkcmVzcyBpZiBob3N0IGhhc1xuICAvLyBjb2xvbnMuXG4gIGlmIChob3N0LmluY2x1ZGVzKCc6JykpIHtcbiAgICByZXR1cm4gYFske2hvc3R9XToke3BvcnQudG9TdHJpbmcoKX1gXG4gIH1cblxuICByZXR1cm4gYCR7aG9zdH06JHtwb3J0LnRvU3RyaW5nKCl9YFxufVxuIl0sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE9BQU8sU0FBU0EsWUFBWUEsQ0FBQ0MsSUFBWSxFQUFFQyxJQUFhLEVBQVU7RUFDaEUsSUFBSUEsSUFBSSxLQUFLQyxTQUFTLEVBQUU7SUFDdEIsT0FBT0YsSUFBSTtFQUNiOztFQUVBO0VBQ0E7RUFDQSxJQUFJQSxJQUFJLENBQUNHLFFBQVEsQ0FBQyxHQUFHLENBQUMsRUFBRTtJQUN0QixPQUFRLElBQUdILElBQUssS0FBSUMsSUFBSSxDQUFDRyxRQUFRLENBQUMsQ0FBRSxFQUFDO0VBQ3ZDO0VBRUEsT0FBUSxHQUFFSixJQUFLLElBQUdDLElBQUksQ0FBQ0csUUFBUSxDQUFDLENBQUUsRUFBQztBQUNyQyJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/post-policy.d.mts b/node_modules/minio/dist/esm/internal/post-policy.d.mts new file mode 100644 index 0000000..acdffdf --- /dev/null +++ b/node_modules/minio/dist/esm/internal/post-policy.d.mts @@ -0,0 +1,17 @@ +import type { ObjectMetaData } from "./type.mjs"; +export declare class PostPolicy { + policy: { + conditions: (string | number)[][]; + expiration?: string; + }; + formData: Record; + setExpires(date: Date): void; + setKey(objectName: string): void; + setKeyStartsWith(prefix: string): void; + setBucket(bucketName: string): void; + setContentType(type: string): void; + setContentTypeStartsWith(prefix: string): void; + setContentDisposition(value: string): void; + setContentLengthRange(min: number, max: number): void; + setUserMetaData(metaData: ObjectMetaData): void; +} \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/post-policy.mjs b/node_modules/minio/dist/esm/internal/post-policy.mjs new file mode 100644 index 0000000..afce763 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/post-policy.mjs @@ -0,0 +1,98 @@ +// Build PostPolicy object that can be signed by presignedPostPolicy +import * as errors from "../errors.mjs"; +import { isObject, isValidBucketName, isValidObjectName, isValidPrefix } from "./helper.mjs"; +export class PostPolicy { + policy = { + conditions: [] + }; + formData = {}; + + // set expiration date + setExpires(date) { + if (!date) { + throw new errors.InvalidDateError('Invalid date: cannot be null'); + } + this.policy.expiration = date.toISOString(); + } + + // set object name + setKey(objectName) { + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name : ${objectName}`); + } + this.policy.conditions.push(['eq', '$key', objectName]); + this.formData.key = objectName; + } + + // set object name prefix, i.e policy allows any keys with this prefix + setKeyStartsWith(prefix) { + if (!isValidPrefix(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`); + } + this.policy.conditions.push(['starts-with', '$key', prefix]); + this.formData.key = prefix; + } + + // set bucket name + setBucket(bucketName) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name : ${bucketName}`); + } + this.policy.conditions.push(['eq', '$bucket', bucketName]); + this.formData.bucket = bucketName; + } + + // set Content-Type + setContentType(type) { + if (!type) { + throw new Error('content-type cannot be null'); + } + this.policy.conditions.push(['eq', '$Content-Type', type]); + this.formData['Content-Type'] = type; + } + + // set Content-Type prefix, i.e image/ allows any image + setContentTypeStartsWith(prefix) { + if (!prefix) { + throw new Error('content-type cannot be null'); + } + this.policy.conditions.push(['starts-with', '$Content-Type', prefix]); + this.formData['Content-Type'] = prefix; + } + + // set Content-Disposition + setContentDisposition(value) { + if (!value) { + throw new Error('content-disposition cannot be null'); + } + this.policy.conditions.push(['eq', '$Content-Disposition', value]); + this.formData['Content-Disposition'] = value; + } + + // set minimum/maximum length of what Content-Length can be. + setContentLengthRange(min, max) { + if (min > max) { + throw new Error('min cannot be more than max'); + } + if (min < 0) { + throw new Error('min should be > 0'); + } + if (max < 0) { + throw new Error('max should be > 0'); + } + this.policy.conditions.push(['content-length-range', min, max]); + } + + // set user defined metadata + setUserMetaData(metaData) { + if (!isObject(metaData)) { + throw new TypeError('metadata should be of type "object"'); + } + Object.entries(metaData).forEach(([key, value]) => { + const amzMetaDataKey = `x-amz-meta-${key}`; + this.policy.conditions.push(['eq', `$${amzMetaDataKey}`, value]); + this.formData[amzMetaDataKey] = value.toString(); + }); + } +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJlcnJvcnMiLCJpc09iamVjdCIsImlzVmFsaWRCdWNrZXROYW1lIiwiaXNWYWxpZE9iamVjdE5hbWUiLCJpc1ZhbGlkUHJlZml4IiwiUG9zdFBvbGljeSIsInBvbGljeSIsImNvbmRpdGlvbnMiLCJmb3JtRGF0YSIsInNldEV4cGlyZXMiLCJkYXRlIiwiSW52YWxpZERhdGVFcnJvciIsImV4cGlyYXRpb24iLCJ0b0lTT1N0cmluZyIsInNldEtleSIsIm9iamVjdE5hbWUiLCJJbnZhbGlkT2JqZWN0TmFtZUVycm9yIiwicHVzaCIsImtleSIsInNldEtleVN0YXJ0c1dpdGgiLCJwcmVmaXgiLCJJbnZhbGlkUHJlZml4RXJyb3IiLCJzZXRCdWNrZXQiLCJidWNrZXROYW1lIiwiSW52YWxpZEJ1Y2tldE5hbWVFcnJvciIsImJ1Y2tldCIsInNldENvbnRlbnRUeXBlIiwidHlwZSIsIkVycm9yIiwic2V0Q29udGVudFR5cGVTdGFydHNX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/dist/esm/internal/request.d.mts new file mode 100644 index 0000000..60ff1cf --- /dev/null +++ b/node_modules/minio/dist/esm/internal/request.d.mts @@ -0,0 +1,11 @@ +/// +/// +/// +/// +import type * as http from 'node:http'; +import type * as https from 'node:https'; +import type * as stream from 'node:stream'; +import type { Transport } from "./type.mjs"; +export declare function request(transport: Transport, opt: https.RequestOptions, body?: Buffer | string | stream.Readable | null): Promise; +export declare const retryHttpCodes: Record; +export declare function requestWithRetry(transport: Transport, opt: https.RequestOptions, body?: Buffer | string | stream.Readable | null, maxRetries?: number, baseDelayMs?: number, maximumDelayMs?: number): Promise; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/request.mjs b/node_modules/minio/dist/esm/internal/request.mjs new file mode 100644 index 0000000..2ec047e --- /dev/null +++ b/node_modules/minio/dist/esm/internal/request.mjs @@ -0,0 +1,75 @@ +import { pipeline } from "stream"; +import { promisify } from "util"; +const pipelineAsync = promisify(pipeline); +export async function request(transport, opt, body = null) { + return new Promise((resolve, reject) => { + const requestObj = transport.request(opt, response => { + resolve(response); + }); + requestObj.on('error', reject); + if (!body || Buffer.isBuffer(body) || typeof body === 'string') { + requestObj.end(body); + } else { + pipelineAsync(body, requestObj).catch(reject); + } + }); +} +const MAX_RETRIES = 1; +const BASE_DELAY_MS = 100; // Base delay for exponential backoff +const MAX_DELAY_MS = 60000; // Max delay for exponential backoff + +// Retryable error codes for HTTP ( ref: minio-go) +export const retryHttpCodes = { + 408: true, + 429: true, + 499: true, + 500: true, + 502: true, + 503: true, + 504: true, + 520: true +}; +const isHttpRetryable = httpResCode => { + return retryHttpCodes[httpResCode] !== undefined; +}; +const sleep = ms => { + return new Promise(resolve => setTimeout(resolve, ms)); +}; +const getExpBackOffDelay = (retryCount, baseDelayMs, maximumDelayMs) => { + const backOffBy = baseDelayMs * (1 << retryCount); + const additionalDelay = Math.random() * backOffBy; + return Math.min(backOffBy + additionalDelay, maximumDelayMs); +}; +export async function requestWithRetry(transport, opt, body = null, maxRetries = MAX_RETRIES, baseDelayMs = BASE_DELAY_MS, maximumDelayMs = MAX_DELAY_MS) { + let attempt = 0; + let isRetryable = false; + while (attempt <= maxRetries) { + try { + const response = await request(transport, opt, body); + // Check if the HTTP status code is retryable + if (isHttpRetryable(response.statusCode)) { + isRetryable = true; + throw new Error(`Retryable HTTP status: ${response.statusCode}`); // trigger retry attempt with calculated delay + } + + return response; // Success, return the raw response + } catch (err) { + if (isRetryable) { + attempt++; + isRetryable = false; + if (attempt > maxRetries) { + throw new Error(`Request failed after ${maxRetries} retries: ${err}`); + } + const delay = getExpBackOffDelay(attempt, baseDelayMs, maximumDelayMs); + // eslint-disable-next-line no-console + console.warn(`${new Date().toLocaleString()} Retrying request (attempt ${attempt}/${maxRetries}) after ${delay}ms due to: ${err}`); + await sleep(delay); + } else { + throw err; // re-throw if any request, syntax errors + } + } + } + + throw new Error(`${MAX_RETRIES} Retries exhausted, request failed.`); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJwaXBlbGluZSIsInByb21pc2lmeSIsInBpcGVsaW5lQXN5bmMiLCJyZXF1ZXN0IiwidHJhbnNwb3J0Iiwib3B0IiwiYm9keSIsIlByb21pc2UiLCJyZXNvbHZlIiwicmVqZWN0IiwicmVxdWVzdE9iaiIsInJlc3BvbnNlIiwib24iLCJCdWZmZXIiLCJpc0J1ZmZlciIsImVuZCIsImNhdGNoIiwiTUFYX1JFVFJJRVMiLCJCQVNFX0RFTEFZX01TIiwiTUFYX0RFTEFZX01TIiwicmV0cnlIdHRwQ29kZXMiLCJpc0h0dHBSZXRyeWFibGUiLCJodHRwUmVzQ29kZSIsInVuZGVmaW5lZCIsInNsZWVwIiwibXMiLCJzZXRUaW1lb3V0IiwiZ2V0RXhwQmFja09mZkRlbGF5IiwicmV0cnlDb3VudCIsImJhc2VEZWxheU1zIiwibWF4aW11bURlbGF5TXMiLCJiYWNrT2ZmQnkiLCJhZGRpdGlvbmFsRGVs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FJQyxJQUFJLENBQUMsQ0FBQyxDQUFDQyxjQUFjLENBQUMsQ0FBRSw4QkFBNkJULE9BQVEsSUFBR0QsVUFBVyxXQUFVTSxLQUFNLGNBQWFELEdBQUksRUFDckgsQ0FBQztRQUNELE1BQU1sQixLQUFLLENBQUNtQixLQUFLLENBQUM7TUFDcEIsQ0FBQyxNQUFNO1FBQ0wsTUFBTUQsR0FBRyxFQUFDO01BQ1o7SUFDRjtFQUNGOztFQUVBLE1BQU0sSUFBSUQsS0FBSyxDQUFFLEdBQUV4QixXQUFZLHFDQUFvQyxDQUFDO0FBQ3RFIn0= \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/response.d.mts b/node_modules/minio/dist/esm/internal/response.d.mts new file mode 100644 index 0000000..6676ad9 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/response.d.mts @@ -0,0 +1,8 @@ +/// +/// +/// +import type http from 'node:http'; +import type stream from 'node:stream'; +export declare function readAsBuffer(res: stream.Readable): Promise; +export declare function readAsString(res: http.IncomingMessage): Promise; +export declare function drainResponse(res: stream.Readable): Promise; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/response.mjs b/node_modules/minio/dist/esm/internal/response.mjs new file mode 100644 index 0000000..51c4e07 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/response.mjs @@ -0,0 +1,16 @@ +export async function readAsBuffer(res) { + return new Promise((resolve, reject) => { + const body = []; + res.on('data', chunk => body.push(chunk)).on('error', e => reject(e)).on('end', () => resolve(Buffer.concat(body))); + }); +} +export async function readAsString(res) { + const body = await readAsBuffer(res); + return body.toString(); +} +export async function drainResponse(res) { + return new Promise((resolve, reject) => { + res.on('data', () => {}).on('error', e => reject(e)).on('end', () => resolve()); + }); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJyZWFkQXNCdWZmZXIiLCJyZXMiLCJQcm9taXNlIiwicmVzb2x2ZSIsInJlamVjdCIsImJvZHkiLCJ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sQ0FBQyxPQUFPLEVBQUdHLENBQUMsSUFBS0wsTUFBTSxDQUFDSyxDQUFDLENBQUMsQ0FBQyxDQUM3QkgsRUFBRSxDQUFDLEtBQUssRUFBRSxNQUFNSCxPQUFPLENBQUMsQ0FBQyxDQUFDO0VBQy9CLENBQUMsQ0FBQztBQUNKIn0= \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/s3-endpoints.d.mts b/node_modules/minio/dist/esm/internal/s3-endpoints.d.mts new file mode 100644 index 0000000..d26e9e2 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/s3-endpoints.d.mts @@ -0,0 +1,38 @@ +declare const awsS3Endpoint: { + 'af-south-1': string; + 'ap-east-1': string; + 'ap-south-1': string; + 'ap-south-2': string; + 'ap-southeast-1': string; + 'ap-southeast-2': string; + 'ap-southeast-3': string; + 'ap-southeast-4': string; + 'ap-southeast-5': string; + 'ap-northeast-1': string; + 'ap-northeast-2': string; + 'ap-northeast-3': string; + 'ca-central-1': string; + 'ca-west-1': string; + 'cn-north-1': string; + 'eu-central-1': string; + 'eu-central-2': string; + 'eu-north-1': string; + 'eu-south-1': string; + 'eu-south-2': string; + 'eu-west-1': string; + 'eu-west-2': string; + 'eu-west-3': string; + 'il-central-1': string; + 'me-central-1': string; + 'me-south-1': string; + 'sa-east-1': string; + 'us-east-1': string; + 'us-east-2': string; + 'us-west-1': string; + 'us-west-2': string; + 'us-gov-east-1': string; + 'us-gov-west-1': string; +}; +export type Region = keyof typeof awsS3Endpoint | string; +export declare function getS3Endpoint(region: Region): string; +export {}; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/s3-endpoints.mjs b/node_modules/minio/dist/esm/internal/s3-endpoints.mjs new file mode 100644 index 0000000..c040154 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/s3-endpoints.mjs @@ -0,0 +1,68 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015, 2016 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isString } from "./helper.mjs"; + +// List of currently supported endpoints. +const awsS3Endpoint = { + 'af-south-1': 's3.af-south-1.amazonaws.com', + 'ap-east-1': 's3.ap-east-1.amazonaws.com', + 'ap-south-1': 's3.ap-south-1.amazonaws.com', + 'ap-south-2': 's3.ap-south-2.amazonaws.com', + 'ap-southeast-1': 's3.ap-southeast-1.amazonaws.com', + 'ap-southeast-2': 's3.ap-southeast-2.amazonaws.com', + 'ap-southeast-3': 's3.ap-southeast-3.amazonaws.com', + 'ap-southeast-4': 's3.ap-southeast-4.amazonaws.com', + 'ap-southeast-5': 's3.ap-southeast-5.amazonaws.com', + 'ap-northeast-1': 's3.ap-northeast-1.amazonaws.com', + 'ap-northeast-2': 's3.ap-northeast-2.amazonaws.com', + 'ap-northeast-3': 's3.ap-northeast-3.amazonaws.com', + 'ca-central-1': 's3.ca-central-1.amazonaws.com', + 'ca-west-1': 's3.ca-west-1.amazonaws.com', + 'cn-north-1': 's3.cn-north-1.amazonaws.com.cn', + 'eu-central-1': 's3.eu-central-1.amazonaws.com', + 'eu-central-2': 's3.eu-central-2.amazonaws.com', + 'eu-north-1': 's3.eu-north-1.amazonaws.com', + 'eu-south-1': 's3.eu-south-1.amazonaws.com', + 'eu-south-2': 's3.eu-south-2.amazonaws.com', + 'eu-west-1': 's3.eu-west-1.amazonaws.com', + 'eu-west-2': 's3.eu-west-2.amazonaws.com', + 'eu-west-3': 's3.eu-west-3.amazonaws.com', + 'il-central-1': 's3.il-central-1.amazonaws.com', + 'me-central-1': 's3.me-central-1.amazonaws.com', + 'me-south-1': 's3.me-south-1.amazonaws.com', + 'sa-east-1': 's3.sa-east-1.amazonaws.com', + 'us-east-1': 's3.us-east-1.amazonaws.com', + 'us-east-2': 's3.us-east-2.amazonaws.com', + 'us-west-1': 's3.us-west-1.amazonaws.com', + 'us-west-2': 's3.us-west-2.amazonaws.com', + 'us-gov-east-1': 's3.us-gov-east-1.amazonaws.com', + 'us-gov-west-1': 's3.us-gov-west-1.amazonaws.com' + // Add new endpoints here. +}; + +// getS3Endpoint get relevant endpoint for the region. +export function getS3Endpoint(region) { + if (!isString(region)) { + throw new TypeError(`Invalid region: ${region}`); + } + const endpoint = awsS3Endpoint[region]; + if (endpoint) { + return endpoint; + } + return 's3.amazonaws.com'; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJpc1N0cmluZyIsImF3c1MzRW5kcG9pbnQiLCJnZXRTM0VuZHBvaW50IiwicmVnaW9uIiwiVHlwZUVycm9yIiwiZW5kcG9pbnQiXSwic291cmNlcyI6WyJzMy1lbmRwb2ludHMudHMiXSwic291cmNlc0NvbnRlbnQiOlsiLypcbiAqIE1pbklPIEphdmFzY3JpcHQgTGlicmFyeSBmb3IgQW1hem9uIFMzIENvbXBhdGlibGUgQ2xvdWQgU3RvcmFnZSwgKEMpIDIwMTUsIDIwMTYgTWluSU8sIEluYy5cbiAqXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgQXBhY2hlIExpY2Vuc2UsIFZlcnNpb24gMi4wICh0aGUgXCJMaWNlbnNlXCIpO1xuICogeW91IG1heSBub3QgdXNlIHRoaXMgZmlsZSBleGNlcHQgaW4gY29tcGxpYW5jZSB3aXRoIHRoZSBMaWNlbnNlLlxuICogWW91IG1heSBvYnRhaW4gYSBjb3B5IG9mIHRoZSBMaWNlbnNlIGF0XG4gKlxuICogICAgIGh0dHA6Ly93d3cuYXBhY2hlLm9yZy9saWNlbnNlcy9MSUNFTlNFLTIuMFxuICpcbiAqIFVubGVzcyByZXF1aXJlZCBieSBhcHBsaWNhYmxlIGxhdyBvciBh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RUFDekMsY0FBYyxFQUFFLCtCQUErQjtFQUMvQyxjQUFjLEVBQUUsK0JBQStCO0VBQy9DLFlBQVksRUFBRSw2QkFBNkI7RUFDM0MsV0FBVyxFQUFFLDRCQUE0QjtFQUN6QyxXQUFXLEVBQUUsNEJBQTRCO0VBQ3pDLFdBQVcsRUFBRSw0QkFBNEI7RUFDekMsV0FBVyxFQUFFLDRCQUE0QjtFQUN6QyxXQUFXLEVBQUUsNEJBQTRCO0VBQ3pDLGVBQWUsRUFBRSxnQ0FBZ0M7RUFDakQsZUFBZSxFQUFFO0VBQ2pCO0FBQ0YsQ0FBQzs7QUFJRDtBQUNBLE9BQU8sU0FBU0MsYUFBYUEsQ0FBQ0MsTUFBYyxFQUFVO0VBQ3BELElBQUksQ0FBQ0gsUUFBUSxDQUFDRyxNQUFNLENBQUMsRUFBRTtJQUNyQixNQUFNLElBQUlDLFNBQVMsQ0FBRSxtQkFBa0JELE1BQU8sRUFBQyxDQUFDO0VBQ2xEO0VBRUEsTUFBTUUsUUFBUSxHQUFJSixhQUFhLENBQTRCRSxNQUFNLENBQUM7RUFDbEUsSUFBSUUsUUFBUSxFQUFFO0lBQ1osT0FBT0EsUUFBUTtFQUNqQjtFQUNBLE9BQU8sa0JBQWtCO0FBQzNCIn0= \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/type.d.mts b/node_modules/minio/dist/esm/internal/type.d.mts new file mode 100644 index 0000000..c71e056 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/type.d.mts @@ -0,0 +1,482 @@ +/// +/// +/// +import type * as http from 'node:http'; +import type { Readable as ReadableStream } from 'node:stream'; +import type { CopyDestinationOptions, CopySourceOptions } from "../helpers.mjs"; +import type { CopyConditions } from "./copy-conditions.mjs"; +export type VersionIdentificator = { + versionId?: string; +}; +export type GetObjectOpts = VersionIdentificator & { + SSECustomerAlgorithm?: string; + SSECustomerKey?: string; + SSECustomerKeyMD5?: string; +}; +export type Binary = string | Buffer; +export type ResponseHeader = Record; +export type ObjectMetaData = Record; +export type RequestHeaders = Record; +export type EnabledOrDisabledStatus = 'Enabled' | 'Disabled'; +export declare const ENCRYPTION_TYPES: { + readonly SSEC: "SSE-C"; + readonly KMS: "KMS"; +}; +export type ENCRYPTION_TYPES = (typeof ENCRYPTION_TYPES)[keyof typeof ENCRYPTION_TYPES]; +export type Encryption = { + type: typeof ENCRYPTION_TYPES.SSEC; +} | { + type: typeof ENCRYPTION_TYPES.KMS; + SSEAlgorithm?: string; + KMSMasterKeyID?: string; +}; +export declare const RETENTION_MODES: { + readonly GOVERNANCE: "GOVERNANCE"; + readonly COMPLIANCE: "COMPLIANCE"; +}; +export type RETENTION_MODES = (typeof RETENTION_MODES)[keyof typeof RETENTION_MODES]; +export declare const RETENTION_VALIDITY_UNITS: { + readonly DAYS: "Days"; + readonly YEARS: "Years"; +}; +export type RETENTION_VALIDITY_UNITS = (typeof RETENTION_VALIDITY_UNITS)[keyof typeof RETENTION_VALIDITY_UNITS]; +export declare const LEGAL_HOLD_STATUS: { + readonly ENABLED: "ON"; + readonly DISABLED: "OFF"; +}; +export type LEGAL_HOLD_STATUS = (typeof LEGAL_HOLD_STATUS)[keyof typeof LEGAL_HOLD_STATUS]; +export type Transport = Pick; +export interface IRequest { + protocol: string; + port?: number | string; + method: string; + path: string; + headers: RequestHeaders; +} +export type ICanonicalRequest = string; +export interface IncompleteUploadedBucketItem { + key: string; + uploadId: string; + size: number; +} +export interface MetadataItem { + Key: string; + Value: string; +} +export interface ItemBucketMetadataList { + Items: MetadataItem[]; +} +export interface ItemBucketMetadata { + [key: string]: any; +} +export interface ItemBucketTags { + [key: string]: any; +} +export interface BucketItemFromList { + name: string; + creationDate: Date; +} +export interface BucketItemCopy { + etag: string; + lastModified: Date; +} +export type BucketItem = { + name: string; + size: number; + etag: string; + prefix?: never; + lastModified: Date; +} | { + name?: never; + etag?: never; + lastModified?: never; + prefix: string; + size: 0; +}; +export type BucketItemWithMetadata = BucketItem & { + metadata?: ItemBucketMetadata | ItemBucketMetadataList; + tags?: ItemBucketTags; +}; +export interface BucketStream extends ReadableStream { + on(event: 'data', listener: (item: T) => void): this; + on(event: 'end' | 'pause' | 'readable' | 'resume' | 'close', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; +} +export interface BucketItemStat { + size: number; + etag: string; + lastModified: Date; + metaData: ItemBucketMetadata; + versionId?: string | null; +} +export type StatObjectOpts = { + versionId?: string; +}; +export type ReplicationRuleStatus = { + Status: EnabledOrDisabledStatus; +}; +export type Tag = { + Key: string; + Value: string; +}; +export type Tags = Record; +export type ReplicationRuleDestination = { + Bucket: string; + StorageClass: string; +}; +export type ReplicationRuleAnd = { + Prefix: string; + Tags: Tag[]; +}; +export type ReplicationRuleFilter = { + Prefix: string; + And: ReplicationRuleAnd; + Tag: Tag; +}; +export type ReplicaModifications = { + Status: ReplicationRuleStatus; +}; +export type SourceSelectionCriteria = { + ReplicaModifications: ReplicaModifications; +}; +export type ExistingObjectReplication = { + Status: ReplicationRuleStatus; +}; +export type ReplicationRule = { + ID: string; + Status: ReplicationRuleStatus; + Priority: number; + DeleteMarkerReplication: ReplicationRuleStatus; + DeleteReplication: ReplicationRuleStatus; + Destination: ReplicationRuleDestination; + Filter: ReplicationRuleFilter; + SourceSelectionCriteria: SourceSelectionCriteria; + ExistingObjectReplication: ExistingObjectReplication; +}; +export type ReplicationConfigOpts = { + role: string; + rules: ReplicationRule[]; +}; +export type ReplicationConfig = { + ReplicationConfiguration: ReplicationConfigOpts; +}; +export type ResultCallback = (error: Error | null, result: T) => void; +export type GetObjectLegalHoldOptions = { + versionId: string; +}; +/** + * @deprecated keep for backward compatible, use `LEGAL_HOLD_STATUS` instead + */ +export type LegalHoldStatus = LEGAL_HOLD_STATUS; +export type PutObjectLegalHoldOptions = { + versionId?: string; + status: LEGAL_HOLD_STATUS; +}; +export interface UploadedObjectInfo { + etag: string; + versionId: string | null; +} +export interface RetentionOptions { + versionId: string; + mode?: RETENTION_MODES; + retainUntilDate?: IsoDate; + governanceBypass?: boolean; +} +export type Retention = RetentionOptions | EmptyObject; +export type IsoDate = string; +export type EmptyObject = Record; +export type ObjectLockInfo = { + objectLockEnabled: EnabledOrDisabledStatus; + mode: RETENTION_MODES; + unit: RETENTION_VALIDITY_UNITS; + validity: number; +} | EmptyObject; +export type ObjectLockConfigParam = { + ObjectLockEnabled?: 'Enabled' | undefined; + Rule?: { + DefaultRetention: { + Mode: RETENTION_MODES; + Days: number; + Years: number; + } | EmptyObject; + } | EmptyObject; +}; +export type VersioningEnabled = 'Enabled'; +export type VersioningSuspended = 'Suspended'; +export type TaggingOpts = { + versionId: string; +}; +export type PutTaggingParams = { + bucketName: string; + objectName?: string; + tags: Tags; + putOpts?: TaggingOpts; +}; +export type RemoveTaggingParams = { + bucketName: string; + objectName?: string; + removeOpts?: TaggingOpts; +}; +export type InputSerialization = { + CompressionType?: 'NONE' | 'GZIP' | 'BZIP2'; + CSV?: { + AllowQuotedRecordDelimiter?: boolean; + Comments?: string; + FieldDelimiter?: string; + FileHeaderInfo?: 'NONE' | 'IGNORE' | 'USE'; + QuoteCharacter?: string; + QuoteEscapeCharacter?: string; + RecordDelimiter?: string; + }; + JSON?: { + Type: 'DOCUMENT' | 'LINES'; + }; + Parquet?: EmptyObject; +}; +export type OutputSerialization = { + CSV?: { + FieldDelimiter?: string; + QuoteCharacter?: string; + QuoteEscapeCharacter?: string; + QuoteFields?: string; + RecordDelimiter?: string; + }; + JSON?: { + RecordDelimiter?: string; + }; +}; +export type SelectProgress = { + Enabled: boolean; +}; +export type ScanRange = { + Start: number; + End: number; +}; +export type SelectOptions = { + expression: string; + expressionType?: string; + inputSerialization: InputSerialization; + outputSerialization: OutputSerialization; + requestProgress?: SelectProgress; + scanRange?: ScanRange; +}; +export type Expiration = { + Date?: string; + Days: number; + DeleteMarker?: boolean; + DeleteAll?: boolean; +}; +export type RuleFilterAnd = { + Prefix: string; + Tags: Tag[]; +}; +export type RuleFilter = { + And?: RuleFilterAnd; + Prefix: string; + Tag?: Tag[]; +}; +export type NoncurrentVersionExpiration = { + NoncurrentDays: number; + NewerNoncurrentVersions?: number; +}; +export type NoncurrentVersionTransition = { + StorageClass: string; + NoncurrentDays?: number; + NewerNoncurrentVersions?: number; +}; +export type Transition = { + Date?: string; + StorageClass: string; + Days: number; +}; +export type AbortIncompleteMultipartUpload = { + DaysAfterInitiation: number; +}; +export type LifecycleRule = { + AbortIncompleteMultipartUpload?: AbortIncompleteMultipartUpload; + ID: string; + Prefix?: string; + Status?: string; + Expiration?: Expiration; + Filter?: RuleFilter; + NoncurrentVersionExpiration?: NoncurrentVersionExpiration; + NoncurrentVersionTransition?: NoncurrentVersionTransition; + Transition?: Transition; +}; +export type LifecycleConfig = { + Rule: LifecycleRule[]; +}; +export type LifeCycleConfigParam = LifecycleConfig | null | undefined | ''; +export type ApplySSEByDefault = { + KmsMasterKeyID?: string; + SSEAlgorithm: string; +}; +export type EncryptionRule = { + ApplyServerSideEncryptionByDefault?: ApplySSEByDefault; +}; +export type EncryptionConfig = { + Rule: EncryptionRule[]; +}; +export type GetObjectRetentionOpts = { + versionId: string; +}; +export type ObjectRetentionInfo = { + mode: RETENTION_MODES; + retainUntilDate: string; +}; +export type RemoveObjectsEntry = { + name: string; + versionId?: string; +}; +export type ObjectName = string; +export type RemoveObjectsParam = ObjectName[] | RemoveObjectsEntry[]; +export type RemoveObjectsRequestEntry = { + Key: string; + VersionId?: string; +}; +export type RemoveObjectsResponse = null | undefined | { + Error?: { + Code?: string; + Message?: string; + Key?: string; + VersionId?: string; + }; +}; +export type CopyObjectResultV1 = { + etag: string; + lastModified: string | Date; +}; +export type CopyObjectResultV2 = { + Bucket?: string; + Key?: string; + LastModified: string | Date; + MetaData?: ResponseHeader; + VersionId?: string | null; + SourceVersionId?: string | null; + Etag?: string; + Size?: number; +}; +export type CopyObjectResult = CopyObjectResultV1 | CopyObjectResultV2; +export type CopyObjectParams = [CopySourceOptions, CopyDestinationOptions] | [string, string, string, CopyConditions?]; +export type ExcludedPrefix = { + Prefix: string; +}; +export type BucketVersioningConfiguration = { + Status: VersioningEnabled | VersioningSuspended; + MFADelete?: string; + ExcludedPrefixes?: ExcludedPrefix[]; + ExcludeFolders?: boolean; +}; +export type UploadPartConfig = { + bucketName: string; + objectName: string; + uploadID: string; + partNumber: number; + headers: RequestHeaders; + sourceObj: string; +}; +export type PreSignRequestParams = { + [key: string]: string; +}; +/** List object api types **/ +export type CommonPrefix = { + Prefix: string; +}; +export type Owner = { + ID: string; + DisplayName: string; +}; +export type Metadata = { + Items: MetadataItem[]; +}; +export type ObjectInfo = { + key?: string; + name?: string; + lastModified?: Date; + etag?: string; + owner?: Owner; + storageClass?: string; + userMetadata?: Metadata; + userTags?: string; + prefix?: string; + size?: number; +}; +export type ListObjectQueryRes = { + isTruncated?: boolean; + nextMarker?: string; + objects?: ObjectInfo[]; + keyMarker?: string; + versionIdMarker?: string; +}; +export type ListObjectQueryOpts = { + Delimiter?: string; + MaxKeys?: number; + IncludeVersion?: boolean; + keyMarker?: string; + versionIdMarker?: string; +}; +/** List object api types **/ +export type ObjectVersionEntry = { + IsLatest?: string; + VersionId?: string; +}; +export type ObjectRowEntry = ObjectVersionEntry & { + Key: string; + LastModified?: Date | undefined; + ETag?: string; + Size?: string; + Owner?: Owner; + StorageClass?: string; +}; +export type ListObjectV2Res = { + objects: BucketItem[]; + isTruncated: boolean; + nextContinuationToken: string; +}; +export type NotificationConfigEntry = { + Id: string; + Event: string[]; + Filter: { + Name: string; + Value: string; + }[]; +}; +export type TopicConfigEntry = NotificationConfigEntry & { + Topic: string; +}; +export type QueueConfigEntry = NotificationConfigEntry & { + Queue: string; +}; +export type CloudFunctionConfigEntry = NotificationConfigEntry & { + CloudFunction: string; +}; +export type NotificationConfigResult = { + TopicConfiguration: TopicConfigEntry[]; + QueueConfiguration: QueueConfigEntry[]; + CloudFunctionConfiguration: CloudFunctionConfigEntry[]; +}; +export interface ListBucketResultV1 { + Name?: string; + Prefix?: string; + ContinuationToken?: string; + KeyCount?: string; + Marker?: string; + MaxKeys?: string; + Delimiter?: string; + IsTruncated?: boolean; + Contents?: ObjectRowEntry[]; + NextKeyMarker?: string; + CommonPrefixes?: CommonPrefix[]; + Version?: ObjectRowEntry[]; + DeleteMarker?: ObjectRowEntry[]; + VersionIdMarker?: string; + NextVersionIdMarker?: string; + NextMarker?: string; +} +export interface PostPolicyResult { + postURL: string; + formData: { + [key: string]: any; + }; +} \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/type.mjs b/node_modules/minio/dist/esm/internal/type.mjs new file mode 100644 index 0000000..5f938a3 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/type.mjs @@ -0,0 +1,30 @@ +// nodejs IncomingHttpHeaders is Record, but it's actually this: + +export const ENCRYPTION_TYPES = { + SSEC: 'SSE-C', + KMS: 'KMS' +}; +export const RETENTION_MODES = { + GOVERNANCE: 'GOVERNANCE', + COMPLIANCE: 'COMPLIANCE' +}; +export const RETENTION_VALIDITY_UNITS = { + DAYS: 'Days', + YEARS: 'Years' +}; +export const LEGAL_HOLD_STATUS = { + ENABLED: 'ON', + DISABLED: 'OFF' +}; + +/* Replication Config types */ + +/* Replication Config types */ + +/** + * @deprecated keep for backward compatible, use `LEGAL_HOLD_STATUS` instead + */ + +/** List object api types **/ // Common types +/** List object api types **/ +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJFTkNSWVBUSU9OX1RZUEVTIiwiU1NFQyIsIktNUyIsIlJFVEVOVElPTl9NT0RFUyIsIkdPVkVSTkFOQ0UiLCJDT01QTElBTkNFIiwiUkVURU5USU9OX1ZBTElESVRZX1VOSVRTIiwiREFZUyIsIllFQVJTIiwiTEVHQUxfSE9MRF9TVEFUVVMiLCJFTkFCTEVEIiwiRElTQUJMRUQiXSwic291cmNlcyI6WyJ0eXBlLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB0eXBlICogY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UEEsOEJBRUE7QUE0Q0EifQ== \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/xml-parser.d.mts b/node_modules/minio/dist/esm/internal/xml-parser.d.mts new file mode 100644 index 0000000..f0f2365 --- /dev/null +++ b/node_modules/minio/dist/esm/internal/xml-parser.d.mts @@ -0,0 +1,93 @@ +/// +/// +import type * as http from 'node:http'; +import { SelectResults } from "../helpers.mjs"; +import type { BucketItemFromList, BucketItemWithMetadata, CopyObjectResultV1, ListObjectV2Res, NotificationConfigResult, ObjectInfo, ObjectLockInfo, ReplicationConfig, Tag } from "./type.mjs"; +export declare function parseBucketRegion(xml: string): string; +export declare function parseError(xml: string, headerInfo: Record): Record; +export declare function parseResponseError(response: http.IncomingMessage): Promise>; +/** + * parse XML response for list objects v2 with metadata in a bucket + */ +export declare function parseListObjectsV2WithMetadata(xml: string): { + objects: Array; + isTruncated: boolean; + nextContinuationToken: string; +}; +export declare function parseListObjectsV2(xml: string): ListObjectV2Res; +export declare function parseBucketNotification(xml: string): NotificationConfigResult; +export type UploadedPart = { + part: number; + lastModified?: Date; + etag: string; + size: number; +}; +export declare function parseListParts(xml: string): { + isTruncated: boolean; + marker: number; + parts: UploadedPart[]; +}; +export declare function parseListBucket(xml: string): BucketItemFromList[]; +export declare function parseInitiateMultipart(xml: string): string; +export declare function parseReplicationConfig(xml: string): ReplicationConfig; +export declare function parseObjectLegalHoldConfig(xml: string): any; +export declare function parseTagging(xml: string): Tag[]; +export declare function parseCompleteMultipart(xml: string): { + location: any; + bucket: any; + key: any; + etag: any; + errCode?: undefined; + errMessage?: undefined; +} | { + errCode: any; + errMessage: any; + location?: undefined; + bucket?: undefined; + key?: undefined; + etag?: undefined; +} | undefined; +type UploadID = string; +export type ListMultipartResult = { + uploads: { + key: string; + uploadId: UploadID; + initiator?: { + id: string; + displayName: string; + }; + owner?: { + id: string; + displayName: string; + }; + storageClass: unknown; + initiated: Date; + }[]; + prefixes: { + prefix: string; + }[]; + isTruncated: boolean; + nextKeyMarker: string; + nextUploadIdMarker: string; +}; +export declare function parseListMultipart(xml: string): ListMultipartResult; +export declare function parseObjectLockConfig(xml: string): ObjectLockInfo; +export declare function parseBucketVersioningConfig(xml: string): any; +export declare function parseSelectObjectContentResponse(res: Buffer): SelectResults | undefined; +export declare function parseLifecycleConfig(xml: string): any; +export declare function parseBucketEncryptionConfig(xml: string): any; +export declare function parseObjectRetentionConfig(xml: string): { + mode: any; + retainUntilDate: any; +}; +export declare function removeObjectsParser(xml: string): any[]; +export declare function parseCopyObject(xml: string): CopyObjectResultV1; +export declare function parseListObjects(xml: string): { + objects: ObjectInfo[]; + isTruncated?: boolean | undefined; + nextMarker?: string | undefined; + versionIdMarker?: string | undefined; + keyMarker?: string | undefined; +}; +export declare function uploadPartParser(xml: string): any; +export {}; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/internal/xml-parser.mjs b/node_modules/minio/dist/esm/internal/xml-parser.mjs new file mode 100644 index 0000000..747646c --- /dev/null +++ b/node_modules/minio/dist/esm/internal/xml-parser.mjs @@ -0,0 +1,818 @@ +import crc32 from 'buffer-crc32'; +import { XMLParser } from 'fast-xml-parser'; +import * as errors from "../errors.mjs"; +import { SelectResults } from "../helpers.mjs"; +import { isObject, parseXml, readableStream, sanitizeETag, sanitizeObjectKey, sanitizeSize, toArray } from "./helper.mjs"; +import { readAsString } from "./response.mjs"; +import { RETENTION_VALIDITY_UNITS } from "./type.mjs"; + +// parse XML response for bucket region +export function parseBucketRegion(xml) { + // return region information + return parseXml(xml).LocationConstraint; +} +const fxp = new XMLParser(); +const fxpWithoutNumParser = new XMLParser({ + // @ts-ignore + numberParseOptions: { + skipLike: /./ + } +}); + +// Parse XML and return information as Javascript types +// parse error XML response +export function parseError(xml, headerInfo) { + let xmlErr = {}; + const xmlObj = fxp.parse(xml); + if (xmlObj.Error) { + xmlErr = xmlObj.Error; + } + const e = new errors.S3Error(); + Object.entries(xmlErr).forEach(([key, value]) => { + e[key.toLowerCase()] = value; + }); + Object.entries(headerInfo).forEach(([key, value]) => { + e[key] = value; + }); + return e; +} + +// Generates an Error object depending on http statusCode and XML body +export async function parseResponseError(response) { + const statusCode = response.statusCode; + let code = '', + message = ''; + if (statusCode === 301) { + code = 'MovedPermanently'; + message = 'Moved Permanently'; + } else if (statusCode === 307) { + code = 'TemporaryRedirect'; + message = 'Are you using the correct endpoint URL?'; + } else if (statusCode === 403) { + code = 'AccessDenied'; + message = 'Valid and authorized credentials required'; + } else if (statusCode === 404) { + code = 'NotFound'; + message = 'Not Found'; + } else if (statusCode === 405) { + code = 'MethodNotAllowed'; + message = 'Method Not Allowed'; + } else if (statusCode === 501) { + code = 'MethodNotAllowed'; + message = 'Method Not Allowed'; + } else if (statusCode === 503) { + code = 'SlowDown'; + message = 'Please reduce your request rate.'; + } else { + const hErrCode = response.headers['x-minio-error-code']; + const hErrDesc = response.headers['x-minio-error-desc']; + if (hErrCode && hErrDesc) { + code = hErrCode; + message = hErrDesc; + } + } + const headerInfo = {}; + // A value created by S3 compatible server that uniquely identifies the request. + headerInfo.amzRequestid = response.headers['x-amz-request-id']; + // A special token that helps troubleshoot API replies and issues. + headerInfo.amzId2 = response.headers['x-amz-id-2']; + + // Region where the bucket is located. This header is returned only + // in HEAD bucket and ListObjects response. + headerInfo.amzBucketRegion = response.headers['x-amz-bucket-region']; + const xmlString = await readAsString(response); + if (xmlString) { + throw parseError(xmlString, headerInfo); + } + + // Message should be instantiated for each S3Errors. + const e = new errors.S3Error(message, { + cause: headerInfo + }); + // S3 Error code. + e.code = code; + Object.entries(headerInfo).forEach(([key, value]) => { + // @ts-expect-error force set error properties + e[key] = value; + }); + throw e; +} + +/** + * parse XML response for list objects v2 with metadata in a bucket + */ +export function parseListObjectsV2WithMetadata(xml) { + const result = { + objects: [], + isTruncated: false, + nextContinuationToken: '' + }; + let xmlobj = parseXml(xml); + if (!xmlobj.ListBucketResult) { + throw new errors.InvalidXMLError('Missing tag: "ListBucketResult"'); + } + xmlobj = xmlobj.ListBucketResult; + if (xmlobj.IsTruncated) { + result.isTruncated = xmlobj.IsTruncated; + } + if (xmlobj.NextContinuationToken) { + result.nextContinuationToken = xmlobj.NextContinuationToken; + } + if (xmlobj.Contents) { + toArray(xmlobj.Contents).forEach(content => { + const name = sanitizeObjectKey(content.Key); + const lastModified = new Date(content.LastModified); + const etag = sanitizeETag(content.ETag); + const size = content.Size; + let tags = {}; + if (content.UserTags != null) { + toArray(content.UserTags.split('&')).forEach(tag => { + const [key, value] = tag.split('='); + tags[key] = value; + }); + } else { + tags = {}; + } + let metadata; + if (content.UserMetadata != null) { + metadata = toArray(content.UserMetadata)[0]; + } else { + metadata = null; + } + result.objects.push({ + name, + lastModified, + etag, + size, + metadata, + tags + }); + }); + } + if (xmlobj.CommonPrefixes) { + toArray(xmlobj.CommonPrefixes).forEach(commonPrefix => { + result.objects.push({ + prefix: sanitizeObjectKey(toArray(commonPrefix.Prefix)[0]), + size: 0 + }); + }); + } + return result; +} +export function parseListObjectsV2(xml) { + const result = { + objects: [], + isTruncated: false, + nextContinuationToken: '' + }; + let xmlobj = parseXml(xml); + if (!xmlobj.ListBucketResult) { + throw new errors.InvalidXMLError('Missing tag: "ListBucketResult"'); + } + xmlobj = xmlobj.ListBucketResult; + if (xmlobj.IsTruncated) { + result.isTruncated = xmlobj.IsTruncated; + } + if (xmlobj.NextContinuationToken) { + result.nextContinuationToken = xmlobj.NextContinuationToken; + } + if (xmlobj.Contents) { + toArray(xmlobj.Contents).forEach(content => { + const name = sanitizeObjectKey(toArray(content.Key)[0]); + const lastModified = new Date(content.LastModified); + const etag = sanitizeETag(content.ETag); + const size = content.Size; + result.objects.push({ + name, + lastModified, + etag, + size + }); + }); + } + if (xmlobj.CommonPrefixes) { + toArray(xmlobj.CommonPrefixes).forEach(commonPrefix => { + result.objects.push({ + prefix: sanitizeObjectKey(toArray(commonPrefix.Prefix)[0]), + size: 0 + }); + }); + } + return result; +} +export function parseBucketNotification(xml) { + const result = { + TopicConfiguration: [], + QueueConfiguration: [], + CloudFunctionConfiguration: [] + }; + const genEvents = events => { + if (!events) { + return []; + } + return toArray(events); + }; + const genFilterRules = filters => { + var _filterArr$; + const rules = []; + if (!filters) { + return rules; + } + const filterArr = toArray(filters); + if ((_filterArr$ = filterArr[0]) !== null && _filterArr$ !== void 0 && _filterArr$.S3Key) { + var _s3KeyArr$; + const s3KeyArr = toArray(filterArr[0].S3Key); + if ((_s3KeyArr$ = s3KeyArr[0]) !== null && _s3KeyArr$ !== void 0 && _s3KeyArr$.FilterRule) { + toArray(s3KeyArr[0].FilterRule).forEach(rule => { + const r = rule; + const Name = toArray(r.Name)[0]; + const Value = toArray(r.Value)[0]; + rules.push({ + Name, + Value + }); + }); + } + } + return rules; + }; + let xmlobj = parseXml(xml); + xmlobj = xmlobj.NotificationConfiguration; + if (xmlobj.TopicConfiguration) { + toArray(xmlobj.TopicConfiguration).forEach(config => { + const Id = toArray(config.Id)[0]; + const Topic = toArray(config.Topic)[0]; + const Event = genEvents(config.Event); + const Filter = genFilterRules(config.Filter); + result.TopicConfiguration.push({ + Id, + Topic, + Event, + Filter + }); + }); + } + if (xmlobj.QueueConfiguration) { + toArray(xmlobj.QueueConfiguration).forEach(config => { + const Id = toArray(config.Id)[0]; + const Queue = toArray(config.Queue)[0]; + const Event = genEvents(config.Event); + const Filter = genFilterRules(config.Filter); + result.QueueConfiguration.push({ + Id, + Queue, + Event, + Filter + }); + }); + } + if (xmlobj.CloudFunctionConfiguration) { + toArray(xmlobj.CloudFunctionConfiguration).forEach(config => { + const Id = toArray(config.Id)[0]; + const CloudFunction = toArray(config.CloudFunction)[0]; + const Event = genEvents(config.Event); + const Filter = genFilterRules(config.Filter); + result.CloudFunctionConfiguration.push({ + Id, + CloudFunction, + Event, + Filter + }); + }); + } + return result; +} +// parse XML response for list parts of an in progress multipart upload +export function parseListParts(xml) { + let xmlobj = parseXml(xml); + const result = { + isTruncated: false, + parts: [], + marker: 0 + }; + if (!xmlobj.ListPartsResult) { + throw new errors.InvalidXMLError('Missing tag: "ListPartsResult"'); + } + xmlobj = xmlobj.ListPartsResult; + if (xmlobj.IsTruncated) { + result.isTruncated = xmlobj.IsTruncated; + } + if (xmlobj.NextPartNumberMarker) { + result.marker = toArray(xmlobj.NextPartNumberMarker)[0] || ''; + } + if (xmlobj.Part) { + toArray(xmlobj.Part).forEach(p => { + const part = parseInt(toArray(p.PartNumber)[0], 10); + const lastModified = new Date(p.LastModified); + const etag = p.ETag.replace(/^"/g, '').replace(/"$/g, '').replace(/^"/g, '').replace(/"$/g, '').replace(/^"/g, '').replace(/"$/g, ''); + result.parts.push({ + part, + lastModified, + etag, + size: parseInt(p.Size, 10) + }); + }); + } + return result; +} +export function parseListBucket(xml) { + let result = []; + const listBucketResultParser = new XMLParser({ + parseTagValue: true, + // Enable parsing of values + numberParseOptions: { + leadingZeros: false, + // Disable number parsing for values with leading zeros + hex: false, + // Disable hex number parsing - Invalid bucket name + skipLike: /^[0-9]+$/ // Skip number parsing if the value consists entirely of digits + }, + + tagValueProcessor: (tagName, tagValue = '') => { + // Ensure that the Name tag is always treated as a string + if (tagName === 'Name') { + return tagValue.toString(); + } + return tagValue; + }, + ignoreAttributes: false // Ensure that all attributes are parsed + }); + + const parsedXmlRes = listBucketResultParser.parse(xml); + if (!parsedXmlRes.ListAllMyBucketsResult) { + throw new errors.InvalidXMLError('Missing tag: "ListAllMyBucketsResult"'); + } + const { + ListAllMyBucketsResult: { + Buckets = {} + } = {} + } = parsedXmlRes; + if (Buckets.Bucket) { + result = toArray(Buckets.Bucket).map((bucket = {}) => { + const { + Name: bucketName, + CreationDate + } = bucket; + const creationDate = new Date(CreationDate); + return { + name: bucketName, + creationDate + }; + }); + } + return result; +} +export function parseInitiateMultipart(xml) { + let xmlobj = parseXml(xml); + if (!xmlobj.InitiateMultipartUploadResult) { + throw new errors.InvalidXMLError('Missing tag: "InitiateMultipartUploadResult"'); + } + xmlobj = xmlobj.InitiateMultipartUploadResult; + if (xmlobj.UploadId) { + return xmlobj.UploadId; + } + throw new errors.InvalidXMLError('Missing tag: "UploadId"'); +} +export function parseReplicationConfig(xml) { + const xmlObj = parseXml(xml); + const { + Role, + Rule + } = xmlObj.ReplicationConfiguration; + return { + ReplicationConfiguration: { + role: Role, + rules: toArray(Rule) + } + }; +} +export function parseObjectLegalHoldConfig(xml) { + const xmlObj = parseXml(xml); + return xmlObj.LegalHold; +} +export function parseTagging(xml) { + const xmlObj = parseXml(xml); + let result = []; + if (xmlObj.Tagging && xmlObj.Tagging.TagSet && xmlObj.Tagging.TagSet.Tag) { + const tagResult = xmlObj.Tagging.TagSet.Tag; + // if it is a single tag convert into an array so that the return value is always an array. + if (Array.isArray(tagResult)) { + result = [...tagResult]; + } else { + result.push(tagResult); + } + } + return result; +} + +// parse XML response when a multipart upload is completed +export function parseCompleteMultipart(xml) { + const xmlobj = parseXml(xml).CompleteMultipartUploadResult; + if (xmlobj.Location) { + const location = toArray(xmlobj.Location)[0]; + const bucket = toArray(xmlobj.Bucket)[0]; + const key = xmlobj.Key; + const etag = xmlobj.ETag.replace(/^"/g, '').replace(/"$/g, '').replace(/^"/g, '').replace(/"$/g, '').replace(/^"/g, '').replace(/"$/g, ''); + return { + location, + bucket, + key, + etag + }; + } + // Complete Multipart can return XML Error after a 200 OK response + if (xmlobj.Code && xmlobj.Message) { + const errCode = toArray(xmlobj.Code)[0]; + const errMessage = toArray(xmlobj.Message)[0]; + return { + errCode, + errMessage + }; + } +} +// parse XML response for listing in-progress multipart uploads +export function parseListMultipart(xml) { + const result = { + prefixes: [], + uploads: [], + isTruncated: false, + nextKeyMarker: '', + nextUploadIdMarker: '' + }; + let xmlobj = parseXml(xml); + if (!xmlobj.ListMultipartUploadsResult) { + throw new errors.InvalidXMLError('Missing tag: "ListMultipartUploadsResult"'); + } + xmlobj = xmlobj.ListMultipartUploadsResult; + if (xmlobj.IsTruncated) { + result.isTruncated = xmlobj.IsTruncated; + } + if (xmlobj.NextKeyMarker) { + result.nextKeyMarker = xmlobj.NextKeyMarker; + } + if (xmlobj.NextUploadIdMarker) { + result.nextUploadIdMarker = xmlobj.nextUploadIdMarker || ''; + } + if (xmlobj.CommonPrefixes) { + toArray(xmlobj.CommonPrefixes).forEach(prefix => { + // @ts-expect-error index check + result.prefixes.push({ + prefix: sanitizeObjectKey(toArray(prefix.Prefix)[0]) + }); + }); + } + if (xmlobj.Upload) { + toArray(xmlobj.Upload).forEach(upload => { + const uploadItem = { + key: upload.Key, + uploadId: upload.UploadId, + storageClass: upload.StorageClass, + initiated: new Date(upload.Initiated) + }; + if (upload.Initiator) { + uploadItem.initiator = { + id: upload.Initiator.ID, + displayName: upload.Initiator.DisplayName + }; + } + if (upload.Owner) { + uploadItem.owner = { + id: upload.Owner.ID, + displayName: upload.Owner.DisplayName + }; + } + result.uploads.push(uploadItem); + }); + } + return result; +} +export function parseObjectLockConfig(xml) { + const xmlObj = parseXml(xml); + let lockConfigResult = {}; + if (xmlObj.ObjectLockConfiguration) { + lockConfigResult = { + objectLockEnabled: xmlObj.ObjectLockConfiguration.ObjectLockEnabled + }; + let retentionResp; + if (xmlObj.ObjectLockConfiguration && xmlObj.ObjectLockConfiguration.Rule && xmlObj.ObjectLockConfiguration.Rule.DefaultRetention) { + retentionResp = xmlObj.ObjectLockConfiguration.Rule.DefaultRetention || {}; + lockConfigResult.mode = retentionResp.Mode; + } + if (retentionResp) { + const isUnitYears = retentionResp.Years; + if (isUnitYears) { + lockConfigResult.validity = isUnitYears; + lockConfigResult.unit = RETENTION_VALIDITY_UNITS.YEARS; + } else { + lockConfigResult.validity = retentionResp.Days; + lockConfigResult.unit = RETENTION_VALIDITY_UNITS.DAYS; + } + } + } + return lockConfigResult; +} +export function parseBucketVersioningConfig(xml) { + const xmlObj = parseXml(xml); + return xmlObj.VersioningConfiguration; +} + +// Used only in selectObjectContent API. +// extractHeaderType extracts the first half of the header message, the header type. +function extractHeaderType(stream) { + const headerNameLen = Buffer.from(stream.read(1)).readUInt8(); + const headerNameWithSeparator = Buffer.from(stream.read(headerNameLen)).toString(); + const splitBySeparator = (headerNameWithSeparator || '').split(':'); + return splitBySeparator.length >= 1 ? splitBySeparator[1] : ''; +} +function extractHeaderValue(stream) { + const bodyLen = Buffer.from(stream.read(2)).readUInt16BE(); + return Buffer.from(stream.read(bodyLen)).toString(); +} +export function parseSelectObjectContentResponse(res) { + const selectResults = new SelectResults({}); // will be returned + + const responseStream = readableStream(res); // convert byte array to a readable responseStream + // @ts-ignore + while (responseStream._readableState.length) { + // Top level responseStream read tracker. + let msgCrcAccumulator; // accumulate from start of the message till the message crc start. + + const totalByteLengthBuffer = Buffer.from(responseStream.read(4)); + msgCrcAccumulator = crc32(totalByteLengthBuffer); + const headerBytesBuffer = Buffer.from(responseStream.read(4)); + msgCrcAccumulator = crc32(headerBytesBuffer, msgCrcAccumulator); + const calculatedPreludeCrc = msgCrcAccumulator.readInt32BE(); // use it to check if any CRC mismatch in header itself. + + const preludeCrcBuffer = Buffer.from(responseStream.read(4)); // read 4 bytes i.e 4+4 =8 + 4 = 12 ( prelude + prelude crc) + msgCrcAccumulator = crc32(preludeCrcBuffer, msgCrcAccumulator); + const totalMsgLength = totalByteLengthBuffer.readInt32BE(); + const headerLength = headerBytesBuffer.readInt32BE(); + const preludeCrcByteValue = preludeCrcBuffer.readInt32BE(); + if (preludeCrcByteValue !== calculatedPreludeCrc) { + // Handle Header CRC mismatch Error + throw new Error(`Header Checksum Mismatch, Prelude CRC of ${preludeCrcByteValue} does not equal expected CRC of ${calculatedPreludeCrc}`); + } + const headers = {}; + if (headerLength > 0) { + const headerBytes = Buffer.from(responseStream.read(headerLength)); + msgCrcAccumulator = crc32(headerBytes, msgCrcAccumulator); + const headerReaderStream = readableStream(headerBytes); + // @ts-ignore + while (headerReaderStream._readableState.length) { + const headerTypeName = extractHeaderType(headerReaderStream); + headerReaderStream.read(1); // just read and ignore it. + if (headerTypeName) { + headers[headerTypeName] = extractHeaderValue(headerReaderStream); + } + } + } + let payloadStream; + const payLoadLength = totalMsgLength - headerLength - 16; + if (payLoadLength > 0) { + const payLoadBuffer = Buffer.from(responseStream.read(payLoadLength)); + msgCrcAccumulator = crc32(payLoadBuffer, msgCrcAccumulator); + // read the checksum early and detect any mismatch so we can avoid unnecessary further processing. + const messageCrcByteValue = Buffer.from(responseStream.read(4)).readInt32BE(); + const calculatedCrc = msgCrcAccumulator.readInt32BE(); + // Handle message CRC Error + if (messageCrcByteValue !== calculatedCrc) { + throw new Error(`Message Checksum Mismatch, Message CRC of ${messageCrcByteValue} does not equal expected CRC of ${calculatedCrc}`); + } + payloadStream = readableStream(payLoadBuffer); + } + const messageType = headers['message-type']; + switch (messageType) { + case 'error': + { + const errorMessage = headers['error-code'] + ':"' + headers['error-message'] + '"'; + throw new Error(errorMessage); + } + case 'event': + { + const contentType = headers['content-type']; + const eventType = headers['event-type']; + switch (eventType) { + case 'End': + { + selectResults.setResponse(res); + return selectResults; + } + case 'Records': + { + var _payloadStream; + const readData = (_payloadStream = payloadStream) === null || _payloadStream === void 0 ? void 0 : _payloadStream.read(payLoadLength); + selectResults.setRecords(readData); + break; + } + case 'Progress': + { + switch (contentType) { + case 'text/xml': + { + var _payloadStream2; + const progressData = (_payloadStream2 = payloadStream) === null || _payloadStream2 === void 0 ? void 0 : _payloadStream2.read(payLoadLength); + selectResults.setProgress(progressData.toString()); + break; + } + default: + { + const errorMessage = `Unexpected content-type ${contentType} sent for event-type Progress`; + throw new Error(errorMessage); + } + } + } + break; + case 'Stats': + { + switch (contentType) { + case 'text/xml': + { + var _payloadStream3; + const statsData = (_payloadStream3 = payloadStream) === null || _payloadStream3 === void 0 ? void 0 : _payloadStream3.read(payLoadLength); + selectResults.setStats(statsData.toString()); + break; + } + default: + { + const errorMessage = `Unexpected content-type ${contentType} sent for event-type Stats`; + throw new Error(errorMessage); + } + } + } + break; + default: + { + // Continuation message: Not sure if it is supported. did not find a reference or any message in response. + // It does not have a payload. + const warningMessage = `Un implemented event detected ${messageType}.`; + // eslint-disable-next-line no-console + console.warn(warningMessage); + } + } + } + } + } +} +export function parseLifecycleConfig(xml) { + const xmlObj = parseXml(xml); + return xmlObj.LifecycleConfiguration; +} +export function parseBucketEncryptionConfig(xml) { + return parseXml(xml); +} +export function parseObjectRetentionConfig(xml) { + const xmlObj = parseXml(xml); + const retentionConfig = xmlObj.Retention; + return { + mode: retentionConfig.Mode, + retainUntilDate: retentionConfig.RetainUntilDate + }; +} +export function removeObjectsParser(xml) { + const xmlObj = parseXml(xml); + if (xmlObj.DeleteResult && xmlObj.DeleteResult.Error) { + // return errors as array always. as the response is object in case of single object passed in removeObjects + return toArray(xmlObj.DeleteResult.Error); + } + return []; +} + +// parse XML response for copy object +export function parseCopyObject(xml) { + const result = { + etag: '', + lastModified: '' + }; + let xmlobj = parseXml(xml); + if (!xmlobj.CopyObjectResult) { + throw new errors.InvalidXMLError('Missing tag: "CopyObjectResult"'); + } + xmlobj = xmlobj.CopyObjectResult; + if (xmlobj.ETag) { + result.etag = xmlobj.ETag.replace(/^"/g, '').replace(/"$/g, '').replace(/^"/g, '').replace(/"$/g, '').replace(/^"/g, '').replace(/"$/g, ''); + } + if (xmlobj.LastModified) { + result.lastModified = new Date(xmlobj.LastModified); + } + return result; +} +const formatObjInfo = (content, opts = {}) => { + const { + Key, + LastModified, + ETag, + Size, + VersionId, + IsLatest + } = content; + if (!isObject(opts)) { + opts = {}; + } + const name = sanitizeObjectKey(toArray(Key)[0] || ''); + const lastModified = LastModified ? new Date(toArray(LastModified)[0] || '') : undefined; + const etag = sanitizeETag(toArray(ETag)[0] || ''); + const size = sanitizeSize(Size || ''); + return { + name, + lastModified, + etag, + size, + versionId: VersionId, + isLatest: IsLatest, + isDeleteMarker: opts.IsDeleteMarker ? opts.IsDeleteMarker : false + }; +}; + +// parse XML response for list objects in a bucket +export function parseListObjects(xml) { + const result = { + objects: [], + isTruncated: false, + nextMarker: undefined, + versionIdMarker: undefined, + keyMarker: undefined + }; + let isTruncated = false; + let nextMarker; + const xmlobj = fxpWithoutNumParser.parse(xml); + const parseCommonPrefixesEntity = commonPrefixEntry => { + if (commonPrefixEntry) { + toArray(commonPrefixEntry).forEach(commonPrefix => { + result.objects.push({ + prefix: sanitizeObjectKey(toArray(commonPrefix.Prefix)[0] || ''), + size: 0 + }); + }); + } + }; + const listBucketResult = xmlobj.ListBucketResult; + const listVersionsResult = xmlobj.ListVersionsResult; + if (listBucketResult) { + if (listBucketResult.IsTruncated) { + isTruncated = listBucketResult.IsTruncated; + } + if (listBucketResult.Contents) { + toArray(listBucketResult.Contents).forEach(content => { + const name = sanitizeObjectKey(toArray(content.Key)[0] || ''); + const lastModified = new Date(toArray(content.LastModified)[0] || ''); + const etag = sanitizeETag(toArray(content.ETag)[0] || ''); + const size = sanitizeSize(content.Size || ''); + result.objects.push({ + name, + lastModified, + etag, + size + }); + }); + } + if (listBucketResult.Marker) { + nextMarker = listBucketResult.Marker; + } + if (listBucketResult.NextMarker) { + nextMarker = listBucketResult.NextMarker; + } else if (isTruncated && result.objects.length > 0) { + var _result$objects; + nextMarker = (_result$objects = result.objects[result.objects.length - 1]) === null || _result$objects === void 0 ? void 0 : _result$objects.name; + } + if (listBucketResult.CommonPrefixes) { + parseCommonPrefixesEntity(listBucketResult.CommonPrefixes); + } + } + if (listVersionsResult) { + if (listVersionsResult.IsTruncated) { + isTruncated = listVersionsResult.IsTruncated; + } + if (listVersionsResult.Version) { + toArray(listVersionsResult.Version).forEach(content => { + result.objects.push(formatObjInfo(content)); + }); + } + if (listVersionsResult.DeleteMarker) { + toArray(listVersionsResult.DeleteMarker).forEach(content => { + result.objects.push(formatObjInfo(content, { + IsDeleteMarker: true + })); + }); + } + if (listVersionsResult.NextKeyMarker) { + result.keyMarker = listVersionsResult.NextKeyMarker; + } + if (listVersionsResult.NextVersionIdMarker) { + result.versionIdMarker = listVersionsResult.NextVersionIdMarker; + } + if (listVersionsResult.CommonPrefixes) { + parseCommonPrefixesEntity(listVersionsResult.CommonPrefixes); + } + } + result.isTruncated = isTruncated; + if (isTruncated) { + result.nextMarker = nextMarker; + } + return result; +} +export function uploadPartParser(xml) { + const xmlObj = parseXml(xml); + const respEl = xmlObj.CopyPartResult; + return respEl; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjcmMzMiIsIlhNTFBhcnNlciIsImVycm9ycyIsIlNlbGVjdFJlc3VsdHMiLCJpc09iamVjdCIsInBhcnNlWG1sIiwicmVhZGFibGVTdHJlYW0iLCJzYW5pdGl6ZUVUYWciLCJzYW5pdGl6ZU9iamVjdEtleSIsInNhbml0aXplU2l6ZSIsInRvQXJyYXkiLCJyZWFkQXNTdHJpbmciLCJSRVRFTlRJT05fVkFMSURJVFlfVU5JVFMiLCJwYXJzZUJ1Y2tldFJlZ2lvbiIsInhtbCIsIkxvY2F0aW9uQ29uc3RyYWludCIsImZ4cCIsImZ4cFdpdGhvdXROdW1QYXJzZXIiLCJudW1iZXJQYXJzZU9wdGlvbnMiLCJza2lwTGlrZSIsInBhcnNlRXJyb3IiLCJoZWFkZXJJbmZvIiwieG1sRXJyIiwieG1sT2JqIiwicGFyc2UiLCJFcnJvciIsImUiLCJTM0Vycm9yIiwiT2JqZWN0IiwiZW50cmllcyIsImZvckVhY2giLCJrZXkiLCJ2YWx1ZSIsInRvTG93ZXJDYXNlIiwicGFyc2VSZXNwb25zZUVycm9yIiwicmVzcG9uc2UiLCJzdGF0dXNDb2RlIiwiY29kZSIsIm1lc3NhZ2UiLCJoRXJyQ29kZSIsImhlYWRlcnMiLCJoRXJyRGVzYyIsImFtelJlcXVlc3RpZCIsImFteklkMiIsImFtekJ1Y2tldFJlZ2lvbiIsInhtbFN0cmluZyIsImNhdXNlIiwicGFyc2VMaXN0T2JqZWN0c1YyV2l0aE1ldGFkYXRhIiwicmVzdWx0Iiwib2JqZWN0cyIsImlzVHJ1bmNhdGVkIiwibmV4dENvbnRpbnVhdGlvblRva2VuIiwieG1sb2JqIiwiTGlzdEJ1Y2tldFJlc3VsdCIsIkludmFsaWRYTUxFcn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AgICAgcmV0dXJuIHNlbGVjdFJlc3VsdHNcbiAgICAgICAgICB9XG5cbiAgICAgICAgICBjYXNlICdSZWNvcmRzJzoge1xuICAgICAgICAgICAgY29uc3QgcmVhZERhdGEgPSBwYXlsb2FkU3RyZWFtPy5yZWFkKHBheUxvYWRMZW5ndGgpXG4gICAgICAgICAgICBzZWxlY3RSZXN1bHRzLnNldFJlY29yZHMocmVhZERhdGEpXG4gICAgICAgICAgICBicmVha1xuICAgICAgICAgIH1cblxuICAgICAgICAgIGNhc2UgJ1Byb2dyZXNzJzpcbiAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgc3dpdGNoIChjb250ZW50VHlwZSkge1xuICAgICAgICAgICAgICAgIGNhc2UgJ3RleHQveG1sJzoge1xuICAgICAgICAgICAgICAgICAgY29uc3QgcHJvZ3Jlc3NEYXRhID0gcGF5bG9hZFN0cmVhbT8ucmVhZChwYXlMb2FkTGVuZ3RoKVxuICAgICAgICAgICAgICAgICAgc2VsZWN0UmVzdWx0cy5zZXRQcm9ncmVzcyhwcm9ncmVzc0RhdGEudG9TdHJpbmcoKSlcbiAgICAgICAgICAgICAgICAgIGJyZWFrXG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIGRlZmF1bHQ6IHtcbiAgICAgICAgICAgICAgICAgIGNvbnN0IGVycm9yTWVzc2FnZSA9IGBVbmV4cGVjdGVkIGNvbnRlbnQtdHlwZSAke2NvbnRlbnRUeXBlfSBzZW50IGZvciBldmVudC10eXBlIFByb2dyZXNzYFxuICAgICAgICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKGVycm9yTWVzc2FnZSlcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGJyZWFrXG4gICAgICAgICAgY2FzZSAnU3RhdHMnOlxuICAgICAgICAgICAge1xuICAgICAgICAgICAgICBzd2l0Y2ggKGNvbnRlbnRUeXBlKSB7XG4gICAgICAgICAgICAgICAgY2FzZSAndGV4dC94bWwnOiB7XG4gICAgICAgICAgICAgICAgICBjb25zdCBzdGF0c0RhdGEgPSBwYXlsb2FkU3RyZWFtPy5yZWFkKHBheUxvYWRMZW5ndGgpXG4gICAgICAgICAgICAgICAgICBzZWxlY3RSZXN1bHRzLnNldFN0YXRzKHN0YXRzRGF0YS50b1N0cmluZygpKVxuICAgICAgICAgICAgICAgICAgYnJlYWtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgZGVmYXVsdDoge1xuICAgICAgICAgICAgICAgICAgY29uc3QgZXJyb3JNZXNzYWdlID0gYFVuZXhwZWN0ZWQgY29udGVudC10eXBlICR7Y29udGVudFR5cGV9IHNlbnQgZm9yIGV2ZW50LXR5cGUgU3RhdHNgXG4gICAgICAgICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoZXJyb3JNZXNzYWdlKVxuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfVxuICAgICAgICAgICAgYnJlYWtcbiAgICAgICAgICBkZWZhdWx0OiB7XG4gICAgICAgICAgICAvLyBDb250aW51YXRpb24gbWVzc2FnZTogTm90IHN1cmUgaWYgaXQgaXMgc3VwcG9ydGVkLiBkaWQgbm90IGZpbmQgYSByZWZlcmVuY2Ugb3IgYW55IG1lc3NhZ2UgaW4gcmVzcG9uc2UuXG4gICAgICAgICAgICAvLyBJdCBkb2VzIG5vdCBoYXZlIGEgcGF5bG9hZC5cbiAgICAgICAgICAgIGNvbnN0IHdhcm5pbmdNZXNzYWdlID0gYFVuIGltcGxlbWVudGVkIGV2ZW50IGRldGVjdGVkICAke21lc3NhZ2VUeXBlfS5gXG4gICAgICAgICAgICAvLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgbm8tY29uc29sZVxuICAgICAgICAgICAgY29uc29sZS53YXJuKHdhcm5pbmdNZXNzYWdlKVxuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgfVxuIC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DaEMsSUFBSUEsV0FBVyxFQUFFO0lBQ2ZGLE1BQU0sQ0FBQ3NPLFVBQVUsR0FBR0EsVUFBVTtFQUNoQztFQUNBLE9BQU90TyxNQUFNO0FBQ2Y7QUFFQSxPQUFPLFNBQVNvUCxnQkFBZ0JBLENBQUN0UixHQUFXLEVBQUU7RUFDNUMsTUFBTVMsTUFBTSxHQUFHbEIsUUFBUSxDQUFDUyxHQUFHLENBQUM7RUFDNUIsTUFBTXVSLE1BQU0sR0FBRzlRLE1BQU0sQ0FBQytRLGNBQWM7RUFDcEMsT0FBT0QsTUFBTTtBQUNmIn0= \ No newline at end of file diff --git a/node_modules/minio/dist/esm/minio.d.mts b/node_modules/minio/dist/esm/minio.d.mts new file mode 100644 index 0000000..f72ea90 --- /dev/null +++ b/node_modules/minio/dist/esm/minio.d.mts @@ -0,0 +1,40 @@ +import type { LEGAL_HOLD_STATUS, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from "./helpers.mjs"; +import { TypedClient } from "./internal/client.mjs"; +import { CopyConditions } from "./internal/copy-conditions.mjs"; +import { PostPolicy } from "./internal/post-policy.mjs"; +export * from "./errors.mjs"; +export * from "./helpers.mjs"; +export * from "./notification.mjs"; +export { CopyConditions, PostPolicy }; +export { IamAwsProvider } from "./IamAwsProvider.mjs"; +export type { MakeBucketOpt } from "./internal/client.mjs"; +export type { ClientOptions, NoResultCallback, RemoveOptions } from "./internal/client.mjs"; +export type { Region } from "./internal/s3-endpoints.mjs"; +export type { BucketItem, BucketItemCopy, BucketItemFromList, BucketItemStat, BucketItemWithMetadata, BucketStream, EmptyObject, ExistingObjectReplication, GetObjectLegalHoldOptions, IncompleteUploadedBucketItem, InputSerialization, IsoDate, ItemBucketMetadata, ItemBucketMetadataList, LegalHoldStatus, LifecycleConfig, LifecycleRule, MetadataItem, ObjectLockInfo, OutputSerialization, PostPolicyResult, PutObjectLegalHoldOptions, ReplicaModifications, ReplicationConfig, ReplicationConfigOpts, ReplicationRule, ReplicationRuleAnd, ReplicationRuleDestination, ReplicationRuleFilter, ReplicationRuleStatus, Retention, RetentionOptions, ScanRange, SelectOptions, SelectProgress, SourceSelectionCriteria, Tag } from "./internal/type.mjs"; +/** + * @deprecated keep for backward compatible, use `RETENTION_MODES` instead + */ +export type Mode = RETENTION_MODES; +/** + * @deprecated keep for backward compatible + */ +export type LockUnit = RETENTION_VALIDITY_UNITS; +export type VersioningConfig = Record; +export type TagList = Record; +export interface LockConfig { + mode: RETENTION_MODES; + unit: RETENTION_VALIDITY_UNITS; + validity: number; +} +export interface LegalHoldOptions { + versionId: string; + status: LEGAL_HOLD_STATUS; +} +export interface SourceObjectStats { + size: number; + metaData: string; + lastModicied: Date; + versionId: string; + etag: string; +} +export declare class Client extends TypedClient {} \ No newline at end of file diff --git a/node_modules/minio/dist/esm/minio.mjs b/node_modules/minio/dist/esm/minio.mjs new file mode 100644 index 0000000..883f8f0 --- /dev/null +++ b/node_modules/minio/dist/esm/minio.mjs @@ -0,0 +1,86 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { callbackify } from "./internal/callbackify.mjs"; +import { TypedClient } from "./internal/client.mjs"; +import { CopyConditions } from "./internal/copy-conditions.mjs"; +import { PostPolicy } from "./internal/post-policy.mjs"; +export * from "./errors.mjs"; +export * from "./helpers.mjs"; +export * from "./notification.mjs"; +export { CopyConditions, PostPolicy }; +export { IamAwsProvider } from "./IamAwsProvider.mjs"; + +/** + * @deprecated keep for backward compatible, use `RETENTION_MODES` instead + */ + +/** + * @deprecated keep for backward compatible + */ + +export class Client extends TypedClient {} + +// refactored API use promise internally +Client.prototype.makeBucket = callbackify(Client.prototype.makeBucket); +Client.prototype.bucketExists = callbackify(Client.prototype.bucketExists); +Client.prototype.removeBucket = callbackify(Client.prototype.removeBucket); +Client.prototype.listBuckets = callbackify(Client.prototype.listBuckets); +Client.prototype.getObject = callbackify(Client.prototype.getObject); +Client.prototype.fGetObject = callbackify(Client.prototype.fGetObject); +Client.prototype.getPartialObject = callbackify(Client.prototype.getPartialObject); +Client.prototype.statObject = callbackify(Client.prototype.statObject); +Client.prototype.putObjectRetention = callbackify(Client.prototype.putObjectRetention); +Client.prototype.putObject = callbackify(Client.prototype.putObject); +Client.prototype.fPutObject = callbackify(Client.prototype.fPutObject); +Client.prototype.removeObject = callbackify(Client.prototype.removeObject); +Client.prototype.removeBucketReplication = callbackify(Client.prototype.removeBucketReplication); +Client.prototype.setBucketReplication = callbackify(Client.prototype.setBucketReplication); +Client.prototype.getBucketReplication = callbackify(Client.prototype.getBucketReplication); +Client.prototype.getObjectLegalHold = callbackify(Client.prototype.getObjectLegalHold); +Client.prototype.setObjectLegalHold = callbackify(Client.prototype.setObjectLegalHold); +Client.prototype.setObjectLockConfig = callbackify(Client.prototype.setObjectLockConfig); +Client.prototype.getObjectLockConfig = callbackify(Client.prototype.getObjectLockConfig); +Client.prototype.getBucketPolicy = callbackify(Client.prototype.getBucketPolicy); +Client.prototype.setBucketPolicy = callbackify(Client.prototype.setBucketPolicy); +Client.prototype.getBucketTagging = callbackify(Client.prototype.getBucketTagging); +Client.prototype.getObjectTagging = callbackify(Client.prototype.getObjectTagging); +Client.prototype.setBucketTagging = callbackify(Client.prototype.setBucketTagging); +Client.prototype.removeBucketTagging = callbackify(Client.prototype.removeBucketTagging); +Client.prototype.setObjectTagging = callbackify(Client.prototype.setObjectTagging); +Client.prototype.removeObjectTagging = callbackify(Client.prototype.removeObjectTagging); +Client.prototype.getBucketVersioning = callbackify(Client.prototype.getBucketVersioning); +Client.prototype.setBucketVersioning = callbackify(Client.prototype.setBucketVersioning); +Client.prototype.selectObjectContent = callbackify(Client.prototype.selectObjectContent); +Client.prototype.setBucketLifecycle = callbackify(Client.prototype.setBucketLifecycle); +Client.prototype.getBucketLifecycle = callbackify(Client.prototype.getBucketLifecycle); +Client.prototype.removeBucketLifecycle = callbackify(Client.prototype.removeBucketLifecycle); +Client.prototype.setBucketEncryption = callbackify(Client.prototype.setBucketEncryption); +Client.prototype.getBucketEncryption = callbackify(Client.prototype.getBucketEncryption); +Client.prototype.removeBucketEncryption = callbackify(Client.prototype.removeBucketEncryption); +Client.prototype.getObjectRetention = callbackify(Client.prototype.getObjectRetention); +Client.prototype.removeObjects = callbackify(Client.prototype.removeObjects); +Client.prototype.removeIncompleteUpload = callbackify(Client.prototype.removeIncompleteUpload); +Client.prototype.copyObject = callbackify(Client.prototype.copyObject); +Client.prototype.composeObject = callbackify(Client.prototype.composeObject); +Client.prototype.presignedUrl = callbackify(Client.prototype.presignedUrl); +Client.prototype.presignedGetObject = callbackify(Client.prototype.presignedGetObject); +Client.prototype.presignedPutObject = callbackify(Client.prototype.presignedPutObject); +Client.prototype.presignedPostPolicy = callbackify(Client.prototype.presignedPostPolicy); +Client.prototype.setBucketNotification = callbackify(Client.prototype.setBucketNotification); +Client.prototype.getBucketNotification = callbackify(Client.prototype.getBucketNotification); +Client.prototype.removeAllBucketNotification = callbackify(Client.prototype.removeAllBucketNotification); +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjYWxsYmFja2lmeSIsIlR5cGVkQ2xpZW50IiwiQ29weUNvbmRpdGlvbnMiLCJQb3N0UG9saWN5IiwiSWFtQXdzUHJvdmlkZXIiLCJDbGllbnQiLCJwcm90b3R5cGUiLCJtYWtlQnVja2V0IiwiYnVja2V0RXhpc3RzIiwicmVtb3ZlQnVja2V0IiwibGlzdEJ1Y2tldHMiLCJnZXRPYmplY3QiLCJmR2V0T2JqZWN0IiwiZ2V0UGFydGlhbE9iamVjdC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BQ0ssTUFBTSxDQUFDQyxTQUFTLENBQUN5QyxhQUFhLENBQUM7QUFDNUUxQyxNQUFNLENBQUNDLFNBQVMsQ0FBQzBDLFlBQVksR0FBR2hELFdBQVcsQ0FBQ0ssTUFBTSxDQUFDQyxTQUFTLENBQUMwQyxZQUFZLENBQUM7QUFDMUUzQyxNQUFNLENBQUNDLFNBQVMsQ0FBQzJDLGtCQUFrQixHQUFHakQsV0FBVyxDQUFDSyxNQUFNLENBQUNDLFNBQVMsQ0FBQzJDLGtCQUFrQixDQUFDO0FBQ3RGNUMsTUFBTSxDQUFDQyxTQUFTLENBQUM0QyxrQkFBa0IsR0FBR2xELFdBQVcsQ0FBQ0ssTUFBTSxDQUFDQyxTQUFTLENBQUM0QyxrQkFBa0IsQ0FBQztBQUN0RjdDLE1BQU0sQ0FBQ0MsU0FBUyxDQUFDNkMsbUJBQW1CLEdBQUduRCxXQUFXLENBQUNLLE1BQU0sQ0FBQ0MsU0FBUyxDQUFDNkMsbUJBQW1CLENBQUM7QUFDeEY5QyxNQUFNLENBQUNDLFNBQVMsQ0FBQzhDLHFCQUFxQixHQUFHcEQsV0FBVyxDQUFDSyxNQUFNLENBQUNDLFNBQVMsQ0FBQzhDLHFCQUFxQixDQUFDO0FBQzVGL0MsTUFBTSxDQUFDQyxTQUFTLENBQUMrQyxxQkFBcUIsR0FBR3JELFdBQVcsQ0FBQ0ssTUFBTSxDQUFDQyxTQUFTLENBQUMrQyxxQkFBcUIsQ0FBQztBQUM1RmhELE1BQU0sQ0FBQ0MsU0FBUyxDQUFDZ0QsMkJBQTJCLEdBQUd0RCxXQUFXLENBQUNLLE1BQU0sQ0FBQ0MsU0FBUyxDQUFDZ0QsMkJBQTJCLENBQUMifQ== \ No newline at end of file diff --git a/node_modules/minio/dist/esm/notification.d.mts b/node_modules/minio/dist/esm/notification.d.mts new file mode 100644 index 0000000..b172cf9 --- /dev/null +++ b/node_modules/minio/dist/esm/notification.d.mts @@ -0,0 +1,58 @@ +import { EventEmitter } from 'eventemitter3'; +import type { TypedClient } from "./internal/client.mjs"; +type Event = unknown; +export declare class TargetConfig { + private Filter?; + private Event?; + private Id; + setId(id: unknown): void; + addEvent(newevent: Event): void; + addFilterSuffix(suffix: string): void; + addFilterPrefix(prefix: string): void; +} +export declare class TopicConfig extends TargetConfig { + private Topic; + constructor(arn: string); +} +export declare class QueueConfig extends TargetConfig { + private Queue; + constructor(arn: string); +} +export declare class CloudFunctionConfig extends TargetConfig { + private CloudFunction; + constructor(arn: string); +} +export declare class NotificationConfig { + private TopicConfiguration?; + private CloudFunctionConfiguration?; + private QueueConfiguration?; + add(target: TargetConfig): void; +} +export declare const buildARN: (partition: string, service: string, region: string, accountId: string, resource: string) => string; +export declare const ObjectCreatedAll = "s3:ObjectCreated:*"; +export declare const ObjectCreatedPut = "s3:ObjectCreated:Put"; +export declare const ObjectCreatedPost = "s3:ObjectCreated:Post"; +export declare const ObjectCreatedCopy = "s3:ObjectCreated:Copy"; +export declare const ObjectCreatedCompleteMultipartUpload = "s3:ObjectCreated:CompleteMultipartUpload"; +export declare const ObjectRemovedAll = "s3:ObjectRemoved:*"; +export declare const ObjectRemovedDelete = "s3:ObjectRemoved:Delete"; +export declare const ObjectRemovedDeleteMarkerCreated = "s3:ObjectRemoved:DeleteMarkerCreated"; +export declare const ObjectReducedRedundancyLostObject = "s3:ReducedRedundancyLostObject"; +export type NotificationEvent = 's3:ObjectCreated:*' | 's3:ObjectCreated:Put' | 's3:ObjectCreated:Post' | 's3:ObjectCreated:Copy' | 's3:ObjectCreated:CompleteMultipartUpload' | 's3:ObjectRemoved:*' | 's3:ObjectRemoved:Delete' | 's3:ObjectRemoved:DeleteMarkerCreated' | 's3:ReducedRedundancyLostObject' | 's3:TestEvent' | 's3:ObjectRestore:Post' | 's3:ObjectRestore:Completed' | 's3:Replication:OperationFailedReplication' | 's3:Replication:OperationMissedThreshold' | 's3:Replication:OperationReplicatedAfterThreshold' | 's3:Replication:OperationNotTracked' | string; +export type NotificationRecord = unknown; +export declare class NotificationPoller extends EventEmitter<{ + notification: (event: NotificationRecord) => void; + error: (error: unknown) => void; +}> { + private client; + private bucketName; + private prefix; + private suffix; + private events; + private ending; + constructor(client: TypedClient, bucketName: string, prefix: string, suffix: string, events: NotificationEvent[]); + start(): void; + stop(): void; + checkForChanges(): void; +} +export {}; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/notification.mjs b/node_modules/minio/dist/esm/notification.mjs new file mode 100644 index 0000000..2fe075b --- /dev/null +++ b/node_modules/minio/dist/esm/notification.mjs @@ -0,0 +1,209 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2016 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { EventEmitter } from 'eventemitter3'; +import jsonLineParser from 'stream-json/jsonl/Parser.js'; +import { DEFAULT_REGION } from "./helpers.mjs"; +import { pipesetup, uriEscape } from "./internal/helper.mjs"; + +// TODO: type this + +// Base class for three supported configs. +export class TargetConfig { + setId(id) { + this.Id = id; + } + addEvent(newevent) { + if (!this.Event) { + this.Event = []; + } + this.Event.push(newevent); + } + addFilterSuffix(suffix) { + if (!this.Filter) { + this.Filter = { + S3Key: { + FilterRule: [] + } + }; + } + this.Filter.S3Key.FilterRule.push({ + Name: 'suffix', + Value: suffix + }); + } + addFilterPrefix(prefix) { + if (!this.Filter) { + this.Filter = { + S3Key: { + FilterRule: [] + } + }; + } + this.Filter.S3Key.FilterRule.push({ + Name: 'prefix', + Value: prefix + }); + } +} + +// 1. Topic (simple notification service) +export class TopicConfig extends TargetConfig { + constructor(arn) { + super(); + this.Topic = arn; + } +} + +// 2. Queue (simple queue service) +export class QueueConfig extends TargetConfig { + constructor(arn) { + super(); + this.Queue = arn; + } +} + +// 3. CloudFront (lambda function) +export class CloudFunctionConfig extends TargetConfig { + constructor(arn) { + super(); + this.CloudFunction = arn; + } +} + +// Notification config - array of target configs. +// Target configs can be +// 1. Topic (simple notification service) +// 2. Queue (simple queue service) +// 3. CloudFront (lambda function) +export class NotificationConfig { + add(target) { + let instance; + if (target instanceof TopicConfig) { + instance = this.TopicConfiguration ?? (this.TopicConfiguration = []); + } + if (target instanceof QueueConfig) { + instance = this.QueueConfiguration ?? (this.QueueConfiguration = []); + } + if (target instanceof CloudFunctionConfig) { + instance = this.CloudFunctionConfiguration ?? (this.CloudFunctionConfiguration = []); + } + if (instance) { + instance.push(target); + } + } +} +export const buildARN = (partition, service, region, accountId, resource) => { + return 'arn:' + partition + ':' + service + ':' + region + ':' + accountId + ':' + resource; +}; +export const ObjectCreatedAll = 's3:ObjectCreated:*'; +export const ObjectCreatedPut = 's3:ObjectCreated:Put'; +export const ObjectCreatedPost = 's3:ObjectCreated:Post'; +export const ObjectCreatedCopy = 's3:ObjectCreated:Copy'; +export const ObjectCreatedCompleteMultipartUpload = 's3:ObjectCreated:CompleteMultipartUpload'; +export const ObjectRemovedAll = 's3:ObjectRemoved:*'; +export const ObjectRemovedDelete = 's3:ObjectRemoved:Delete'; +export const ObjectRemovedDeleteMarkerCreated = 's3:ObjectRemoved:DeleteMarkerCreated'; +export const ObjectReducedRedundancyLostObject = 's3:ReducedRedundancyLostObject'; + +// put string at least so auto-complete could work +// TODO: type this +// Poll for notifications, used in #listenBucketNotification. +// Listening constitutes repeatedly requesting s3 whether or not any +// changes have occurred. +export class NotificationPoller extends EventEmitter { + constructor(client, bucketName, prefix, suffix, events) { + super(); + this.client = client; + this.bucketName = bucketName; + this.prefix = prefix; + this.suffix = suffix; + this.events = events; + this.ending = false; + } + + // Starts the polling. + start() { + this.ending = false; + process.nextTick(() => { + this.checkForChanges(); + }); + } + + // Stops the polling. + stop() { + this.ending = true; + } + checkForChanges() { + // Don't continue if we're looping again but are cancelled. + if (this.ending) { + return; + } + const method = 'GET'; + const queries = []; + if (this.prefix) { + const prefix = uriEscape(this.prefix); + queries.push(`prefix=${prefix}`); + } + if (this.suffix) { + const suffix = uriEscape(this.suffix); + queries.push(`suffix=${suffix}`); + } + if (this.events) { + this.events.forEach(s3event => queries.push('events=' + uriEscape(s3event))); + } + queries.sort(); + let query = ''; + if (queries.length > 0) { + query = `${queries.join('&')}`; + } + const region = this.client.region || DEFAULT_REGION; + this.client.makeRequestAsync({ + method, + bucketName: this.bucketName, + query + }, '', [200], region).then(response => { + const asm = jsonLineParser.make(); + pipesetup(response, asm).on('data', data => { + // Data is flushed periodically (every 5 seconds), so we should + // handle it after flushing from the JSON parser. + let records = data.value.Records; + // If null (= no records), change to an empty array. + if (!records) { + records = []; + } + + // Iterate over the notifications and emit them individually. + records.forEach(record => { + this.emit('notification', record); + }); + + // If we're done, stop. + if (this.ending) { + response === null || response === void 0 ? void 0 : response.destroy(); + } + }).on('error', e => this.emit('error', e)).on('end', () => { + // Do it again, if we haven't cancelled yet. + process.nextTick(() => { + this.checkForChanges(); + }); + }); + }, e => { + return this.emit('error', e); + }); + } +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJFdmVudEVtaXR0ZXIiLCJqc29uTGluZVBhcnNlciIsIkRFRkFVTFRfUkVHSU9OIiwicGlwZXNldHVwIiwidXJpRXNjYXBlIiwiVGFyZ2V0Q29uZmlnIiwic2V0SWQiLCJpZCIsIklkIiwiYWRkRXZlbnQiLCJuZXdldmVudCIsIkV2ZW50IiwicHVzaCIsImFkZEZpbHRlclN1ZmZpeCIsInN1ZmZpeCIsIkZpbHRlciIsIlMzS2V5IiwiRmlsdGVyUnVsZSIsIk5hbWUiLCJWYWx1ZSIsImFkZEZpbHRlclByZWZpeCIsInByZWZpeCIsIlRvcGljQ29uZmlnIiwiY29uc3RydWN0b3IiLC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LEVBQUU7UUFDZDs7UUFFQTtRQUNBQSxPQUFPLENBQUNiLE9BQU8sQ0FBRWdCLE1BQTBCLElBQUs7VUFDOUMsSUFBSSxDQUFDQyxJQUFJLENBQUMsY0FBYyxFQUFFRCxNQUFNLENBQUM7UUFDbkMsQ0FBQyxDQUFDOztRQUVGO1FBQ0EsSUFBSSxJQUFJLENBQUN4QixNQUFNLEVBQUU7VUFDZmdCLFFBQVEsYUFBUkEsUUFBUSx1QkFBUkEsUUFBUSxDQUFFVSxPQUFPLENBQUMsQ0FBQztRQUNyQjtNQUNGLENBQUMsQ0FBQyxDQUNEUCxFQUFFLENBQUMsT0FBTyxFQUFHUSxDQUFDLElBQUssSUFBSSxDQUFDRixJQUFJLENBQUMsT0FBTyxFQUFFRSxDQUFDLENBQUMsQ0FBQyxDQUN6Q1IsRUFBRSxDQUFDLEtBQUssRUFBRSxNQUFNO1FBQ2Y7UUFDQWpCLE9BQU8sQ0FBQ0MsUUFBUSxDQUFDLE1BQU07VUFDckIsSUFBSSxDQUFDQyxlQUFlLENBQUMsQ0FBQztRQUN4QixDQUFDLENBQUM7TUFDSixDQUFDLENBQUM7SUFDTixDQUFDLEVBQ0F1QixDQUFDLElBQUs7TUFDTCxPQUFPLElBQUksQ0FBQ0YsSUFBSSxDQUFDLE9BQU8sRUFBRUUsQ0FBQyxDQUFDO0lBQzlCLENBQ0YsQ0FBQztFQUNIO0FBQ0YifQ== \ No newline at end of file diff --git a/node_modules/minio/dist/esm/signing.d.mts b/node_modules/minio/dist/esm/signing.d.mts new file mode 100644 index 0000000..cad45a8 --- /dev/null +++ b/node_modules/minio/dist/esm/signing.d.mts @@ -0,0 +1,5 @@ +import type { IRequest } from "./internal/type.mjs"; +export declare function postPresignSignatureV4(region: string, date: Date, secretKey: string, policyBase64: string): string; +export declare function signV4(request: IRequest, accessKey: string, secretKey: string, region: string, requestDate: Date, sha256sum: string, serviceName?: string): string; +export declare function signV4ByServiceName(request: IRequest, accessKey: string, secretKey: string, region: string, requestDate: Date, contentSha256: string, serviceName?: string): string; +export declare function presignSignatureV4(request: IRequest, accessKey: string, secretKey: string, sessionToken: string | undefined, region: string, requestDate: Date, expires: number | undefined): string; \ No newline at end of file diff --git a/node_modules/minio/dist/esm/signing.mjs b/node_modules/minio/dist/esm/signing.mjs new file mode 100644 index 0000000..4f2e59f --- /dev/null +++ b/node_modules/minio/dist/esm/signing.mjs @@ -0,0 +1,258 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2016 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as crypto from "crypto"; +import * as errors from "./errors.mjs"; +import { PRESIGN_EXPIRY_DAYS_MAX } from "./helpers.mjs"; +import { getScope, isNumber, isObject, isString, makeDateLong, makeDateShort, uriEscape } from "./internal/helper.mjs"; +const signV4Algorithm = 'AWS4-HMAC-SHA256'; + +// getCanonicalRequest generate a canonical request of style. +// +// canonicalRequest = +// \n +// \n +// \n +// \n +// \n +// +// +function getCanonicalRequest(method, path, headers, signedHeaders, hashedPayload) { + if (!isString(method)) { + throw new TypeError('method should be of type "string"'); + } + if (!isString(path)) { + throw new TypeError('path should be of type "string"'); + } + if (!isObject(headers)) { + throw new TypeError('headers should be of type "object"'); + } + if (!Array.isArray(signedHeaders)) { + throw new TypeError('signedHeaders should be of type "array"'); + } + if (!isString(hashedPayload)) { + throw new TypeError('hashedPayload should be of type "string"'); + } + const headersArray = signedHeaders.reduce((acc, i) => { + // Trim spaces from the value (required by V4 spec) + const val = `${headers[i]}`.replace(/ +/g, ' '); + acc.push(`${i.toLowerCase()}:${val}`); + return acc; + }, []); + const requestResource = path.split('?')[0]; + let requestQuery = path.split('?')[1]; + if (!requestQuery) { + requestQuery = ''; + } + if (requestQuery) { + requestQuery = requestQuery.split('&').sort().map(element => !element.includes('=') ? element + '=' : element).join('&'); + } + return [method.toUpperCase(), requestResource, requestQuery, headersArray.join('\n') + '\n', signedHeaders.join(';').toLowerCase(), hashedPayload].join('\n'); +} + +// generate a credential string +function getCredential(accessKey, region, requestDate, serviceName = 's3') { + if (!isString(accessKey)) { + throw new TypeError('accessKey should be of type "string"'); + } + if (!isString(region)) { + throw new TypeError('region should be of type "string"'); + } + if (!isObject(requestDate)) { + throw new TypeError('requestDate should be of type "object"'); + } + return `${accessKey}/${getScope(region, requestDate, serviceName)}`; +} + +// Returns signed headers array - alphabetically sorted +function getSignedHeaders(headers) { + if (!isObject(headers)) { + throw new TypeError('request should be of type "object"'); + } + // Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258 + // + // User-Agent: + // + // This is ignored from signing because signing this causes problems with generating pre-signed URLs + // (that are executed by other agents) or when customers pass requests through proxies, which may + // modify the user-agent. + // + // Content-Length: + // + // This is ignored from signing because generating a pre-signed URL should not provide a content-length + // constraint, specifically when vending a S3 pre-signed PUT URL. The corollary to this is that when + // sending regular requests (non-pre-signed), the signature contains a checksum of the body, which + // implicitly validates the payload length (since changing the number of bytes would change the checksum) + // and therefore this header is not valuable in the signature. + // + // Content-Type: + // + // Signing this header causes quite a number of problems in browser environments, where browsers + // like to modify and normalize the content-type header in different ways. There is more information + // on this in https://github.com/aws/aws-sdk-js/issues/244. Avoiding this field simplifies logic + // and reduces the possibility of future bugs + // + // Authorization: + // + // Is skipped for obvious reasons + + const ignoredHeaders = ['authorization', 'content-length', 'content-type', 'user-agent']; + return Object.keys(headers).filter(header => !ignoredHeaders.includes(header)).sort(); +} + +// returns the key used for calculating signature +function getSigningKey(date, region, secretKey, serviceName = 's3') { + if (!isObject(date)) { + throw new TypeError('date should be of type "object"'); + } + if (!isString(region)) { + throw new TypeError('region should be of type "string"'); + } + if (!isString(secretKey)) { + throw new TypeError('secretKey should be of type "string"'); + } + const dateLine = makeDateShort(date); + const hmac1 = crypto.createHmac('sha256', 'AWS4' + secretKey).update(dateLine).digest(), + hmac2 = crypto.createHmac('sha256', hmac1).update(region).digest(), + hmac3 = crypto.createHmac('sha256', hmac2).update(serviceName).digest(); + return crypto.createHmac('sha256', hmac3).update('aws4_request').digest(); +} + +// returns the string that needs to be signed +function getStringToSign(canonicalRequest, requestDate, region, serviceName = 's3') { + if (!isString(canonicalRequest)) { + throw new TypeError('canonicalRequest should be of type "string"'); + } + if (!isObject(requestDate)) { + throw new TypeError('requestDate should be of type "object"'); + } + if (!isString(region)) { + throw new TypeError('region should be of type "string"'); + } + const hash = crypto.createHash('sha256').update(canonicalRequest).digest('hex'); + const scope = getScope(region, requestDate, serviceName); + const stringToSign = [signV4Algorithm, makeDateLong(requestDate), scope, hash]; + return stringToSign.join('\n'); +} + +// calculate the signature of the POST policy +export function postPresignSignatureV4(region, date, secretKey, policyBase64) { + if (!isString(region)) { + throw new TypeError('region should be of type "string"'); + } + if (!isObject(date)) { + throw new TypeError('date should be of type "object"'); + } + if (!isString(secretKey)) { + throw new TypeError('secretKey should be of type "string"'); + } + if (!isString(policyBase64)) { + throw new TypeError('policyBase64 should be of type "string"'); + } + const signingKey = getSigningKey(date, region, secretKey); + return crypto.createHmac('sha256', signingKey).update(policyBase64).digest('hex').toLowerCase(); +} + +// Returns the authorization header +export function signV4(request, accessKey, secretKey, region, requestDate, sha256sum, serviceName = 's3') { + if (!isObject(request)) { + throw new TypeError('request should be of type "object"'); + } + if (!isString(accessKey)) { + throw new TypeError('accessKey should be of type "string"'); + } + if (!isString(secretKey)) { + throw new TypeError('secretKey should be of type "string"'); + } + if (!isString(region)) { + throw new TypeError('region should be of type "string"'); + } + if (!accessKey) { + throw new errors.AccessKeyRequiredError('accessKey is required for signing'); + } + if (!secretKey) { + throw new errors.SecretKeyRequiredError('secretKey is required for signing'); + } + const signedHeaders = getSignedHeaders(request.headers); + const canonicalRequest = getCanonicalRequest(request.method, request.path, request.headers, signedHeaders, sha256sum); + const serviceIdentifier = serviceName || 's3'; + const stringToSign = getStringToSign(canonicalRequest, requestDate, region, serviceIdentifier); + const signingKey = getSigningKey(requestDate, region, secretKey, serviceIdentifier); + const credential = getCredential(accessKey, region, requestDate, serviceIdentifier); + const signature = crypto.createHmac('sha256', signingKey).update(stringToSign).digest('hex').toLowerCase(); + return `${signV4Algorithm} Credential=${credential}, SignedHeaders=${signedHeaders.join(';').toLowerCase()}, Signature=${signature}`; +} +export function signV4ByServiceName(request, accessKey, secretKey, region, requestDate, contentSha256, serviceName = 's3') { + return signV4(request, accessKey, secretKey, region, requestDate, contentSha256, serviceName); +} + +// returns a presigned URL string +export function presignSignatureV4(request, accessKey, secretKey, sessionToken, region, requestDate, expires) { + if (!isObject(request)) { + throw new TypeError('request should be of type "object"'); + } + if (!isString(accessKey)) { + throw new TypeError('accessKey should be of type "string"'); + } + if (!isString(secretKey)) { + throw new TypeError('secretKey should be of type "string"'); + } + if (!isString(region)) { + throw new TypeError('region should be of type "string"'); + } + if (!accessKey) { + throw new errors.AccessKeyRequiredError('accessKey is required for presigning'); + } + if (!secretKey) { + throw new errors.SecretKeyRequiredError('secretKey is required for presigning'); + } + if (expires && !isNumber(expires)) { + throw new TypeError('expires should be of type "number"'); + } + if (expires && expires < 1) { + throw new errors.ExpiresParamError('expires param cannot be less than 1 seconds'); + } + if (expires && expires > PRESIGN_EXPIRY_DAYS_MAX) { + throw new errors.ExpiresParamError('expires param cannot be greater than 7 days'); + } + const iso8601Date = makeDateLong(requestDate); + const signedHeaders = getSignedHeaders(request.headers); + const credential = getCredential(accessKey, region, requestDate); + const hashedPayload = 'UNSIGNED-PAYLOAD'; + const requestQuery = []; + requestQuery.push(`X-Amz-Algorithm=${signV4Algorithm}`); + requestQuery.push(`X-Amz-Credential=${uriEscape(credential)}`); + requestQuery.push(`X-Amz-Date=${iso8601Date}`); + requestQuery.push(`X-Amz-Expires=${expires}`); + requestQuery.push(`X-Amz-SignedHeaders=${uriEscape(signedHeaders.join(';').toLowerCase())}`); + if (sessionToken) { + requestQuery.push(`X-Amz-Security-Token=${uriEscape(sessionToken)}`); + } + const resource = request.path.split('?')[0]; + let query = request.path.split('?')[1]; + if (query) { + query = query + '&' + requestQuery.join('&'); + } else { + query = requestQuery.join('&'); + } + const path = resource + '?' + query; + const canonicalRequest = getCanonicalRequest(request.method, path, request.headers, signedHeaders, hashedPayload); + const stringToSign = getStringToSign(canonicalRequest, requestDate, region); + const signingKey = getSigningKey(requestDate, region, secretKey); + const signature = crypto.createHmac('sha256', signingKey).update(stringToSign).digest('hex').toLowerCase(); + return request.protocol + '//' + request.headers.host + path + `&X-Amz-Signature=${signature}`; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjcnlwdG8iLCJlcnJvcnMiLCJQUkVTSUdOX0VYUElSWV9EQVlTX01BWCIsImdldFNjb3BlIiwiaXNOdW1iZXIiLCJpc09iamVjdCIsImlzU3RyaW5nIiwibWFrZURhdGVMb25nIiwibWFrZURhdGVTaG9ydCIsInVyaUVzY2FwZSIsInNpZ25WNEFsZ29yaXRobSIsImdldENhbm9uaWNhbFJlcXVlc3QiLCJtZXRob2QiLCJwYXRoIiwiaGVhZGVycyIsInNpZ25lZEhlYWRlcnMiLCJoYXNoZWRQYXlsb2FkIiwiVHlwZUVycm9yIiwiQXJyYXkiLCJpc0FycmF5IiwiaGVhZGVyc0FycmF5IiwicmVkdWNlIiwiYWNjIiwiaSIsInZhbCIsInJlcGxhY2UiLCJwdXNoIiwidG9Mb3dlckNhc2UiLCJyZXF1ZXN0UmVzb3VyY2UiLCJzcGxpdCIsInJlcXVlc3RRdWVyeSIsInNvcnQiLCJtYXAiLCJlbGVtZW50IiwiaW5jbHVkZXMiLCJqb2luIiwidG9VcHBlckNhc2UiLCJnZXRDcmVkZW50aWFsIiwiYWNjZXNzS2V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Q0FBQztFQUVqSCxNQUFNK0MsWUFBWSxHQUFHTCxlQUFlLENBQUNDLGdCQUFnQixFQUFFbkIsV0FBVyxFQUFFRCxNQUFNLENBQUM7RUFDM0UsTUFBTTJCLFVBQVUsR0FBR2xCLGFBQWEsQ0FBQ1IsV0FBVyxFQUFFRCxNQUFNLEVBQUVXLFNBQVMsQ0FBQztFQUNoRSxNQUFNd0IsU0FBUyxHQUFHMUUsTUFBTSxDQUFDcUQsVUFBVSxDQUFDLFFBQVEsRUFBRWEsVUFBVSxDQUFDLENBQUNaLE1BQU0sQ0FBQ1MsWUFBWSxDQUFDLENBQUNSLE1BQU0sQ0FBQyxLQUFLLENBQUMsQ0FBQzVCLFdBQVcsQ0FBQyxDQUFDO0VBQzFHLE9BQU95QyxPQUFPLENBQUNnQixRQUFRLEdBQUcsSUFBSSxHQUFHaEIsT0FBTyxDQUFDdEQsT0FBTyxDQUFDdUUsSUFBSSxHQUFHeEUsSUFBSSxHQUFJLG9CQUFtQjZELFNBQVUsRUFBQztBQUNoRyJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/AssumeRoleProvider.d.ts b/node_modules/minio/dist/main/AssumeRoleProvider.d.ts new file mode 100644 index 0000000..4c6270a --- /dev/null +++ b/node_modules/minio/dist/main/AssumeRoleProvider.d.ts @@ -0,0 +1,86 @@ +/// +import * as http from 'node:http'; +import { CredentialProvider } from "./CredentialProvider.js"; +import { Credentials } from "./Credentials.js"; +/** + * @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html + */ +type CredentialResponse = { + ErrorResponse?: { + Error?: { + Code?: string; + Message?: string; + }; + }; + AssumeRoleResponse: { + AssumeRoleResult: { + Credentials: { + AccessKeyId: string; + SecretAccessKey: string; + SessionToken: string; + Expiration: string; + }; + }; + }; +}; +export interface AssumeRoleProviderOptions { + stsEndpoint: string; + accessKey: string; + secretKey: string; + durationSeconds?: number; + sessionToken?: string; + policy?: string; + region?: string; + roleArn?: string; + roleSessionName?: string; + externalId?: string; + token?: string; + webIdentityToken?: string; + action?: string; + transportAgent?: http.Agent; +} +export declare class AssumeRoleProvider extends CredentialProvider { + private readonly stsEndpoint; + private readonly accessKey; + private readonly secretKey; + private readonly durationSeconds; + private readonly policy?; + private readonly region; + private readonly roleArn?; + private readonly roleSessionName?; + private readonly externalId?; + private readonly token?; + private readonly webIdentityToken?; + private readonly action; + private _credentials; + private readonly expirySeconds; + private accessExpiresAt; + private readonly transportAgent?; + private readonly transport; + constructor({ + stsEndpoint, + accessKey, + secretKey, + durationSeconds, + sessionToken, + policy, + region, + roleArn, + roleSessionName, + externalId, + token, + webIdentityToken, + action, + transportAgent + }: AssumeRoleProviderOptions); + getRequestConfig(): { + requestOptions: http.RequestOptions; + requestData: string; + }; + performRequest(): Promise; + parseCredentials(respObj: CredentialResponse): Credentials; + refreshCredentials(): Promise; + getCredentials(): Promise; + isAboutToExpire(): boolean; +} +export default AssumeRoleProvider; \ No newline at end of file diff --git a/node_modules/minio/dist/main/AssumeRoleProvider.js b/node_modules/minio/dist/main/AssumeRoleProvider.js new file mode 100644 index 0000000..951b97f --- /dev/null +++ b/node_modules/minio/dist/main/AssumeRoleProvider.js @@ -0,0 +1,190 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var http = _interopRequireWildcard(require("http"), true); +var https = _interopRequireWildcard(require("https"), true); +var _url = require("url"); +var _CredentialProvider = require("./CredentialProvider.js"); +var _Credentials = require("./Credentials.js"); +var _helper = require("./internal/helper.js"); +var _request = require("./internal/request.js"); +var _response = require("./internal/response.js"); +var _signing = require("./signing.js"); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +/** + * @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html + */ + +const defaultExpirySeconds = 900; +class AssumeRoleProvider extends _CredentialProvider.CredentialProvider { + accessExpiresAt = ''; + constructor({ + stsEndpoint, + accessKey, + secretKey, + durationSeconds = defaultExpirySeconds, + sessionToken, + policy, + region = '', + roleArn, + roleSessionName, + externalId, + token, + webIdentityToken, + action = 'AssumeRole', + transportAgent = undefined + }) { + super({ + accessKey, + secretKey, + sessionToken + }); + this.stsEndpoint = new _url.URL(stsEndpoint); + this.accessKey = accessKey; + this.secretKey = secretKey; + this.policy = policy; + this.region = region; + this.roleArn = roleArn; + this.roleSessionName = roleSessionName; + this.externalId = externalId; + this.token = token; + this.webIdentityToken = webIdentityToken; + this.action = action; + this.durationSeconds = parseInt(durationSeconds); + let expirySeconds = this.durationSeconds; + if (this.durationSeconds < defaultExpirySeconds) { + expirySeconds = defaultExpirySeconds; + } + this.expirySeconds = expirySeconds; // for calculating refresh of credentials. + + // By default, nodejs uses a global agent if the 'agent' property + // is set to undefined. Otherwise, it's okay to assume the users + // know what they're doing if they specify a custom transport agent. + this.transportAgent = transportAgent; + const isHttp = this.stsEndpoint.protocol === 'http:'; + this.transport = isHttp ? http : https; + + /** + * Internal Tracking variables + */ + this._credentials = null; + } + getRequestConfig() { + const hostValue = this.stsEndpoint.hostname; + const portValue = this.stsEndpoint.port; + const qryParams = new _url.URLSearchParams({ + Action: this.action, + Version: '2011-06-15' + }); + qryParams.set('DurationSeconds', this.expirySeconds.toString()); + if (this.policy) { + qryParams.set('Policy', this.policy); + } + if (this.roleArn) { + qryParams.set('RoleArn', this.roleArn); + } + if (this.roleSessionName != null) { + qryParams.set('RoleSessionName', this.roleSessionName); + } + if (this.token != null) { + qryParams.set('Token', this.token); + } + if (this.webIdentityToken) { + qryParams.set('WebIdentityToken', this.webIdentityToken); + } + if (this.externalId) { + qryParams.set('ExternalId', this.externalId); + } + const urlParams = qryParams.toString(); + const contentSha256 = (0, _helper.toSha256)(urlParams); + const date = new Date(); + const requestOptions = { + hostname: hostValue, + port: portValue, + path: '/', + protocol: this.stsEndpoint.protocol, + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'content-length': urlParams.length.toString(), + host: hostValue, + 'x-amz-date': (0, _helper.makeDateLong)(date), + 'x-amz-content-sha256': contentSha256 + }, + agent: this.transportAgent + }; + requestOptions.headers.authorization = (0, _signing.signV4ByServiceName)(requestOptions, this.accessKey, this.secretKey, this.region, date, contentSha256, 'sts'); + return { + requestOptions, + requestData: urlParams + }; + } + async performRequest() { + const { + requestOptions, + requestData + } = this.getRequestConfig(); + const res = await (0, _request.request)(this.transport, requestOptions, requestData); + const body = await (0, _response.readAsString)(res); + return (0, _helper.parseXml)(body); + } + parseCredentials(respObj) { + if (respObj.ErrorResponse) { + var _respObj$ErrorRespons, _respObj$ErrorRespons2, _respObj$ErrorRespons3, _respObj$ErrorRespons4; + throw new Error(`Unable to obtain credentials: ${(_respObj$ErrorRespons = respObj.ErrorResponse) === null || _respObj$ErrorRespons === void 0 ? void 0 : (_respObj$ErrorRespons2 = _respObj$ErrorRespons.Error) === null || _respObj$ErrorRespons2 === void 0 ? void 0 : _respObj$ErrorRespons2.Code} ${(_respObj$ErrorRespons3 = respObj.ErrorResponse) === null || _respObj$ErrorRespons3 === void 0 ? void 0 : (_respObj$ErrorRespons4 = _respObj$ErrorRespons3.Error) === null || _respObj$ErrorRespons4 === void 0 ? void 0 : _respObj$ErrorRespons4.Message}`, { + cause: respObj + }); + } + const { + AssumeRoleResponse: { + AssumeRoleResult: { + Credentials: { + AccessKeyId: accessKey, + SecretAccessKey: secretKey, + SessionToken: sessionToken, + Expiration: expiresAt + } + } + } + } = respObj; + this.accessExpiresAt = expiresAt; + return new _Credentials.Credentials({ + accessKey, + secretKey, + sessionToken + }); + } + async refreshCredentials() { + try { + const assumeRoleCredentials = await this.performRequest(); + this._credentials = this.parseCredentials(assumeRoleCredentials); + } catch (err) { + throw new Error(`Failed to get Credentials: ${err}`, { + cause: err + }); + } + return this._credentials; + } + async getCredentials() { + if (this._credentials && !this.isAboutToExpire()) { + return this._credentials; + } + this._credentials = await this.refreshCredentials(); + return this._credentials; + } + isAboutToExpire() { + const expiresAt = new Date(this.accessExpiresAt); + const provisionalExpiry = new Date(Date.now() + 1000 * 10); // check before 10 seconds. + return provisionalExpiry > expiresAt; + } +} + +// deprecated default export, please use named exports. +// keep for backward compatibility. +// eslint-disable-next-line import/no-default-export +exports.AssumeRoleProvider = AssumeRoleProvider; +var _default = AssumeRoleProvider; +exports.default = _default; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJodHRwIiwiX2ludGVyb3BSZXF1aXJlV2lsZGNhcmQiLCJyZXF1aXJlIiwiaHR0cHMiLCJfdXJsIiwiX0NyZWRlbnRpYWxQcm92aWRlciIsIl9DcmVkZW50aWFscyIsIl9oZWxwZXIiLCJfcmVxdWVzdCIsIl9yZXNwb25zZSIsIl9zaWduaW5nIiwiZSIsInQiLCJXZWFrTWFwIiwiciIsIm4iLCJfX2VzTW9kdWxlIiwibyIsImkiLCJmIiwiX19wcm90b19fIiwiZGVmYXVsdCIsImhhcyIsImdldCIsInNldCIsImhhc093blByb3BlcnR5IiwiY2FsbCIsIk9iamVjdCIsImRlZmluZVByb3BlcnR5IiwiZ2V0T3duUHJvcGVydHlEZXNjcmlwdG9yIiwiZGVmYXVsdEV4cGlyeVNlY29uZHMiLCJBc3N1bWVSb2xlUHJvdmlkZXIiLCJDcmVkZW50aWFsUHJvdmlkZXIiLCJhY2Nlc3NFeHBpcmVzQXQiLCJjb25zdHJ1Y3RvciIsInN0c0VuZHBvaW50IiwiYWNjZXNzS2V5Iiwic2VjcmV0S2V5IiwiZHVyYXRpb25TZWNvbmRzIiwic2Vzc2l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EsR0FDZXJGLGtCQUFrQjtBQUFBb0YsT0FBQSxDQUFBOUYsT0FBQSxHQUFBK0YsUUFBQSJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/CredentialProvider.d.ts b/node_modules/minio/dist/main/CredentialProvider.d.ts new file mode 100644 index 0000000..b2b3913 --- /dev/null +++ b/node_modules/minio/dist/main/CredentialProvider.d.ts @@ -0,0 +1,22 @@ +import { Credentials } from "./Credentials.js"; +export declare class CredentialProvider { + private credentials; + constructor({ + accessKey, + secretKey, + sessionToken + }: { + accessKey: string; + secretKey: string; + sessionToken?: string; + }); + getCredentials(): Promise; + setCredentials(credentials: Credentials): void; + setAccessKey(accessKey: string): void; + getAccessKey(): string; + setSecretKey(secretKey: string): void; + getSecretKey(): string; + setSessionToken(sessionToken: string): void; + getSessionToken(): string | undefined; +} +export default CredentialProvider; \ No newline at end of file diff --git a/node_modules/minio/dist/main/CredentialProvider.js b/node_modules/minio/dist/main/CredentialProvider.js new file mode 100644 index 0000000..63b54db --- /dev/null +++ b/node_modules/minio/dist/main/CredentialProvider.js @@ -0,0 +1,55 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _Credentials = require("./Credentials.js"); +class CredentialProvider { + constructor({ + accessKey, + secretKey, + sessionToken + }) { + this.credentials = new _Credentials.Credentials({ + accessKey, + secretKey, + sessionToken + }); + } + async getCredentials() { + return this.credentials.get(); + } + setCredentials(credentials) { + if (credentials instanceof _Credentials.Credentials) { + this.credentials = credentials; + } else { + throw new Error('Unable to set Credentials. it should be an instance of Credentials class'); + } + } + setAccessKey(accessKey) { + this.credentials.setAccessKey(accessKey); + } + getAccessKey() { + return this.credentials.getAccessKey(); + } + setSecretKey(secretKey) { + this.credentials.setSecretKey(secretKey); + } + getSecretKey() { + return this.credentials.getSecretKey(); + } + setSessionToken(sessionToken) { + this.credentials.setSessionToken(sessionToken); + } + getSessionToken() { + return this.credentials.getSessionToken(); + } +} + +// deprecated default export, please use named exports. +// keep for backward compatibility. +// eslint-disable-next-line import/no-default-export +exports.CredentialProvider = CredentialProvider; +var _default = CredentialProvider; +exports.default = _default; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfQ3JlZGVudGlhbHMiLCJyZXF1aXJlIiwiQ3JlZGVudGlhbFByb3ZpZGVyIiwiY29uc3RydWN0b3IiLCJhY2Nlc3NLZXkiLCJzZWNyZXRLZXkiLCJzZXNzaW9uVG9rZW4iLCJjcmVkZW50aWFscyIsIkNyZWRlbnRpYWxzIiwiZ2V0Q3JlZGVudGlhbHMiLCJnZXQiLCJzZXRDcmVkZW50aWFscyIsIkVycm9yIiwic2V0QWNjZXNzS2V5IiwiZ2V0QWNjZXNzS2V5Iiwic2V0U2VjcmV0S2V5IiwiZ2V0U2VjcmV0S2V5Iiwic2V0U2Vzc2lvblRva2VuIiwiZ2V0U2Vzc2lvblRva2VuIiwiZXhwb3J0cyIsIl9kZWZhdWx0IiwiZGVmYXVsdCJdLCJzb3VyY2VzIjpbIkNyZWRlbnRpYWxQcm92aWRlci50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyBDcmVkZW50aWFscyB9IGZyb20gJy4vQ3JlZGVudGlhbHMudHMnXG5cbmV4cG9ydCBjbGFzcyBDcmVkZW50aWFsUHJvdmlkZXIge1xuICBwcml2YXRlIGNyZWRlbnRpYWxzOiBDcmVkZW50aWFsc1xuXG4gIGNvbnN0cnVjdG9yKHsgYWNjZXNzS2V5LCBzZWNyZXRLZXksIHNlc3Npb25Ub2tlbiB9OiB7IGFjY2Vzc0tleTogc3RyaW5nOyBzZWNyZXRLZXk6IHN0cmluZzsgc2Vzc2lvblRva2VuPzogc3RyaW5nIH0pIHtcbiAgICB0aGlzLmNyZWRlbnRpYWxzID0gbmV3IENyZWRlbnRpYWxzKHtcbiAgICAgIGFjY2Vzc0tleSxcbiAgICAgIHNlY3JldEtleSxcbiAgICAgIHNlc3Npb25Ub2tlbix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7RUFFQVUsWUFBWUEsQ0FBQSxFQUFHO0lBQ2IsT0FBTyxJQUFJLENBQUNQLFdBQVcsQ0FBQ08sWUFBWSxDQUFDLENBQUM7RUFDeEM7RUFFQUMsWUFBWUEsQ0FBQ1YsU0FBaUIsRUFBRTtJQUM5QixJQUFJLENBQUNFLFdBQVcsQ0FBQ1EsWUFBWSxDQUFDVixTQUFTLENBQUM7RUFDMUM7RUFFQVcsWUFBWUEsQ0FBQSxFQUFHO0lBQ2IsT0FBTyxJQUFJLENBQUNULFdBQVcsQ0FBQ1MsWUFBWSxDQUFDLENBQUM7RUFDeEM7RUFFQUMsZUFBZUEsQ0FBQ1gsWUFBb0IsRUFBRTtJQUNwQyxJQUFJLENBQUNDLFdBQVcsQ0FBQ1UsZUFBZSxDQUFDWCxZQUFZLENBQUM7RUFDaEQ7RUFFQVksZUFBZUEsQ0FBQSxFQUFHO0lBQ2hCLE9BQU8sSUFBSSxDQUFDWCxXQUFXLENBQUNXLGVBQWUsQ0FBQyxDQUFDO0VBQzNDO0FBQ0Y7O0FBRUE7QUFDQTtBQUNBO0FBQUFDLE9BQUEsQ0FBQWpCLGtCQUFBLEdBQUFBLGtCQUFBO0FBQUEsSUFBQWtCLFFBQUEsR0FDZWxCLGtCQUFrQjtBQUFBaUIsT0FBQSxDQUFBRSxPQUFBLEdBQUFELFFBQUEifQ== \ No newline at end of file diff --git a/node_modules/minio/dist/main/Credentials.d.ts b/node_modules/minio/dist/main/Credentials.d.ts new file mode 100644 index 0000000..9e8eb51 --- /dev/null +++ b/node_modules/minio/dist/main/Credentials.d.ts @@ -0,0 +1,22 @@ +export declare class Credentials { + accessKey: string; + secretKey: string; + sessionToken?: string; + constructor({ + accessKey, + secretKey, + sessionToken + }: { + accessKey: string; + secretKey: string; + sessionToken?: string; + }); + setAccessKey(accessKey: string): void; + getAccessKey(): string; + setSecretKey(secretKey: string): void; + getSecretKey(): string; + setSessionToken(sessionToken: string): void; + getSessionToken(): string | undefined; + get(): Credentials; +} +export default Credentials; \ No newline at end of file diff --git a/node_modules/minio/dist/main/Credentials.js b/node_modules/minio/dist/main/Credentials.js new file mode 100644 index 0000000..8574c0b --- /dev/null +++ b/node_modules/minio/dist/main/Credentials.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +class Credentials { + constructor({ + accessKey, + secretKey, + sessionToken + }) { + this.accessKey = accessKey; + this.secretKey = secretKey; + this.sessionToken = sessionToken; + } + setAccessKey(accessKey) { + this.accessKey = accessKey; + } + getAccessKey() { + return this.accessKey; + } + setSecretKey(secretKey) { + this.secretKey = secretKey; + } + getSecretKey() { + return this.secretKey; + } + setSessionToken(sessionToken) { + this.sessionToken = sessionToken; + } + getSessionToken() { + return this.sessionToken; + } + get() { + return this; + } +} + +// deprecated default export, please use named exports. +// keep for backward compatibility. +// eslint-disable-next-line import/no-default-export +exports.Credentials = Credentials; +var _default = Credentials; +exports.default = _default; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDcmVkZW50aWFscyIsImNvbnN0cnVjdG9yIiwiYWNjZXNzS2V5Iiwic2VjcmV0S2V5Iiwic2Vzc2lvblRva2VuIiwic2V0QWNjZXNzS2V5IiwiZ2V0QWNjZXNzS2V5Iiwic2V0U2VjcmV0S2V5IiwiZ2V0U2VjcmV0S2V5Iiwic2V0U2Vzc2lvblRva2VuIiwiZ2V0U2Vzc2lvblRva2VuIiwiZ2V0IiwiZXhwb3J0cyIsIl9kZWZhdWx0IiwiZGVmYXVsdCJdLCJzb3VyY2VzIjpbIkNyZWRlbnRpYWxzLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBjbGFzcyBDcmVkZW50aWFscyB7XG4gIHB1YmxpYyBhY2Nlc3NLZXk6IHN0cmluZ1xuICBwdWJsaWMgc2VjcmV0S2V5OiBzdHJpbmdcbiAgcHVibGljIHNlc3Npb25Ub2tlbj86IHN0cmluZ1xuXG4g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BQUQsUUFBQSJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/IamAwsProvider.d.ts b/node_modules/minio/dist/main/IamAwsProvider.d.ts new file mode 100644 index 0000000..accc4d7 --- /dev/null +++ b/node_modules/minio/dist/main/IamAwsProvider.d.ts @@ -0,0 +1,27 @@ +/// +import * as http from 'node:http'; +import { CredentialProvider } from "./CredentialProvider.js"; +import { Credentials } from "./Credentials.js"; +export interface IamAwsProviderOptions { + customEndpoint?: string; + transportAgent?: http.Agent; +} +export declare class IamAwsProvider extends CredentialProvider { + private readonly customEndpoint?; + private _credentials; + private readonly transportAgent?; + private accessExpiresAt; + constructor({ + customEndpoint, + transportAgent + }: IamAwsProviderOptions); + getCredentials(): Promise; + private fetchCredentials; + private fetchCredentialsUsingTokenFile; + private fetchImdsToken; + private getIamRoleNamedUrl; + private getIamRoleName; + private requestCredentials; + private isAboutToExpire; +} +export default IamAwsProvider; \ No newline at end of file diff --git a/node_modules/minio/dist/main/IamAwsProvider.js b/node_modules/minio/dist/main/IamAwsProvider.js new file mode 100644 index 0000000..0ef720e --- /dev/null +++ b/node_modules/minio/dist/main/IamAwsProvider.js @@ -0,0 +1,197 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var fs = _interopRequireWildcard(require("fs/promises"), true); +var http = _interopRequireWildcard(require("http"), true); +var https = _interopRequireWildcard(require("https"), true); +var _url = require("url"); +var _CredentialProvider = require("./CredentialProvider.js"); +var _Credentials = require("./Credentials.js"); +var _helper = require("./internal/helper.js"); +var _request = require("./internal/request.js"); +var _response = require("./internal/response.js"); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +class IamAwsProvider extends _CredentialProvider.CredentialProvider { + accessExpiresAt = ''; + constructor({ + customEndpoint = undefined, + transportAgent = undefined + }) { + super({ + accessKey: '', + secretKey: '' + }); + this.customEndpoint = customEndpoint; + this.transportAgent = transportAgent; + + /** + * Internal Tracking variables + */ + this._credentials = null; + } + async getCredentials() { + if (!this._credentials || this.isAboutToExpire()) { + this._credentials = await this.fetchCredentials(); + } + return this._credentials; + } + async fetchCredentials() { + try { + // check for IRSA (https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) + const tokenFile = process.env.AWS_WEB_IDENTITY_TOKEN_FILE; + if (tokenFile) { + return await this.fetchCredentialsUsingTokenFile(tokenFile); + } + + // try with IAM role for EC2 instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) + let tokenHeader = 'Authorization'; + let token = process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN; + const relativeUri = process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI; + const fullUri = process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI; + let url; + if (relativeUri) { + url = new _url.URL(relativeUri, 'http://169.254.170.2'); + } else if (fullUri) { + url = new _url.URL(fullUri); + } else { + token = await this.fetchImdsToken(); + tokenHeader = 'X-aws-ec2-metadata-token'; + url = await this.getIamRoleNamedUrl(token); + } + return this.requestCredentials(url, tokenHeader, token); + } catch (err) { + throw new Error(`Failed to get Credentials: ${err}`, { + cause: err + }); + } + } + async fetchCredentialsUsingTokenFile(tokenFile) { + const token = await fs.readFile(tokenFile, { + encoding: 'utf8' + }); + const region = process.env.AWS_REGION; + const stsEndpoint = new _url.URL(region ? `https://sts.${region}.amazonaws.com` : 'https://sts.amazonaws.com'); + const hostValue = stsEndpoint.hostname; + const portValue = stsEndpoint.port; + const qryParams = new _url.URLSearchParams({ + Action: 'AssumeRoleWithWebIdentity', + Version: '2011-06-15' + }); + const roleArn = process.env.AWS_ROLE_ARN; + if (roleArn) { + qryParams.set('RoleArn', roleArn); + const roleSessionName = process.env.AWS_ROLE_SESSION_NAME; + qryParams.set('RoleSessionName', roleSessionName ? roleSessionName : Date.now().toString()); + } + qryParams.set('WebIdentityToken', token); + qryParams.sort(); + const requestOptions = { + hostname: hostValue, + port: portValue, + path: `${stsEndpoint.pathname}?${qryParams.toString()}`, + protocol: stsEndpoint.protocol, + method: 'POST', + headers: {}, + agent: this.transportAgent + }; + const transport = stsEndpoint.protocol === 'http:' ? http : https; + const res = await (0, _request.request)(transport, requestOptions, null); + const body = await (0, _response.readAsString)(res); + const assumeRoleResponse = (0, _helper.parseXml)(body); + const creds = assumeRoleResponse.AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult.Credentials; + this.accessExpiresAt = creds.Expiration; + return new _Credentials.Credentials({ + accessKey: creds.AccessKeyId, + secretKey: creds.SecretAccessKey, + sessionToken: creds.SessionToken + }); + } + async fetchImdsToken() { + const endpoint = this.customEndpoint ? this.customEndpoint : 'http://169.254.169.254'; + const url = new _url.URL('/latest/api/token', endpoint); + const requestOptions = { + hostname: url.hostname, + port: url.port, + path: `${url.pathname}${url.search}`, + protocol: url.protocol, + method: 'PUT', + headers: { + 'X-aws-ec2-metadata-token-ttl-seconds': '21600' + }, + agent: this.transportAgent + }; + const transport = url.protocol === 'http:' ? http : https; + const res = await (0, _request.request)(transport, requestOptions, null); + return await (0, _response.readAsString)(res); + } + async getIamRoleNamedUrl(token) { + const endpoint = this.customEndpoint ? this.customEndpoint : 'http://169.254.169.254'; + const url = new _url.URL('latest/meta-data/iam/security-credentials/', endpoint); + const roleName = await this.getIamRoleName(url, token); + return new _url.URL(`${url.pathname}/${encodeURIComponent(roleName)}`, url.origin); + } + async getIamRoleName(url, token) { + const requestOptions = { + hostname: url.hostname, + port: url.port, + path: `${url.pathname}${url.search}`, + protocol: url.protocol, + method: 'GET', + headers: { + 'X-aws-ec2-metadata-token': token + }, + agent: this.transportAgent + }; + const transport = url.protocol === 'http:' ? http : https; + const res = await (0, _request.request)(transport, requestOptions, null); + const body = await (0, _response.readAsString)(res); + const roleNames = body.split(/\r\n|[\n\r\u2028\u2029]/); + if (roleNames.length === 0) { + throw new Error(`No IAM roles attached to EC2 service ${url}`); + } + return roleNames[0]; + } + async requestCredentials(url, tokenHeader, token) { + const headers = {}; + if (token) { + headers[tokenHeader] = token; + } + const requestOptions = { + hostname: url.hostname, + port: url.port, + path: `${url.pathname}${url.search}`, + protocol: url.protocol, + method: 'GET', + headers: headers, + agent: this.transportAgent + }; + const transport = url.protocol === 'http:' ? http : https; + const res = await (0, _request.request)(transport, requestOptions, null); + const body = await (0, _response.readAsString)(res); + const ecsCredentials = JSON.parse(body); + if (!ecsCredentials.Code || ecsCredentials.Code != 'Success') { + throw new Error(`${url} failed with code ${ecsCredentials.Code} and message ${ecsCredentials.Message}`); + } + this.accessExpiresAt = ecsCredentials.Expiration; + return new _Credentials.Credentials({ + accessKey: ecsCredentials.AccessKeyID, + secretKey: ecsCredentials.SecretAccessKey, + sessionToken: ecsCredentials.Token + }); + } + isAboutToExpire() { + const expiresAt = new Date(this.accessExpiresAt); + const provisionalExpiry = new Date(Date.now() + 1000 * 10); // 10 seconds leeway + return provisionalExpiry > expiresAt; + } +} + +// deprecated default export, please use named exports. +// keep for backward compatibility. +// eslint-disable-next-line import/no-default-export +exports.IamAwsProvider = IamAwsProvider; +var _default = IamAwsProvider; +exports.default = _default; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJmcyIsIl9pbnRlcm9wUmVxdWlyZVdpbGRjYXJkIiwicmVxdWlyZSIsImh0dHAiLCJodHRwcyIsIl91cmwiLCJfQ3JlZGVudGlhbFByb3ZpZGVyIiwiX0NyZWRlbnRpYWxzIiwiX2hlbHBlciIsIl9yZXF1ZXN0IiwiX3Jlc3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R0FBRyxJQUFJNUMsSUFBSSxDQUFDQSxJQUFJLENBQUNDLEdBQUcsQ0FBQyxDQUFDLEdBQUcsSUFBSSxHQUFHLEVBQUUsQ0FBQyxFQUFDO0lBQzNELE9BQU8yQyxpQkFBaUIsR0FBR0QsU0FBUztFQUN0QztBQUNGOztBQUVBO0FBQ0E7QUFDQTtBQUFBRSxPQUFBLENBQUEvRixjQUFBLEdBQUFBLGNBQUE7QUFBQSxJQUFBZ0csUUFBQSxHQUNlaEcsY0FBYztBQUFBK0YsT0FBQSxDQUFBeEcsT0FBQSxHQUFBeUcsUUFBQSJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/errors.d.ts b/node_modules/minio/dist/main/errors.d.ts new file mode 100644 index 0000000..aa14700 --- /dev/null +++ b/node_modules/minio/dist/main/errors.d.ts @@ -0,0 +1,82 @@ +/// +declare class ExtendableError extends Error { + constructor(message?: string, opt?: ErrorOptions); +} +/** + * AnonymousRequestError is generated for anonymous keys on specific + * APIs. NOTE: PresignedURL generation always requires access keys. + */ +export declare class AnonymousRequestError extends ExtendableError {} +/** + * InvalidArgumentError is generated for all invalid arguments. + */ +export declare class InvalidArgumentError extends ExtendableError {} +/** + * InvalidPortError is generated when a non integer value is provided + * for ports. + */ +export declare class InvalidPortError extends ExtendableError {} +/** + * InvalidEndpointError is generated when an invalid end point value is + * provided which does not follow domain standards. + */ +export declare class InvalidEndpointError extends ExtendableError {} +/** + * InvalidBucketNameError is generated when an invalid bucket name is + * provided which does not follow AWS S3 specifications. + * http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html + */ +export declare class InvalidBucketNameError extends ExtendableError {} +/** + * InvalidObjectNameError is generated when an invalid object name is + * provided which does not follow AWS S3 specifications. + * http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html + */ +export declare class InvalidObjectNameError extends ExtendableError {} +/** + * AccessKeyRequiredError generated by signature methods when access + * key is not found. + */ +export declare class AccessKeyRequiredError extends ExtendableError {} +/** + * SecretKeyRequiredError generated by signature methods when secret + * key is not found. + */ +export declare class SecretKeyRequiredError extends ExtendableError {} +/** + * ExpiresParamError generated when expires parameter value is not + * well within stipulated limits. + */ +export declare class ExpiresParamError extends ExtendableError {} +/** + * InvalidDateError generated when invalid date is found. + */ +export declare class InvalidDateError extends ExtendableError {} +/** + * InvalidPrefixError generated when object prefix provided is invalid + * or does not conform to AWS S3 object key restrictions. + */ +export declare class InvalidPrefixError extends ExtendableError {} +/** + * InvalidBucketPolicyError generated when the given bucket policy is invalid. + */ +export declare class InvalidBucketPolicyError extends ExtendableError {} +/** + * IncorrectSizeError generated when total data read mismatches with + * the input size. + */ +export declare class IncorrectSizeError extends ExtendableError {} +/** + * InvalidXMLError generated when an unknown XML is found. + */ +export declare class InvalidXMLError extends ExtendableError {} +/** + * S3Error is generated for errors returned from S3 server. + * see getErrorTransformer for details + */ +export declare class S3Error extends ExtendableError { + code?: string; + region?: string; +} +export declare class IsValidBucketNameError extends ExtendableError {} +export {}; \ No newline at end of file diff --git a/node_modules/minio/dist/main/errors.js b/node_modules/minio/dist/main/errors.js new file mode 100644 index 0000000..5dd04f1 --- /dev/null +++ b/node_modules/minio/dist/main/errors.js @@ -0,0 +1,138 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// + +class ExtendableError extends Error { + constructor(message, opt) { + // error Option {cause?: unknown} is a 'nice to have', + // don't use it internally + super(message, opt); + // set error name, otherwise it's always 'Error' + this.name = this.constructor.name; + } +} + +/** + * AnonymousRequestError is generated for anonymous keys on specific + * APIs. NOTE: PresignedURL generation always requires access keys. + */ +class AnonymousRequestError extends ExtendableError {} + +/** + * InvalidArgumentError is generated for all invalid arguments. + */ +exports.AnonymousRequestError = AnonymousRequestError; +class InvalidArgumentError extends ExtendableError {} + +/** + * InvalidPortError is generated when a non integer value is provided + * for ports. + */ +exports.InvalidArgumentError = InvalidArgumentError; +class InvalidPortError extends ExtendableError {} + +/** + * InvalidEndpointError is generated when an invalid end point value is + * provided which does not follow domain standards. + */ +exports.InvalidPortError = InvalidPortError; +class InvalidEndpointError extends ExtendableError {} + +/** + * InvalidBucketNameError is generated when an invalid bucket name is + * provided which does not follow AWS S3 specifications. + * http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html + */ +exports.InvalidEndpointError = InvalidEndpointError; +class InvalidBucketNameError extends ExtendableError {} + +/** + * InvalidObjectNameError is generated when an invalid object name is + * provided which does not follow AWS S3 specifications. + * http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html + */ +exports.InvalidBucketNameError = InvalidBucketNameError; +class InvalidObjectNameError extends ExtendableError {} + +/** + * AccessKeyRequiredError generated by signature methods when access + * key is not found. + */ +exports.InvalidObjectNameError = InvalidObjectNameError; +class AccessKeyRequiredError extends ExtendableError {} + +/** + * SecretKeyRequiredError generated by signature methods when secret + * key is not found. + */ +exports.AccessKeyRequiredError = AccessKeyRequiredError; +class SecretKeyRequiredError extends ExtendableError {} + +/** + * ExpiresParamError generated when expires parameter value is not + * well within stipulated limits. + */ +exports.SecretKeyRequiredError = SecretKeyRequiredError; +class ExpiresParamError extends ExtendableError {} + +/** + * InvalidDateError generated when invalid date is found. + */ +exports.ExpiresParamError = ExpiresParamError; +class InvalidDateError extends ExtendableError {} + +/** + * InvalidPrefixError generated when object prefix provided is invalid + * or does not conform to AWS S3 object key restrictions. + */ +exports.InvalidDateError = InvalidDateError; +class InvalidPrefixError extends ExtendableError {} + +/** + * InvalidBucketPolicyError generated when the given bucket policy is invalid. + */ +exports.InvalidPrefixError = InvalidPrefixError; +class InvalidBucketPolicyError extends ExtendableError {} + +/** + * IncorrectSizeError generated when total data read mismatches with + * the input size. + */ +exports.InvalidBucketPolicyError = InvalidBucketPolicyError; +class IncorrectSizeError extends ExtendableError {} + +/** + * InvalidXMLError generated when an unknown XML is found. + */ +exports.IncorrectSizeError = IncorrectSizeError; +class InvalidXMLError extends ExtendableError {} + +/** + * S3Error is generated for errors returned from S3 server. + * see getErrorTransformer for details + */ +exports.InvalidXMLError = InvalidXMLError; +class S3Error extends ExtendableError {} +exports.S3Error = S3Error; +class IsValidBucketNameError extends ExtendableError {} +exports.IsValidBucketNameError = IsValidBucketNameError; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJFeHRlbmRhYmxlRXJyb3IiLCJFcnJvciIsImNvbnN0cnVjdG9yIiwibWVzc2FnZSIsIm9wdCIsIm5hbWUiLCJBbm9ueW1vdXNSZXF1ZXN0RXJyb3IiLCJleHBvcnRzIiwiSW52YWxpZEFyZ3VtZW50RXJyb3IiLCJJbnZhbGlkUG9ydEVycm9yIiwiSW52YWxpZEVuZHBvaW50RXJyb3IiLCJJbnZhbGlkQnVja2V0TmFtZUVycm9yIiwiSW52YWxpZE9iamVjdE5hbWVFcnJvciIsIkFjY2Vzc0tleVJlcXVpcmVkRXJyb3IiLCJTZWNyZXRLZXlSZXF1aXJlZEVycm9yIiwiRXhwaXJlc1BhcmFtRXJyb3IiLCJJbnZhbGlkRGF0ZUVycm9yIiwiSW52YWxpZFByZWZpeEVycm9yIiwiSW52YWxpZEJ1Y2tldFBvbGljeUVycm9yIiwiSW5jb3JyZWN0U2l6ZUVycm9yIiwiSW52YWxpZFhNTEVycm9yIiwiUzNFcnJvciIsIklzVmFsaWRCdWNrZXROYW1lRXJyb3IiXSwic291cmNlcyI6WyJlcnJvcnMudHMiXSwic291cmNlc0NvbnRlbnQiOlsiLypcbiAqIE1p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UFBRU8sT0FBQSxDQUFBZSxzQkFBQSxHQUFBQSxzQkFBQSJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/helpers.d.ts b/node_modules/minio/dist/main/helpers.d.ts new file mode 100644 index 0000000..26ce1b1 --- /dev/null +++ b/node_modules/minio/dist/main/helpers.d.ts @@ -0,0 +1,156 @@ +import type { Encryption, ObjectMetaData, RequestHeaders } from "./internal/type.js"; +import { RETENTION_MODES } from "./internal/type.js"; +export { ENCRYPTION_TYPES, LEGAL_HOLD_STATUS, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from "./internal/type.js"; +export declare const DEFAULT_REGION = "us-east-1"; +export declare const PRESIGN_EXPIRY_DAYS_MAX: number; +export interface ICopySourceOptions { + Bucket: string; + Object: string; + /** + * Valid versionId + */ + VersionID?: string; + /** + * Etag to match + */ + MatchETag?: string; + /** + * Etag to exclude + */ + NoMatchETag?: string; + /** + * Modified Date of the object/part. UTC Date in string format + */ + MatchModifiedSince?: string | null; + /** + * Modified Date of the object/part to exclude UTC Date in string format + */ + MatchUnmodifiedSince?: string | null; + /** + * true or false Object range to match + */ + MatchRange?: boolean; + Start?: number; + End?: number; + Encryption?: Encryption; +} +export declare class CopySourceOptions { + readonly Bucket: string; + readonly Object: string; + readonly VersionID: string; + MatchETag: string; + private readonly NoMatchETag; + private readonly MatchModifiedSince; + private readonly MatchUnmodifiedSince; + readonly MatchRange: boolean; + readonly Start: number; + readonly End: number; + private readonly Encryption?; + constructor({ + Bucket, + Object, + VersionID, + MatchETag, + NoMatchETag, + MatchModifiedSince, + MatchUnmodifiedSince, + MatchRange, + Start, + End, + Encryption + }: ICopySourceOptions); + validate(): boolean; + getHeaders(): RequestHeaders; +} +/** + * @deprecated use nodejs fs module + */ +export declare function removeDirAndFiles(dirPath: string, removeSelf?: boolean): void; +export interface ICopyDestinationOptions { + /** + * Bucket name + */ + Bucket: string; + /** + * Object Name for the destination (composed/copied) object defaults + */ + Object: string; + /** + * Encryption configuration defaults to {} + * @default {} + */ + Encryption?: Encryption; + UserMetadata?: ObjectMetaData; + /** + * query-string encoded string or Record Object + */ + UserTags?: Record | string; + LegalHold?: 'on' | 'off'; + /** + * UTC Date String + */ + RetainUntilDate?: string; + Mode?: RETENTION_MODES; + MetadataDirective?: 'COPY' | 'REPLACE'; + /** + * Extra headers for the target object + */ + Headers?: Record; +} +export declare class CopyDestinationOptions { + readonly Bucket: string; + readonly Object: string; + private readonly Encryption?; + private readonly UserMetadata?; + private readonly UserTags?; + private readonly LegalHold?; + private readonly RetainUntilDate?; + private readonly Mode?; + private readonly MetadataDirective?; + private readonly Headers?; + constructor({ + Bucket, + Object, + Encryption, + UserMetadata, + UserTags, + LegalHold, + RetainUntilDate, + Mode, + MetadataDirective, + Headers + }: ICopyDestinationOptions); + getHeaders(): RequestHeaders; + validate(): boolean; +} +/** + * maybe this should be a generic type for Records, leave it for later refactor + */ +export declare class SelectResults { + private records?; + private response?; + private stats?; + private progress?; + constructor({ + records, + // parsed data as stream + response, + // original response stream + stats, + // stats as xml + progress + }: { + records?: unknown; + response?: unknown; + stats?: string; + progress?: unknown; + }); + setStats(stats: string): void; + getStats(): string | undefined; + setProgress(progress: unknown): void; + getProgress(): unknown; + setResponse(response: unknown): void; + getResponse(): unknown; + setRecords(records: unknown): void; + getRecords(): unknown; +} \ No newline at end of file diff --git a/node_modules/minio/dist/main/helpers.js b/node_modules/minio/dist/main/helpers.js new file mode 100644 index 0000000..bea5b04 --- /dev/null +++ b/node_modules/minio/dist/main/helpers.js @@ -0,0 +1,232 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.removeDirAndFiles = removeDirAndFiles; +var fs = _interopRequireWildcard(require("fs"), true); +var path = _interopRequireWildcard(require("path"), true); +var querystring = _interopRequireWildcard(require("query-string"), true); +var errors = _interopRequireWildcard(require("./errors.js"), true); +var _helper = require("./internal/helper.js"); +var _type = require("./internal/type.js"); +exports.RETENTION_MODES = _type.RETENTION_MODES; +exports.ENCRYPTION_TYPES = _type.ENCRYPTION_TYPES; +exports.LEGAL_HOLD_STATUS = _type.LEGAL_HOLD_STATUS; +exports.RETENTION_VALIDITY_UNITS = _type.RETENTION_VALIDITY_UNITS; +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +const DEFAULT_REGION = 'us-east-1'; +exports.DEFAULT_REGION = DEFAULT_REGION; +const PRESIGN_EXPIRY_DAYS_MAX = 24 * 60 * 60 * 7; // 7 days in seconds +exports.PRESIGN_EXPIRY_DAYS_MAX = PRESIGN_EXPIRY_DAYS_MAX; +class CopySourceOptions { + constructor({ + Bucket, + Object, + VersionID = '', + MatchETag = '', + NoMatchETag = '', + MatchModifiedSince = null, + MatchUnmodifiedSince = null, + MatchRange = false, + Start = 0, + End = 0, + Encryption = undefined + }) { + this.Bucket = Bucket; + this.Object = Object; + this.VersionID = VersionID; + this.MatchETag = MatchETag; + this.NoMatchETag = NoMatchETag; + this.MatchModifiedSince = MatchModifiedSince; + this.MatchUnmodifiedSince = MatchUnmodifiedSince; + this.MatchRange = MatchRange; + this.Start = Start; + this.End = End; + this.Encryption = Encryption; + } + validate() { + if (!(0, _helper.isValidBucketName)(this.Bucket)) { + throw new errors.InvalidBucketNameError('Invalid Source bucket name: ' + this.Bucket); + } + if (!(0, _helper.isValidObjectName)(this.Object)) { + throw new errors.InvalidObjectNameError(`Invalid Source object name: ${this.Object}`); + } + if (this.MatchRange && this.Start !== -1 && this.End !== -1 && this.Start > this.End || this.Start < 0) { + throw new errors.InvalidObjectNameError('Source start must be non-negative, and start must be at most end.'); + } else if (this.MatchRange && !(0, _helper.isNumber)(this.Start) || !(0, _helper.isNumber)(this.End)) { + throw new errors.InvalidObjectNameError('MatchRange is specified. But Invalid Start and End values are specified.'); + } + return true; + } + getHeaders() { + const headerOptions = {}; + headerOptions['x-amz-copy-source'] = encodeURI(this.Bucket + '/' + this.Object); + if (!(0, _helper.isEmpty)(this.VersionID)) { + headerOptions['x-amz-copy-source'] = `${encodeURI(this.Bucket + '/' + this.Object)}?versionId=${this.VersionID}`; + } + if (!(0, _helper.isEmpty)(this.MatchETag)) { + headerOptions['x-amz-copy-source-if-match'] = this.MatchETag; + } + if (!(0, _helper.isEmpty)(this.NoMatchETag)) { + headerOptions['x-amz-copy-source-if-none-match'] = this.NoMatchETag; + } + if (!(0, _helper.isEmpty)(this.MatchModifiedSince)) { + headerOptions['x-amz-copy-source-if-modified-since'] = this.MatchModifiedSince; + } + if (!(0, _helper.isEmpty)(this.MatchUnmodifiedSince)) { + headerOptions['x-amz-copy-source-if-unmodified-since'] = this.MatchUnmodifiedSince; + } + return headerOptions; + } +} + +/** + * @deprecated use nodejs fs module + */ +exports.CopySourceOptions = CopySourceOptions; +function removeDirAndFiles(dirPath, removeSelf = true) { + if (removeSelf) { + return fs.rmSync(dirPath, { + recursive: true, + force: true + }); + } + fs.readdirSync(dirPath).forEach(item => { + fs.rmSync(path.join(dirPath, item), { + recursive: true, + force: true + }); + }); +} +class CopyDestinationOptions { + constructor({ + Bucket, + Object, + Encryption, + UserMetadata, + UserTags, + LegalHold, + RetainUntilDate, + Mode, + MetadataDirective, + Headers + }) { + this.Bucket = Bucket; + this.Object = Object; + this.Encryption = Encryption ?? undefined; // null input will become undefined, easy for runtime assert + this.UserMetadata = UserMetadata; + this.UserTags = UserTags; + this.LegalHold = LegalHold; + this.Mode = Mode; // retention mode + this.RetainUntilDate = RetainUntilDate; + this.MetadataDirective = MetadataDirective; + this.Headers = Headers; + } + getHeaders() { + const replaceDirective = 'REPLACE'; + const headerOptions = {}; + const userTags = this.UserTags; + if (!(0, _helper.isEmpty)(userTags)) { + headerOptions['X-Amz-Tagging-Directive'] = replaceDirective; + headerOptions['X-Amz-Tagging'] = (0, _helper.isObject)(userTags) ? querystring.stringify(userTags) : (0, _helper.isString)(userTags) ? userTags : ''; + } + if (this.Mode) { + headerOptions['X-Amz-Object-Lock-Mode'] = this.Mode; // GOVERNANCE or COMPLIANCE + } + + if (this.RetainUntilDate) { + headerOptions['X-Amz-Object-Lock-Retain-Until-Date'] = this.RetainUntilDate; // needs to be UTC. + } + + if (this.LegalHold) { + headerOptions['X-Amz-Object-Lock-Legal-Hold'] = this.LegalHold; // ON or OFF + } + + if (this.UserMetadata) { + for (const [key, value] of Object.entries(this.UserMetadata)) { + headerOptions[`X-Amz-Meta-${key}`] = value.toString(); + } + } + if (this.MetadataDirective) { + headerOptions[`X-Amz-Metadata-Directive`] = this.MetadataDirective; + } + if (this.Encryption) { + const encryptionHeaders = (0, _helper.getEncryptionHeaders)(this.Encryption); + for (const [key, value] of Object.entries(encryptionHeaders)) { + headerOptions[key] = value; + } + } + if (this.Headers) { + for (const [key, value] of Object.entries(this.Headers)) { + headerOptions[key] = value; + } + } + return headerOptions; + } + validate() { + if (!(0, _helper.isValidBucketName)(this.Bucket)) { + throw new errors.InvalidBucketNameError('Invalid Destination bucket name: ' + this.Bucket); + } + if (!(0, _helper.isValidObjectName)(this.Object)) { + throw new errors.InvalidObjectNameError(`Invalid Destination object name: ${this.Object}`); + } + if (!(0, _helper.isEmpty)(this.UserMetadata) && !(0, _helper.isObject)(this.UserMetadata)) { + throw new errors.InvalidObjectNameError(`Destination UserMetadata should be an object with key value pairs`); + } + if (!(0, _helper.isEmpty)(this.Mode) && ![_type.RETENTION_MODES.GOVERNANCE, _type.RETENTION_MODES.COMPLIANCE].includes(this.Mode)) { + throw new errors.InvalidObjectNameError(`Invalid Mode specified for destination object it should be one of [GOVERNANCE,COMPLIANCE]`); + } + if (this.Encryption !== undefined && (0, _helper.isEmptyObject)(this.Encryption)) { + throw new errors.InvalidObjectNameError(`Invalid Encryption configuration for destination object `); + } + return true; + } +} + +/** + * maybe this should be a generic type for Records, leave it for later refactor + */ +exports.CopyDestinationOptions = CopyDestinationOptions; +class SelectResults { + constructor({ + records, + // parsed data as stream + response, + // original response stream + stats, + // stats as xml + progress // stats as xml + }) { + this.records = records; + this.response = response; + this.stats = stats; + this.progress = progress; + } + setStats(stats) { + this.stats = stats; + } + getStats() { + return this.stats; + } + setProgress(progress) { + this.progress = progress; + } + getProgress() { + return this.progress; + } + setResponse(response) { + this.response = response; + } + getResponse() { + return this.response; + } + setRecords(records) { + this.records = records; + } + getRecords() { + return this.records; + } +} +exports.SelectResults = SelectResults; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJmcyIsIl9pbnRlcm9wUmVxdWlyZVdpbGRjYXJkIiwicmVxdWlyZSIsInBhdGgiLCJxdWVyeXN0cmluZyIsImVycm9ycyIsIl9oZWxwZXIiLCJfdHlwZSIsImV4cG9ydHMiLCJSRVRFTlRJT05fTU9ERVMiLCJFTkNSWVBUSU9OX1RZUEVTIiwiTEVHQUxfSE9MRF9TVEFUVVMiLCJSRVRFTlRJT05fVkFMSURJVFlfVU5JVFMiLCJlIiwidCIsIldlYWtNYXAiLCJyIiwibiIsIl9fZXNNb2R1bGUiLCJvIiwiaSIsImYiLCJfX3Byb3RvX18iLCJkZWZhdWx0IiwiaGFzIiwiZ2V0Iiwic2V0IiwiaGFzT3duUHJvcGVydHkiLCJjYWxsIiwiT2JqZWN0IiwiZGVmaW5lUHJvcGVydHkiLCJnZXRPd25Qcm9wZXJ0eURlc2NyaXB0b3IiLCJERUZBVUxUX1JFR0lPTiIsIlBSRVNJR05fRVhQSVJZX0RBWVNfTUFYIiwiQ29weVNvdXJjZU9wdGlvbnMiLCJjb25zdHJ1Y3RvciIsIkJ1Y2tldCIsIlZlcnNpb25JRCIsIk1hd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QUNQLFFBQWlCLEVBQUU7SUFDN0IsSUFBSSxDQUFDQSxRQUFRLEdBQUdBLFFBQVE7RUFDMUI7RUFFQVEsV0FBV0EsQ0FBQSxFQUFHO0lBQ1osT0FBTyxJQUFJLENBQUNSLFFBQVE7RUFDdEI7RUFFQVMsVUFBVUEsQ0FBQ1YsT0FBZ0IsRUFBRTtJQUMzQixJQUFJLENBQUNBLE9BQU8sR0FBR0EsT0FBTztFQUN4QjtFQUVBVyxVQUFVQSxDQUFBLEVBQVk7SUFDcEIsT0FBTyxJQUFJLENBQUNYLE9BQU87RUFDckI7QUFDRjtBQUFDbkYsT0FBQSxDQUFBa0YsYUFBQSxHQUFBQSxhQUFBIn0= \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/async.d.ts b/node_modules/minio/dist/main/internal/async.d.ts new file mode 100644 index 0000000..3a2e548 --- /dev/null +++ b/node_modules/minio/dist/main/internal/async.d.ts @@ -0,0 +1,9 @@ +/// +/// +import * as fs from 'node:fs'; +import * as stream from 'node:stream'; +export { promises as fsp } from 'node:fs'; +export declare const streamPromise: { + pipeline: typeof stream.pipeline.__promisify__; +}; +export declare const fstat: typeof fs.fstat.__promisify__; \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/async.js b/node_modules/minio/dist/main/internal/async.js new file mode 100644 index 0000000..9b5fdfa --- /dev/null +++ b/node_modules/minio/dist/main/internal/async.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var fs = _interopRequireWildcard(require("fs"), true); +var stream = _interopRequireWildcard(require("stream"), true); +var _util = require("util"); +var _nodeFs = require("fs"); +exports.fsp = _nodeFs.promises; +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +// promise helper for stdlib + +// TODO: use "node:fs/promise" directly after we stop testing on nodejs 12 + +const streamPromise = { + // node:stream/promises Added in: v15.0.0 + pipeline: (0, _util.promisify)(stream.pipeline) +}; +exports.streamPromise = streamPromise; +const fstat = (0, _util.promisify)(fs.fstat); +exports.fstat = fstat; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJmcyIsIl9pbnRlcm9wUmVxdWlyZVdpbGRjYXJkIiwicmVxdWlyZSIsInN0cmVhbSIsIl91dGlsIiwiX25vZGVGcyIsImV4cG9ydHMiLCJmc3AiLCJwcm9taXNlcyIsImUiLCJ0IiwiV2Vha01hcCIsInIiLCJuIiwiX19lc01vZHVsZSIsIm8iLCJpIiwiZiIsIl9fcHJvdG9fXyIsImRlZmF1bHQiLCJoYXMiLCJnZXQiLCJzZXQiLCJoYXNPd25Qcm9wZXJ0eSIsImNhbGwiLCJPYmplY3QiLCJkZWZpbmVQcm9wZXJ0eSIsImdldE93blByb3BlcnR5RGVzY3JpcHRvciIsInN0cmVhbVByb21pc2UiLCJwaXBlbGluZSIsInByb21pc2lmeSIsImZzdGF0Il0sInNvdXJjZXMiOlsiYXN5bmMudHMiXSwic291cmNlc0NvbnRlbnQiOlsiLy8gcHJvbWlzZSBoZWxwZXIgZm9yIHN0ZGxpYlxuXG5pbXBvcnQgKiBhcyBmcyBmcm9tICdub2RlOmZzJ1xuaW1wb3J0ICogYXMgc3RyZWFtIGZyb20gJ25vZGU6c3RyZWFtJ1xuaW1wb3J0IHsgcHJvbWlzaWZ5IH0gZnJvbSAnbm9kZTp1dGlsJ1xuXG4vLyBUT0RPOiB1c2UgXCJub2RlOmZzL3Byb21pc2VcIiBkaXJlY3RseSBhZ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QSxRQUFBRyxDQUFBLENBQUFLLEdBQUEsQ0FBQVgsQ0FBQSxVQUFBTSxDQUFBLENBQUFNLEdBQUEsQ0FBQVosQ0FBQSxHQUFBTSxDQUFBLENBQUFPLEdBQUEsQ0FBQWIsQ0FBQSxFQUFBUSxDQUFBLGdCQUFBUCxDQUFBLElBQUFELENBQUEsZ0JBQUFDLENBQUEsT0FBQWEsY0FBQSxDQUFBQyxJQUFBLENBQUFmLENBQUEsRUFBQUMsQ0FBQSxPQUFBTSxDQUFBLElBQUFELENBQUEsR0FBQVUsTUFBQSxDQUFBQyxjQUFBLEtBQUFELE1BQUEsQ0FBQUUsd0JBQUEsQ0FBQWxCLENBQUEsRUFBQUMsQ0FBQSxPQUFBTSxDQUFBLENBQUFLLEdBQUEsSUFBQUwsQ0FBQSxDQUFBTSxHQUFBLElBQUFQLENBQUEsQ0FBQUUsQ0FBQSxFQUFBUCxDQUFBLEVBQUFNLENBQUEsSUFBQUMsQ0FBQSxDQUFBUCxDQUFBLElBQUFELENBQUEsQ0FBQUMsQ0FBQSxXQUFBTyxDQUFBLEtBQUFSLENBQUEsRUFBQUMsQ0FBQTtBQVB6Qzs7QUFNQTs7QUFFTyxNQUFNa0IsYUFBYSxHQUFHO0VBQzNCO0VBQ0FDLFFBQVEsRUFBRSxJQUFBQyxlQUFTLEVBQUMzQixNQUFNLENBQUMwQixRQUFRO0FBQ3JDLENBQUM7QUFBQXZCLE9BQUEsQ0FBQXNCLGFBQUEsR0FBQUEsYUFBQTtBQUVNLE1BQU1HLEtBQUssR0FBRyxJQUFBRCxlQUFTLEVBQUM5QixFQUFFLENBQUMrQixLQUFLLENBQUM7QUFBQXpCLE9BQUEsQ0FBQXlCLEtBQUEsR0FBQUEsS0FBQSJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/callbackify.d.ts b/node_modules/minio/dist/main/internal/callbackify.d.ts new file mode 100644 index 0000000..89800ca --- /dev/null +++ b/node_modules/minio/dist/main/internal/callbackify.d.ts @@ -0,0 +1 @@ +export declare function callbackify(fn: (...args: any[]) => any): (this: any, ...args: any[]) => any; \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/callbackify.js b/node_modules/minio/dist/main/internal/callbackify.js new file mode 100644 index 0000000..49c247a --- /dev/null +++ b/node_modules/minio/dist/main/internal/callbackify.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.callbackify = callbackify; +/* eslint-disable @typescript-eslint/no-explicit-any */ + +// Wrapper for an async function that supports callback style API. +// It will preserve 'this'. +function callbackify(fn) { + return function (...args) { + const lastArg = args[args.length - 1]; + if (typeof lastArg === 'function') { + const callback = args.pop(); + return fn.apply(this, args).then(result => callback(null, result), err => callback(err)); + } + return fn.apply(this, args); + }; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjYWxsYmFja2lmeSIsImZuIiwiYXJncyIsImxhc3RBcmciLCJsZW5ndGgiLCJjYWxsYmFjayIsInBvcCIsImFwcGx5IiwidGhlbiIsInJlc3VsdCIsImVyciJdLCJzb3VyY2VzIjpbImNhbGxiYWNraWZ5LnRzIl0sInNvdXJjZXNDb250ZW50IjpbIi8qIGVzbGludC1kaXNhYmxlIEB0eXBlc2NyaXB0LWVzbGludC9uby1leHBsaWNpdC1hbnkgKi9cblxuLy8gV3JhcHBlciBmb3IgYW4gYXN5bmMgZnVuY3Rpb24gdGhhdCBzdXBwb3J0cyBjYWxsYmFjayBzdHlsZSBBUEkuXG4vLyBJdCB3aWxsIHByZXNlcnZlICd0aGlzJy5cbmV4cG9ydCBmdW5jdGlvbiBjYWxsYmFja2lmeShmbjogKC4uLmFyZ3M6IGFueVtdKSA9PiBhbnkpIHtcbiAgcmV0dXJuIGZ1bmN0aW9uICh0aGlzOiBhbnksIC4uLmFyZ3M6IGFueVtdKSB7XG4gICAgY29uc3QgbGFzdEFyZyA9IGFyZ3NbYXJncy5sZW5ndGggLSAxXVxuXG4gICAgaWYgKHR5cGVvZiBsYXN0QXJnID09PSAnZnVuY3Rpb24nKSB7XG4gICAgICBjb25zdCBjYWxsYmFjayA9IGFyZ3MucG9wKClcbiAgICAgIHJldHVybiBmbi5hcHBseSh0aGlzLCBhcmdzKS50aGVuKFxuICAgICAgICAocmVzdWx0OiBhbnkpID0+IGNhbGxiYWNrKG51bGwsIHJlc3VsdCksXG4gICAgICAgIChlcnI6IGFueSkgPT4gY2FsbGJhY2soZXJyKSxcbiAgICAgIClcbiAgICB9XG5cbiAgICByZXR1cm4gZm4uYXBwbHkodGhpcywgYXJncylcbiAgfVxufVxuIl0sIm1hcHBpbmdzIjoiOzs7Ozs7QUFBQTs7QUFFQTtBQUNBO0FBQ08sU0FBU0EsV0FBV0EsQ0FBQ0MsRUFBMkIsRUFBRTtFQUN2RCxPQUFPLFVBQXFCLEdBQUdDLElBQVcsRUFBRTtJQUMxQyxNQUFNQyxPQUFPLEdBQUdELElBQUksQ0FBQ0EsSUFBSSxDQUFDRSxNQUFNLEdBQUcsQ0FBQyxDQUFDO0lBRXJDLElBQUksT0FBT0QsT0FBTyxLQUFLLFVBQVUsRUFBRTtNQUNqQyxNQUFNRSxRQUFRLEdBQUdILElBQUksQ0FBQ0ksR0FBRyxDQUFDLENBQUM7TUFDM0IsT0FBT0wsRUFBRSxDQUFDTSxLQUFLLENBQUMsSUFBSSxFQUFFTCxJQUFJLENBQUMsQ0FBQ00sSUFBSSxDQUM3QkMsTUFBVyxJQUFLSixRQUFRLENBQUMsSUFBSSxFQUFFSSxNQUFNLENBQUMsRUFDdENDLEdBQVEsSUFBS0wsUUFBUSxDQUFDSyxHQUFHLENBQzVCLENBQUM7SUFDSDtJQUVBLE9BQU9ULEVBQUUsQ0FBQ00sS0FBSyxDQUFDLElBQUksRUFBRUwsSUFBSSxDQUFDO0VBQzdCLENBQUM7QUFDSCJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/client.d.ts b/node_modules/minio/dist/main/internal/client.d.ts new file mode 100644 index 0000000..5d2748a --- /dev/null +++ b/node_modules/minio/dist/main/internal/client.d.ts @@ -0,0 +1,394 @@ +/// +/// +/// +/// +import * as http from 'node:http'; +import * as https from 'node:https'; +import * as stream from 'node:stream'; +import { CredentialProvider } from "../CredentialProvider.js"; +import type { SelectResults } from "../helpers.js"; +import { CopyDestinationOptions, CopySourceOptions, LEGAL_HOLD_STATUS } from "../helpers.js"; +import type { NotificationEvent } from "../notification.js"; +import { NotificationConfig, NotificationPoller } from "../notification.js"; +import { CopyConditions } from "./copy-conditions.js"; +import { Extensions } from "./extensions.js"; +import { PostPolicy } from "./post-policy.js"; +import type { Region } from "./s3-endpoints.js"; +import type { Binary, BucketItem, BucketItemFromList, BucketItemStat, BucketStream, BucketVersioningConfiguration, CopyObjectResult, EncryptionConfig, GetObjectLegalHoldOptions, GetObjectOpts, GetObjectRetentionOpts, IncompleteUploadedBucketItem, IRequest, ItemBucketMetadata, LifecycleConfig, LifeCycleConfigParam, ListObjectQueryOpts, ListObjectV2Res, NotificationConfigResult, ObjectInfo, ObjectLockInfo, ObjectMetaData, ObjectRetentionInfo, PostPolicyResult, PreSignRequestParams, PutObjectLegalHoldOptions, RemoveObjectsParam, RemoveObjectsResponse, ReplicationConfig, ReplicationConfigOpts, RequestHeaders, ResultCallback, Retention, SelectOptions, StatObjectOpts, Tag, TaggingOpts, Tags, Transport, UploadedObjectInfo } from "./type.js"; +import type { ListMultipartResult, UploadedPart } from "./xml-parser.js"; +declare const requestOptionProperties: readonly ["agent", "ca", "cert", "ciphers", "clientCertEngine", "crl", "dhparam", "ecdhCurve", "family", "honorCipherOrder", "key", "passphrase", "pfx", "rejectUnauthorized", "secureOptions", "secureProtocol", "servername", "sessionIdContext"]; +export interface RetryOptions { + /** + * If this set to true, it will take precedence over all other retry options. + * @default false + */ + disableRetry?: boolean; + /** + * The maximum amount of retries for a request. + * @default 1 + */ + maximumRetryCount?: number; + /** + * The minimum duration (in milliseconds) for the exponential backoff algorithm. + * @default 100 + */ + baseDelayMs?: number; + /** + * The maximum duration (in milliseconds) for the exponential backoff algorithm. + * @default 60000 + */ + maximumDelayMs?: number; +} +export interface ClientOptions { + endPoint: string; + accessKey?: string; + secretKey?: string; + useSSL?: boolean; + port?: number; + region?: Region; + transport?: Transport; + sessionToken?: string; + partSize?: number; + pathStyle?: boolean; + credentialsProvider?: CredentialProvider; + s3AccelerateEndpoint?: string; + transportAgent?: http.Agent; + retryOptions?: RetryOptions; +} +export type RequestOption = Partial & { + method: string; + bucketName?: string; + objectName?: string; + query?: string; + pathStyle?: boolean; +}; +export type NoResultCallback = (error: unknown) => void; +export interface MakeBucketOpt { + ObjectLocking?: boolean; +} +export interface RemoveOptions { + versionId?: string; + governanceBypass?: boolean; + forceDelete?: boolean; +} +export declare class TypedClient { + protected transport: Transport; + protected host: string; + protected port: number; + protected protocol: string; + protected accessKey: string; + protected secretKey: string; + protected sessionToken?: string; + protected userAgent: string; + protected anonymous: boolean; + protected pathStyle: boolean; + protected regionMap: Record; + region?: string; + protected credentialsProvider?: CredentialProvider; + partSize: number; + protected overRidePartSize?: boolean; + protected retryOptions: RetryOptions; + protected maximumPartSize: number; + protected maxObjectSize: number; + enableSHA256: boolean; + protected s3AccelerateEndpoint?: string; + protected reqOptions: Record; + protected transportAgent: http.Agent; + private readonly clientExtensions; + constructor(params: ClientOptions); + /** + * Minio extensions that aren't necessary present for Amazon S3 compatible storage servers + */ + get extensions(): Extensions; + /** + * @param endPoint - valid S3 acceleration end point + */ + setS3TransferAccelerate(endPoint: string): void; + /** + * Sets the supported request options. + */ + setRequestOptions(options: Pick): void; + /** + * This is s3 Specific and does not hold validity in any other Object storage. + */ + private getAccelerateEndPointIfSet; + /** + * Set application specific information. + * Generates User-Agent in the following style. + * MinIO (OS; ARCH) LIB/VER APP/VER + */ + setAppInfo(appName: string, appVersion: string): void; + /** + * returns options object that can be used with http.request() + * Takes care of constructing virtual-host-style or path-style hostname + */ + protected getRequestOptions(opts: RequestOption & { + region: string; + }): IRequest & { + host: string; + headers: Record; + }; + setCredentialsProvider(credentialsProvider: CredentialProvider): Promise; + private checkAndRefreshCreds; + private logStream?; + /** + * log the request, response, error + */ + private logHTTP; + /** + * Enable tracing + */ + traceOn(stream?: stream.Writable): void; + /** + * Disable tracing + */ + traceOff(): void; + /** + * makeRequest is the primitive used by the apis for making S3 requests. + * payload can be empty string in case of no payload. + * statusCode is the expected statusCode. If response.statusCode does not match + * we parse the XML error and call the callback with the error message. + * + * A valid region is passed by the calls - listBuckets, makeBucket and getBucketRegion. + * + * @internal + */ + makeRequestAsync(options: RequestOption, payload?: Binary, expectedCodes?: number[], region?: string): Promise; + /** + * new request with promise + * + * No need to drain response, response body is not valid + */ + makeRequestAsyncOmit(options: RequestOption, payload?: Binary, statusCodes?: number[], region?: string): Promise>; + /** + * makeRequestStream will be used directly instead of makeRequest in case the payload + * is available as a stream. for ex. putObject + * + * @internal + */ + makeRequestStreamAsync(options: RequestOption, body: stream.Readable | Binary, sha256sum: string, statusCodes: number[], region: string): Promise; + /** + * gets the region of the bucket + * + * @param bucketName + * + */ + getBucketRegionAsync(bucketName: string): Promise; + /** + * makeRequest is the primitive used by the apis for making S3 requests. + * payload can be empty string in case of no payload. + * statusCode is the expected statusCode. If response.statusCode does not match + * we parse the XML error and call the callback with the error message. + * A valid region is passed by the calls - listBuckets, makeBucket and + * getBucketRegion. + * + * @deprecated use `makeRequestAsync` instead + */ + makeRequest(options: RequestOption, payload: Binary | undefined, expectedCodes: number[] | undefined, region: string | undefined, returnResponse: boolean, cb: (cb: unknown, result: http.IncomingMessage) => void): void; + /** + * makeRequestStream will be used directly instead of makeRequest in case the payload + * is available as a stream. for ex. putObject + * + * @deprecated use `makeRequestStreamAsync` instead + */ + makeRequestStream(options: RequestOption, stream: stream.Readable | Buffer, sha256sum: string, statusCodes: number[], region: string, returnResponse: boolean, cb: (cb: unknown, result: http.IncomingMessage) => void): void; + /** + * @deprecated use `getBucketRegionAsync` instead + */ + getBucketRegion(bucketName: string, cb: (err: unknown, region: string) => void): Promise; + /** + * Creates the bucket `bucketName`. + * + */ + makeBucket(bucketName: string, region?: Region, makeOpts?: MakeBucketOpt): Promise; + /** + * To check if a bucket already exists. + */ + bucketExists(bucketName: string): Promise; + removeBucket(bucketName: string): Promise; + /** + * @deprecated use promise style API + */ + removeBucket(bucketName: string, callback: NoResultCallback): void; + /** + * Callback is called with readable stream of the object content. + */ + getObject(bucketName: string, objectName: string, getOpts?: GetObjectOpts): Promise; + /** + * Callback is called with readable stream of the partial object content. + * @param bucketName + * @param objectName + * @param offset + * @param length - length of the object that will be read in the stream (optional, if not specified we read the rest of the file from the offset) + * @param getOpts + */ + getPartialObject(bucketName: string, objectName: string, offset: number, length?: number, getOpts?: GetObjectOpts): Promise; + /** + * download object content to a file. + * This method will create a temp file named `${filename}.${base64(etag)}.part.minio` when downloading. + * + * @param bucketName - name of the bucket + * @param objectName - name of the object + * @param filePath - path to which the object data will be written to + * @param getOpts - Optional object get option + */ + fGetObject(bucketName: string, objectName: string, filePath: string, getOpts?: GetObjectOpts): Promise; + /** + * Stat information of the object. + */ + statObject(bucketName: string, objectName: string, statOpts?: StatObjectOpts): Promise; + removeObject(bucketName: string, objectName: string, removeOpts?: RemoveOptions): Promise; + listIncompleteUploads(bucket: string, prefix: string, recursive: boolean): BucketStream; + /** + * Called by listIncompleteUploads to fetch a batch of incomplete uploads. + */ + listIncompleteUploadsQuery(bucketName: string, prefix: string, keyMarker: string, uploadIdMarker: string, delimiter: string): Promise; + /** + * Initiate a new multipart upload. + * @internal + */ + initiateNewMultipartUpload(bucketName: string, objectName: string, headers: RequestHeaders): Promise; + /** + * Internal Method to abort a multipart upload request in case of any errors. + * + * @param bucketName - Bucket Name + * @param objectName - Object Name + * @param uploadId - id of a multipart upload to cancel during compose object sequence. + */ + abortMultipartUpload(bucketName: string, objectName: string, uploadId: string): Promise; + findUploadId(bucketName: string, objectName: string): Promise; + /** + * this call will aggregate the parts on the server into a single object. + */ + completeMultipartUpload(bucketName: string, objectName: string, uploadId: string, etags: { + part: number; + etag?: string; + }[]): Promise<{ + etag: string; + versionId: string | null; + }>; + /** + * Get part-info of all parts of an incomplete upload specified by uploadId. + */ + protected listParts(bucketName: string, objectName: string, uploadId: string): Promise; + /** + * Called by listParts to fetch a batch of part-info + */ + private listPartsQuery; + listBuckets(): Promise; + /** + * Calculate part size given the object size. Part size will be atleast this.partSize + */ + calculatePartSize(size: number): number; + /** + * Uploads the object using contents from a file + */ + fPutObject(bucketName: string, objectName: string, filePath: string, metaData?: ObjectMetaData): Promise; + /** + * Uploading a stream, "Buffer" or "string". + * It's recommended to pass `size` argument with stream. + */ + putObject(bucketName: string, objectName: string, stream: stream.Readable | Buffer | string, size?: number, metaData?: ItemBucketMetadata): Promise; + /** + * method to upload buffer in one call + * @private + */ + private uploadBuffer; + /** + * upload stream with MultipartUpload + * @private + */ + private uploadStream; + removeBucketReplication(bucketName: string): Promise; + removeBucketReplication(bucketName: string, callback: NoResultCallback): void; + setBucketReplication(bucketName: string, replicationConfig: ReplicationConfigOpts): void; + setBucketReplication(bucketName: string, replicationConfig: ReplicationConfigOpts): Promise; + getBucketReplication(bucketName: string): void; + getBucketReplication(bucketName: string): Promise; + getObjectLegalHold(bucketName: string, objectName: string, getOpts?: GetObjectLegalHoldOptions, callback?: ResultCallback): Promise; + setObjectLegalHold(bucketName: string, objectName: string, setOpts?: PutObjectLegalHoldOptions): void; + /** + * Get Tags associated with a Bucket + */ + getBucketTagging(bucketName: string): Promise; + /** + * Get the tags associated with a bucket OR an object + */ + getObjectTagging(bucketName: string, objectName: string, getOpts?: GetObjectOpts): Promise; + /** + * Set the policy on a bucket or an object prefix. + */ + setBucketPolicy(bucketName: string, policy: string): Promise; + /** + * Get the policy on a bucket or an object prefix. + */ + getBucketPolicy(bucketName: string): Promise; + putObjectRetention(bucketName: string, objectName: string, retentionOpts?: Retention): Promise; + getObjectLockConfig(bucketName: string, callback: ResultCallback): void; + getObjectLockConfig(bucketName: string): void; + getObjectLockConfig(bucketName: string): Promise; + setObjectLockConfig(bucketName: string, lockConfigOpts: Omit): void; + setObjectLockConfig(bucketName: string, lockConfigOpts: Omit): Promise; + getBucketVersioning(bucketName: string): Promise; + setBucketVersioning(bucketName: string, versionConfig: BucketVersioningConfiguration): Promise; + private setTagging; + private removeTagging; + setBucketTagging(bucketName: string, tags: Tags): Promise; + removeBucketTagging(bucketName: string): Promise; + setObjectTagging(bucketName: string, objectName: string, tags: Tags, putOpts?: TaggingOpts): Promise; + removeObjectTagging(bucketName: string, objectName: string, removeOpts: TaggingOpts): Promise; + selectObjectContent(bucketName: string, objectName: string, selectOpts: SelectOptions): Promise; + private applyBucketLifecycle; + removeBucketLifecycle(bucketName: string): Promise; + setBucketLifecycle(bucketName: string, lifeCycleConfig: LifeCycleConfigParam): Promise; + getBucketLifecycle(bucketName: string): Promise; + setBucketEncryption(bucketName: string, encryptionConfig?: EncryptionConfig): Promise; + getBucketEncryption(bucketName: string): Promise; + removeBucketEncryption(bucketName: string): Promise; + getObjectRetention(bucketName: string, objectName: string, getOpts?: GetObjectRetentionOpts): Promise; + removeObjects(bucketName: string, objectsList: RemoveObjectsParam): Promise; + removeIncompleteUpload(bucketName: string, objectName: string): Promise; + private copyObjectV1; + private copyObjectV2; + copyObject(source: CopySourceOptions, dest: CopyDestinationOptions): Promise; + copyObject(targetBucketName: string, targetObjectName: string, sourceBucketNameAndObjectName: string, conditions?: CopyConditions): Promise; + uploadPart(partConfig: { + bucketName: string; + objectName: string; + uploadID: string; + partNumber: number; + headers: RequestHeaders; + }, payload?: Binary): Promise<{ + etag: string; + key: string; + part: number; + }>; + composeObject(destObjConfig: CopyDestinationOptions, sourceObjList: CopySourceOptions[], { + maxConcurrency + }?: { + maxConcurrency?: number | undefined; + }): Promise | CopyObjectResult>; + presignedUrl(method: string, bucketName: string, objectName: string, expires?: number | PreSignRequestParams | undefined, reqParams?: PreSignRequestParams | Date, requestDate?: Date): Promise; + presignedGetObject(bucketName: string, objectName: string, expires?: number, respHeaders?: PreSignRequestParams | Date, requestDate?: Date): Promise; + presignedPutObject(bucketName: string, objectName: string, expires?: number): Promise; + newPostPolicy(): PostPolicy; + presignedPostPolicy(postPolicy: PostPolicy): Promise; + listObjectsQuery(bucketName: string, prefix?: string, marker?: string, listQueryOpts?: ListObjectQueryOpts): Promise<{ + objects: ObjectInfo[]; + isTruncated?: boolean | undefined; + nextMarker?: string | undefined; + versionIdMarker?: string | undefined; + keyMarker?: string | undefined; + }>; + listObjects(bucketName: string, prefix?: string, recursive?: boolean, listOpts?: ListObjectQueryOpts | undefined): BucketStream; + listObjectsV2Query(bucketName: string, prefix: string, continuationToken: string, delimiter: string, maxKeys: number, startAfter: string): Promise; + listObjectsV2(bucketName: string, prefix?: string, recursive?: boolean, startAfter?: string): BucketStream; + setBucketNotification(bucketName: string, config: NotificationConfig): Promise; + removeAllBucketNotification(bucketName: string): Promise; + getBucketNotification(bucketName: string): Promise; + listenBucketNotification(bucketName: string, prefix: string, suffix: string, events: NotificationEvent[]): NotificationPoller; +} +export {}; \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/client.js b/node_modules/minio/dist/main/internal/client.js new file mode 100644 index 0000000..5ab16ff --- /dev/null +++ b/node_modules/minio/dist/main/internal/client.js @@ -0,0 +1,3013 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var crypto = _interopRequireWildcard(require("crypto"), true); +var fs = _interopRequireWildcard(require("fs"), true); +var http = _interopRequireWildcard(require("http"), true); +var https = _interopRequireWildcard(require("https"), true); +var path = _interopRequireWildcard(require("path"), true); +var stream = _interopRequireWildcard(require("stream"), true); +var async = _interopRequireWildcard(require("async"), true); +var _blockStream = require("block-stream2"); +var _browserOrNode = require("browser-or-node"); +var _lodash = require("lodash"); +var qs = _interopRequireWildcard(require("query-string"), true); +var _xml2js = require("xml2js"); +var _CredentialProvider = require("../CredentialProvider.js"); +var errors = _interopRequireWildcard(require("../errors.js"), true); +var _helpers = require("../helpers.js"); +var _notification = require("../notification.js"); +var _signing = require("../signing.js"); +var _async2 = require("./async.js"); +var _copyConditions = require("./copy-conditions.js"); +var _extensions = require("./extensions.js"); +var _helper = require("./helper.js"); +var _joinHostPort = require("./join-host-port.js"); +var _postPolicy = require("./post-policy.js"); +var _request = require("./request.js"); +var _response = require("./response.js"); +var _s3Endpoints = require("./s3-endpoints.js"); +var xmlParsers = _interopRequireWildcard(require("./xml-parser.js"), true); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +const xml = new _xml2js.Builder({ + renderOpts: { + pretty: false + }, + headless: true +}); + +// will be replaced by bundler. +const Package = { + version: "8.0.7" || 'development' +}; +const requestOptionProperties = ['agent', 'ca', 'cert', 'ciphers', 'clientCertEngine', 'crl', 'dhparam', 'ecdhCurve', 'family', 'honorCipherOrder', 'key', 'passphrase', 'pfx', 'rejectUnauthorized', 'secureOptions', 'secureProtocol', 'servername', 'sessionIdContext']; +class TypedClient { + partSize = 64 * 1024 * 1024; + maximumPartSize = 5 * 1024 * 1024 * 1024; + maxObjectSize = 5 * 1024 * 1024 * 1024 * 1024; + constructor(params) { + // @ts-expect-error deprecated property + if (params.secure !== undefined) { + throw new Error('"secure" option deprecated, "useSSL" should be used instead'); + } + // Default values if not specified. + if (params.useSSL === undefined) { + params.useSSL = true; + } + if (!params.port) { + params.port = 0; + } + // Validate input params. + if (!(0, _helper.isValidEndpoint)(params.endPoint)) { + throw new errors.InvalidEndpointError(`Invalid endPoint : ${params.endPoint}`); + } + if (!(0, _helper.isValidPort)(params.port)) { + throw new errors.InvalidArgumentError(`Invalid port : ${params.port}`); + } + if (!(0, _helper.isBoolean)(params.useSSL)) { + throw new errors.InvalidArgumentError(`Invalid useSSL flag type : ${params.useSSL}, expected to be of type "boolean"`); + } + + // Validate region only if its set. + if (params.region) { + if (!(0, _helper.isString)(params.region)) { + throw new errors.InvalidArgumentError(`Invalid region : ${params.region}`); + } + } + const host = params.endPoint.toLowerCase(); + let port = params.port; + let protocol; + let transport; + let transportAgent; + // Validate if configuration is not using SSL + // for constructing relevant endpoints. + if (params.useSSL) { + // Defaults to secure. + transport = https; + protocol = 'https:'; + port = port || 443; + transportAgent = https.globalAgent; + } else { + transport = http; + protocol = 'http:'; + port = port || 80; + transportAgent = http.globalAgent; + } + + // if custom transport is set, use it. + if (params.transport) { + if (!(0, _helper.isObject)(params.transport)) { + throw new errors.InvalidArgumentError(`Invalid transport type : ${params.transport}, expected to be type "object"`); + } + transport = params.transport; + } + + // if custom transport agent is set, use it. + if (params.transportAgent) { + if (!(0, _helper.isObject)(params.transportAgent)) { + throw new errors.InvalidArgumentError(`Invalid transportAgent type: ${params.transportAgent}, expected to be type "object"`); + } + transportAgent = params.transportAgent; + } + + // User Agent should always following the below style. + // Please open an issue to discuss any new changes here. + // + // MinIO (OS; ARCH) LIB/VER APP/VER + // + const libraryComments = `(${process.platform}; ${process.arch})`; + const libraryAgent = `MinIO ${libraryComments} minio-js/${Package.version}`; + // User agent block ends. + + this.transport = transport; + this.transportAgent = transportAgent; + this.host = host; + this.port = port; + this.protocol = protocol; + this.userAgent = `${libraryAgent}`; + + // Default path style is true + if (params.pathStyle === undefined) { + this.pathStyle = true; + } else { + this.pathStyle = params.pathStyle; + } + this.accessKey = params.accessKey ?? ''; + this.secretKey = params.secretKey ?? ''; + this.sessionToken = params.sessionToken; + this.anonymous = !this.accessKey || !this.secretKey; + if (params.credentialsProvider) { + this.anonymous = false; + this.credentialsProvider = params.credentialsProvider; + } + this.regionMap = {}; + if (params.region) { + this.region = params.region; + } + if (params.partSize) { + this.partSize = params.partSize; + this.overRidePartSize = true; + } + if (this.partSize < 5 * 1024 * 1024) { + throw new errors.InvalidArgumentError(`Part size should be greater than 5MB`); + } + if (this.partSize > 5 * 1024 * 1024 * 1024) { + throw new errors.InvalidArgumentError(`Part size should be less than 5GB`); + } + + // SHA256 is enabled only for authenticated http requests. If the request is authenticated + // and the connection is https we use x-amz-content-sha256=UNSIGNED-PAYLOAD + // header for signature calculation. + this.enableSHA256 = !this.anonymous && !params.useSSL; + this.s3AccelerateEndpoint = params.s3AccelerateEndpoint || undefined; + this.reqOptions = {}; + this.clientExtensions = new _extensions.Extensions(this); + if (params.retryOptions) { + if (!(0, _helper.isObject)(params.retryOptions)) { + throw new errors.InvalidArgumentError(`Invalid retryOptions type: ${params.retryOptions}, expected to be type "object"`); + } + this.retryOptions = params.retryOptions; + } else { + this.retryOptions = { + disableRetry: false + }; + } + } + /** + * Minio extensions that aren't necessary present for Amazon S3 compatible storage servers + */ + get extensions() { + return this.clientExtensions; + } + + /** + * @param endPoint - valid S3 acceleration end point + */ + setS3TransferAccelerate(endPoint) { + this.s3AccelerateEndpoint = endPoint; + } + + /** + * Sets the supported request options. + */ + setRequestOptions(options) { + if (!(0, _helper.isObject)(options)) { + throw new TypeError('request options should be of type "object"'); + } + this.reqOptions = _lodash.pick(options, requestOptionProperties); + } + + /** + * This is s3 Specific and does not hold validity in any other Object storage. + */ + getAccelerateEndPointIfSet(bucketName, objectName) { + if (!(0, _helper.isEmpty)(this.s3AccelerateEndpoint) && !(0, _helper.isEmpty)(bucketName) && !(0, _helper.isEmpty)(objectName)) { + // http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html + // Disable transfer acceleration for non-compliant bucket names. + if (bucketName.includes('.')) { + throw new Error(`Transfer Acceleration is not supported for non compliant bucket:${bucketName}`); + } + // If transfer acceleration is requested set new host. + // For more details about enabling transfer acceleration read here. + // http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html + return this.s3AccelerateEndpoint; + } + return false; + } + + /** + * Set application specific information. + * Generates User-Agent in the following style. + * MinIO (OS; ARCH) LIB/VER APP/VER + */ + setAppInfo(appName, appVersion) { + if (!(0, _helper.isString)(appName)) { + throw new TypeError(`Invalid appName: ${appName}`); + } + if (appName.trim() === '') { + throw new errors.InvalidArgumentError('Input appName cannot be empty.'); + } + if (!(0, _helper.isString)(appVersion)) { + throw new TypeError(`Invalid appVersion: ${appVersion}`); + } + if (appVersion.trim() === '') { + throw new errors.InvalidArgumentError('Input appVersion cannot be empty.'); + } + this.userAgent = `${this.userAgent} ${appName}/${appVersion}`; + } + + /** + * returns options object that can be used with http.request() + * Takes care of constructing virtual-host-style or path-style hostname + */ + getRequestOptions(opts) { + const method = opts.method; + const region = opts.region; + const bucketName = opts.bucketName; + let objectName = opts.objectName; + const headers = opts.headers; + const query = opts.query; + let reqOptions = { + method, + headers: {}, + protocol: this.protocol, + // If custom transportAgent was supplied earlier, we'll inject it here + agent: this.transportAgent + }; + + // Verify if virtual host supported. + let virtualHostStyle; + if (bucketName) { + virtualHostStyle = (0, _helper.isVirtualHostStyle)(this.host, this.protocol, bucketName, this.pathStyle); + } + let path = '/'; + let host = this.host; + let port; + if (this.port) { + port = this.port; + } + if (objectName) { + objectName = (0, _helper.uriResourceEscape)(objectName); + } + + // For Amazon S3 endpoint, get endpoint based on region. + if ((0, _helper.isAmazonEndpoint)(host)) { + const accelerateEndPoint = this.getAccelerateEndPointIfSet(bucketName, objectName); + if (accelerateEndPoint) { + host = `${accelerateEndPoint}`; + } else { + host = (0, _s3Endpoints.getS3Endpoint)(region); + } + } + if (virtualHostStyle && !opts.pathStyle) { + // For all hosts which support virtual host style, `bucketName` + // is part of the hostname in the following format: + // + // var host = 'bucketName.example.com' + // + if (bucketName) { + host = `${bucketName}.${host}`; + } + if (objectName) { + path = `/${objectName}`; + } + } else { + // For all S3 compatible storage services we will fallback to + // path style requests, where `bucketName` is part of the URI + // path. + if (bucketName) { + path = `/${bucketName}`; + } + if (objectName) { + path = `/${bucketName}/${objectName}`; + } + } + if (query) { + path += `?${query}`; + } + reqOptions.headers.host = host; + if (reqOptions.protocol === 'http:' && port !== 80 || reqOptions.protocol === 'https:' && port !== 443) { + reqOptions.headers.host = (0, _joinHostPort.joinHostPort)(host, port); + } + reqOptions.headers['user-agent'] = this.userAgent; + if (headers) { + // have all header keys in lower case - to make signing easy + for (const [k, v] of Object.entries(headers)) { + reqOptions.headers[k.toLowerCase()] = v; + } + } + + // Use any request option specified in minioClient.setRequestOptions() + reqOptions = Object.assign({}, this.reqOptions, reqOptions); + return { + ...reqOptions, + headers: _lodash.mapValues(_lodash.pickBy(reqOptions.headers, _helper.isDefined), v => v.toString()), + host, + port, + path + }; + } + async setCredentialsProvider(credentialsProvider) { + if (!(credentialsProvider instanceof _CredentialProvider.CredentialProvider)) { + throw new Error('Unable to get credentials. Expected instance of CredentialProvider'); + } + this.credentialsProvider = credentialsProvider; + await this.checkAndRefreshCreds(); + } + async checkAndRefreshCreds() { + if (this.credentialsProvider) { + try { + const credentialsConf = await this.credentialsProvider.getCredentials(); + this.accessKey = credentialsConf.getAccessKey(); + this.secretKey = credentialsConf.getSecretKey(); + this.sessionToken = credentialsConf.getSessionToken(); + } catch (e) { + throw new Error(`Unable to get credentials: ${e}`, { + cause: e + }); + } + } + } + /** + * log the request, response, error + */ + logHTTP(reqOptions, response, err) { + // if no logStream available return. + if (!this.logStream) { + return; + } + if (!(0, _helper.isObject)(reqOptions)) { + throw new TypeError('reqOptions should be of type "object"'); + } + if (response && !(0, _helper.isReadableStream)(response)) { + throw new TypeError('response should be of type "Stream"'); + } + if (err && !(err instanceof Error)) { + throw new TypeError('err should be of type "Error"'); + } + const logStream = this.logStream; + const logHeaders = headers => { + Object.entries(headers).forEach(([k, v]) => { + if (k == 'authorization') { + if ((0, _helper.isString)(v)) { + const redactor = new RegExp('Signature=([0-9a-f]+)'); + v = v.replace(redactor, 'Signature=**REDACTED**'); + } + } + logStream.write(`${k}: ${v}\n`); + }); + logStream.write('\n'); + }; + logStream.write(`REQUEST: ${reqOptions.method} ${reqOptions.path}\n`); + logHeaders(reqOptions.headers); + if (response) { + this.logStream.write(`RESPONSE: ${response.statusCode}\n`); + logHeaders(response.headers); + } + if (err) { + logStream.write('ERROR BODY:\n'); + const errJSON = JSON.stringify(err, null, '\t'); + logStream.write(`${errJSON}\n`); + } + } + + /** + * Enable tracing + */ + traceOn(stream) { + if (!stream) { + stream = process.stdout; + } + this.logStream = stream; + } + + /** + * Disable tracing + */ + traceOff() { + this.logStream = undefined; + } + + /** + * makeRequest is the primitive used by the apis for making S3 requests. + * payload can be empty string in case of no payload. + * statusCode is the expected statusCode. If response.statusCode does not match + * we parse the XML error and call the callback with the error message. + * + * A valid region is passed by the calls - listBuckets, makeBucket and getBucketRegion. + * + * @internal + */ + async makeRequestAsync(options, payload = '', expectedCodes = [200], region = '') { + if (!(0, _helper.isObject)(options)) { + throw new TypeError('options should be of type "object"'); + } + if (!(0, _helper.isString)(payload) && !(0, _helper.isObject)(payload)) { + // Buffer is of type 'object' + throw new TypeError('payload should be of type "string" or "Buffer"'); + } + expectedCodes.forEach(statusCode => { + if (!(0, _helper.isNumber)(statusCode)) { + throw new TypeError('statusCode should be of type "number"'); + } + }); + if (!(0, _helper.isString)(region)) { + throw new TypeError('region should be of type "string"'); + } + if (!options.headers) { + options.headers = {}; + } + if (options.method === 'POST' || options.method === 'PUT' || options.method === 'DELETE') { + options.headers['content-length'] = payload.length.toString(); + } + const sha256sum = this.enableSHA256 ? (0, _helper.toSha256)(payload) : ''; + return this.makeRequestStreamAsync(options, payload, sha256sum, expectedCodes, region); + } + + /** + * new request with promise + * + * No need to drain response, response body is not valid + */ + async makeRequestAsyncOmit(options, payload = '', statusCodes = [200], region = '') { + const res = await this.makeRequestAsync(options, payload, statusCodes, region); + await (0, _response.drainResponse)(res); + return res; + } + + /** + * makeRequestStream will be used directly instead of makeRequest in case the payload + * is available as a stream. for ex. putObject + * + * @internal + */ + async makeRequestStreamAsync(options, body, sha256sum, statusCodes, region) { + if (!(0, _helper.isObject)(options)) { + throw new TypeError('options should be of type "object"'); + } + if (!(Buffer.isBuffer(body) || typeof body === 'string' || (0, _helper.isReadableStream)(body))) { + throw new errors.InvalidArgumentError(`stream should be a Buffer, string or readable Stream, got ${typeof body} instead`); + } + if (!(0, _helper.isString)(sha256sum)) { + throw new TypeError('sha256sum should be of type "string"'); + } + statusCodes.forEach(statusCode => { + if (!(0, _helper.isNumber)(statusCode)) { + throw new TypeError('statusCode should be of type "number"'); + } + }); + if (!(0, _helper.isString)(region)) { + throw new TypeError('region should be of type "string"'); + } + // sha256sum will be empty for anonymous or https requests + if (!this.enableSHA256 && sha256sum.length !== 0) { + throw new errors.InvalidArgumentError(`sha256sum expected to be empty for anonymous or https requests`); + } + // sha256sum should be valid for non-anonymous http requests. + if (this.enableSHA256 && sha256sum.length !== 64) { + throw new errors.InvalidArgumentError(`Invalid sha256sum : ${sha256sum}`); + } + await this.checkAndRefreshCreds(); + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + region = region || (await this.getBucketRegionAsync(options.bucketName)); + const reqOptions = this.getRequestOptions({ + ...options, + region + }); + if (!this.anonymous) { + // For non-anonymous https requests sha256sum is 'UNSIGNED-PAYLOAD' for signature calculation. + if (!this.enableSHA256) { + sha256sum = 'UNSIGNED-PAYLOAD'; + } + const date = new Date(); + reqOptions.headers['x-amz-date'] = (0, _helper.makeDateLong)(date); + reqOptions.headers['x-amz-content-sha256'] = sha256sum; + if (this.sessionToken) { + reqOptions.headers['x-amz-security-token'] = this.sessionToken; + } + reqOptions.headers.authorization = (0, _signing.signV4)(reqOptions, this.accessKey, this.secretKey, region, date, sha256sum); + } + const response = await (0, _request.requestWithRetry)(this.transport, reqOptions, body, this.retryOptions.disableRetry === true ? 0 : this.retryOptions.maximumRetryCount, this.retryOptions.baseDelayMs, this.retryOptions.maximumDelayMs); + if (!response.statusCode) { + throw new Error("BUG: response doesn't have a statusCode"); + } + if (!statusCodes.includes(response.statusCode)) { + // For an incorrect region, S3 server always sends back 400. + // But we will do cache invalidation for all errors so that, + // in future, if AWS S3 decides to send a different status code or + // XML error code we will still work fine. + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + delete this.regionMap[options.bucketName]; + const err = await xmlParsers.parseResponseError(response); + this.logHTTP(reqOptions, response, err); + throw err; + } + this.logHTTP(reqOptions, response); + return response; + } + + /** + * gets the region of the bucket + * + * @param bucketName + * + */ + async getBucketRegionAsync(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name : ${bucketName}`); + } + + // Region is set with constructor, return the region right here. + if (this.region) { + return this.region; + } + const cached = this.regionMap[bucketName]; + if (cached) { + return cached; + } + const extractRegionAsync = async response => { + const body = await (0, _response.readAsString)(response); + const region = xmlParsers.parseBucketRegion(body) || _helpers.DEFAULT_REGION; + this.regionMap[bucketName] = region; + return region; + }; + const method = 'GET'; + const query = 'location'; + // `getBucketLocation` behaves differently in following ways for + // different environments. + // + // - For nodejs env we default to path style requests. + // - For browser env path style requests on buckets yields CORS + // error. To circumvent this problem we make a virtual host + // style request signed with 'us-east-1'. This request fails + // with an error 'AuthorizationHeaderMalformed', additionally + // the error XML also provides Region of the bucket. To validate + // this region is proper we retry the same request with the newly + // obtained region. + const pathStyle = this.pathStyle && !_browserOrNode.isBrowser; + let region; + try { + const res = await this.makeRequestAsync({ + method, + bucketName, + query, + pathStyle + }, '', [200], _helpers.DEFAULT_REGION); + return extractRegionAsync(res); + } catch (e) { + // make alignment with mc cli + if (e instanceof errors.S3Error) { + const errCode = e.code; + const errRegion = e.region; + if (errCode === 'AccessDenied' && !errRegion) { + return _helpers.DEFAULT_REGION; + } + } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + if (!(e.name === 'AuthorizationHeaderMalformed')) { + throw e; + } + // @ts-expect-error we set extra properties on error object + region = e.Region; + if (!region) { + throw e; + } + } + const res = await this.makeRequestAsync({ + method, + bucketName, + query, + pathStyle + }, '', [200], region); + return await extractRegionAsync(res); + } + + /** + * makeRequest is the primitive used by the apis for making S3 requests. + * payload can be empty string in case of no payload. + * statusCode is the expected statusCode. If response.statusCode does not match + * we parse the XML error and call the callback with the error message. + * A valid region is passed by the calls - listBuckets, makeBucket and + * getBucketRegion. + * + * @deprecated use `makeRequestAsync` instead + */ + makeRequest(options, payload = '', expectedCodes = [200], region = '', returnResponse, cb) { + let prom; + if (returnResponse) { + prom = this.makeRequestAsync(options, payload, expectedCodes, region); + } else { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error compatible for old behaviour + prom = this.makeRequestAsyncOmit(options, payload, expectedCodes, region); + } + prom.then(result => cb(null, result), err => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + cb(err); + }); + } + + /** + * makeRequestStream will be used directly instead of makeRequest in case the payload + * is available as a stream. for ex. putObject + * + * @deprecated use `makeRequestStreamAsync` instead + */ + makeRequestStream(options, stream, sha256sum, statusCodes, region, returnResponse, cb) { + const executor = async () => { + const res = await this.makeRequestStreamAsync(options, stream, sha256sum, statusCodes, region); + if (!returnResponse) { + await (0, _response.drainResponse)(res); + } + return res; + }; + executor().then(result => cb(null, result), + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + err => cb(err)); + } + + /** + * @deprecated use `getBucketRegionAsync` instead + */ + getBucketRegion(bucketName, cb) { + return this.getBucketRegionAsync(bucketName).then(result => cb(null, result), + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + err => cb(err)); + } + + // Bucket operations + + /** + * Creates the bucket `bucketName`. + * + */ + async makeBucket(bucketName, region = '', makeOpts) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + // Backward Compatibility + if ((0, _helper.isObject)(region)) { + makeOpts = region; + region = ''; + } + if (!(0, _helper.isString)(region)) { + throw new TypeError('region should be of type "string"'); + } + if (makeOpts && !(0, _helper.isObject)(makeOpts)) { + throw new TypeError('makeOpts should be of type "object"'); + } + let payload = ''; + + // Region already set in constructor, validate if + // caller requested bucket location is same. + if (region && this.region) { + if (region !== this.region) { + throw new errors.InvalidArgumentError(`Configured region ${this.region}, requested ${region}`); + } + } + // sending makeBucket request with XML containing 'us-east-1' fails. For + // default region server expects the request without body + if (region && region !== _helpers.DEFAULT_REGION) { + payload = xml.buildObject({ + CreateBucketConfiguration: { + $: { + xmlns: 'http://s3.amazonaws.com/doc/2006-03-01/' + }, + LocationConstraint: region + } + }); + } + const method = 'PUT'; + const headers = {}; + if (makeOpts && makeOpts.ObjectLocking) { + headers['x-amz-bucket-object-lock-enabled'] = true; + } + + // For custom region clients default to custom region specified in client constructor + const finalRegion = this.region || region || _helpers.DEFAULT_REGION; + const requestOpt = { + method, + bucketName, + headers + }; + try { + await this.makeRequestAsyncOmit(requestOpt, payload, [200], finalRegion); + } catch (err) { + if (region === '' || region === _helpers.DEFAULT_REGION) { + if (err instanceof errors.S3Error) { + const errCode = err.code; + const errRegion = err.region; + if (errCode === 'AuthorizationHeaderMalformed' && errRegion !== '') { + // Retry with region returned as part of error + await this.makeRequestAsyncOmit(requestOpt, payload, [200], errCode); + } + } + } + throw err; + } + } + + /** + * To check if a bucket already exists. + */ + async bucketExists(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'HEAD'; + try { + await this.makeRequestAsyncOmit({ + method, + bucketName + }); + } catch (err) { + // @ts-ignore + if (err.code === 'NoSuchBucket' || err.code === 'NotFound') { + return false; + } + throw err; + } + return true; + } + + /** + * @deprecated use promise style API + */ + + async removeBucket(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'DELETE'; + await this.makeRequestAsyncOmit({ + method, + bucketName + }, '', [204]); + delete this.regionMap[bucketName]; + } + + /** + * Callback is called with readable stream of the object content. + */ + async getObject(bucketName, objectName, getOpts) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + return this.getPartialObject(bucketName, objectName, 0, 0, getOpts); + } + + /** + * Callback is called with readable stream of the partial object content. + * @param bucketName + * @param objectName + * @param offset + * @param length - length of the object that will be read in the stream (optional, if not specified we read the rest of the file from the offset) + * @param getOpts + */ + async getPartialObject(bucketName, objectName, offset, length = 0, getOpts) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!(0, _helper.isNumber)(offset)) { + throw new TypeError('offset should be of type "number"'); + } + if (!(0, _helper.isNumber)(length)) { + throw new TypeError('length should be of type "number"'); + } + let range = ''; + if (offset || length) { + if (offset) { + range = `bytes=${+offset}-`; + } else { + range = 'bytes=0-'; + offset = 0; + } + if (length) { + range += `${+length + offset - 1}`; + } + } + let query = ''; + let headers = { + ...(range !== '' && { + range + }) + }; + if (getOpts) { + const sseHeaders = { + ...(getOpts.SSECustomerAlgorithm && { + 'X-Amz-Server-Side-Encryption-Customer-Algorithm': getOpts.SSECustomerAlgorithm + }), + ...(getOpts.SSECustomerKey && { + 'X-Amz-Server-Side-Encryption-Customer-Key': getOpts.SSECustomerKey + }), + ...(getOpts.SSECustomerKeyMD5 && { + 'X-Amz-Server-Side-Encryption-Customer-Key-MD5': getOpts.SSECustomerKeyMD5 + }) + }; + query = qs.stringify(getOpts); + headers = { + ...(0, _helper.prependXAMZMeta)(sseHeaders), + ...headers + }; + } + const expectedStatusCodes = [200]; + if (range) { + expectedStatusCodes.push(206); + } + const method = 'GET'; + return await this.makeRequestAsync({ + method, + bucketName, + objectName, + headers, + query + }, '', expectedStatusCodes); + } + + /** + * download object content to a file. + * This method will create a temp file named `${filename}.${base64(etag)}.part.minio` when downloading. + * + * @param bucketName - name of the bucket + * @param objectName - name of the object + * @param filePath - path to which the object data will be written to + * @param getOpts - Optional object get option + */ + async fGetObject(bucketName, objectName, filePath, getOpts) { + // Input validation. + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!(0, _helper.isString)(filePath)) { + throw new TypeError('filePath should be of type "string"'); + } + const downloadToTmpFile = async () => { + let partFileStream; + const objStat = await this.statObject(bucketName, objectName, getOpts); + const encodedEtag = Buffer.from(objStat.etag).toString('base64'); + const partFile = `${filePath}.${encodedEtag}.part.minio`; + await _async2.fsp.mkdir(path.dirname(filePath), { + recursive: true + }); + let offset = 0; + try { + const stats = await _async2.fsp.stat(partFile); + if (objStat.size === stats.size) { + return partFile; + } + offset = stats.size; + partFileStream = fs.createWriteStream(partFile, { + flags: 'a' + }); + } catch (e) { + if (e instanceof Error && e.code === 'ENOENT') { + // file not exist + partFileStream = fs.createWriteStream(partFile, { + flags: 'w' + }); + } else { + // other error, maybe access deny + throw e; + } + } + const downloadStream = await this.getPartialObject(bucketName, objectName, offset, 0, getOpts); + await _async2.streamPromise.pipeline(downloadStream, partFileStream); + const stats = await _async2.fsp.stat(partFile); + if (stats.size === objStat.size) { + return partFile; + } + throw new Error('Size mismatch between downloaded file and the object'); + }; + const partFile = await downloadToTmpFile(); + await _async2.fsp.rename(partFile, filePath); + } + + /** + * Stat information of the object. + */ + async statObject(bucketName, objectName, statOpts) { + const statOptDef = statOpts || {}; + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!(0, _helper.isObject)(statOptDef)) { + throw new errors.InvalidArgumentError('statOpts should be of type "object"'); + } + const query = qs.stringify(statOptDef); + const method = 'HEAD'; + const res = await this.makeRequestAsyncOmit({ + method, + bucketName, + objectName, + query + }); + return { + size: parseInt(res.headers['content-length']), + metaData: (0, _helper.extractMetadata)(res.headers), + lastModified: new Date(res.headers['last-modified']), + versionId: (0, _helper.getVersionId)(res.headers), + etag: (0, _helper.sanitizeETag)(res.headers.etag) + }; + } + async removeObject(bucketName, objectName, removeOpts) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (removeOpts && !(0, _helper.isObject)(removeOpts)) { + throw new errors.InvalidArgumentError('removeOpts should be of type "object"'); + } + const method = 'DELETE'; + const headers = {}; + if (removeOpts !== null && removeOpts !== void 0 && removeOpts.governanceBypass) { + headers['X-Amz-Bypass-Governance-Retention'] = true; + } + if (removeOpts !== null && removeOpts !== void 0 && removeOpts.forceDelete) { + headers['x-minio-force-delete'] = true; + } + const queryParams = {}; + if (removeOpts !== null && removeOpts !== void 0 && removeOpts.versionId) { + queryParams.versionId = `${removeOpts.versionId}`; + } + const query = qs.stringify(queryParams); + await this.makeRequestAsyncOmit({ + method, + bucketName, + objectName, + headers, + query + }, '', [200, 204]); + } + + // Calls implemented below are related to multipart. + + listIncompleteUploads(bucket, prefix, recursive) { + if (prefix === undefined) { + prefix = ''; + } + if (recursive === undefined) { + recursive = false; + } + if (!(0, _helper.isValidBucketName)(bucket)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucket); + } + if (!(0, _helper.isValidPrefix)(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`); + } + if (!(0, _helper.isBoolean)(recursive)) { + throw new TypeError('recursive should be of type "boolean"'); + } + const delimiter = recursive ? '' : '/'; + let keyMarker = ''; + let uploadIdMarker = ''; + const uploads = []; + let ended = false; + + // TODO: refactor this with async/await and `stream.Readable.from` + const readStream = new stream.Readable({ + objectMode: true + }); + readStream._read = () => { + // push one upload info per _read() + if (uploads.length) { + return readStream.push(uploads.shift()); + } + if (ended) { + return readStream.push(null); + } + this.listIncompleteUploadsQuery(bucket, prefix, keyMarker, uploadIdMarker, delimiter).then(result => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + result.prefixes.forEach(prefix => uploads.push(prefix)); + async.eachSeries(result.uploads, (upload, cb) => { + // for each incomplete upload add the sizes of its uploaded parts + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + this.listParts(bucket, upload.key, upload.uploadId).then(parts => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + upload.size = parts.reduce((acc, item) => acc + item.size, 0); + uploads.push(upload); + cb(); + }, err => cb(err)); + }, err => { + if (err) { + readStream.emit('error', err); + return; + } + if (result.isTruncated) { + keyMarker = result.nextKeyMarker; + uploadIdMarker = result.nextUploadIdMarker; + } else { + ended = true; + } + + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + readStream._read(); + }); + }, e => { + readStream.emit('error', e); + }); + }; + return readStream; + } + + /** + * Called by listIncompleteUploads to fetch a batch of incomplete uploads. + */ + async listIncompleteUploadsQuery(bucketName, prefix, keyMarker, uploadIdMarker, delimiter) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isString)(prefix)) { + throw new TypeError('prefix should be of type "string"'); + } + if (!(0, _helper.isString)(keyMarker)) { + throw new TypeError('keyMarker should be of type "string"'); + } + if (!(0, _helper.isString)(uploadIdMarker)) { + throw new TypeError('uploadIdMarker should be of type "string"'); + } + if (!(0, _helper.isString)(delimiter)) { + throw new TypeError('delimiter should be of type "string"'); + } + const queries = []; + queries.push(`prefix=${(0, _helper.uriEscape)(prefix)}`); + queries.push(`delimiter=${(0, _helper.uriEscape)(delimiter)}`); + if (keyMarker) { + queries.push(`key-marker=${(0, _helper.uriEscape)(keyMarker)}`); + } + if (uploadIdMarker) { + queries.push(`upload-id-marker=${uploadIdMarker}`); + } + const maxUploads = 1000; + queries.push(`max-uploads=${maxUploads}`); + queries.sort(); + queries.unshift('uploads'); + let query = ''; + if (queries.length > 0) { + query = `${queries.join('&')}`; + } + const method = 'GET'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const body = await (0, _response.readAsString)(res); + return xmlParsers.parseListMultipart(body); + } + + /** + * Initiate a new multipart upload. + * @internal + */ + async initiateNewMultipartUpload(bucketName, objectName, headers) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!(0, _helper.isObject)(headers)) { + throw new errors.InvalidObjectNameError('contentType should be of type "object"'); + } + const method = 'POST'; + const query = 'uploads'; + const res = await this.makeRequestAsync({ + method, + bucketName, + objectName, + query, + headers + }); + const body = await (0, _response.readAsBuffer)(res); + return (0, xmlParsers.parseInitiateMultipart)(body.toString()); + } + + /** + * Internal Method to abort a multipart upload request in case of any errors. + * + * @param bucketName - Bucket Name + * @param objectName - Object Name + * @param uploadId - id of a multipart upload to cancel during compose object sequence. + */ + async abortMultipartUpload(bucketName, objectName, uploadId) { + const method = 'DELETE'; + const query = `uploadId=${uploadId}`; + const requestOptions = { + method, + bucketName, + objectName: objectName, + query + }; + await this.makeRequestAsyncOmit(requestOptions, '', [204]); + } + async findUploadId(bucketName, objectName) { + var _latestUpload; + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + let latestUpload; + let keyMarker = ''; + let uploadIdMarker = ''; + for (;;) { + const result = await this.listIncompleteUploadsQuery(bucketName, objectName, keyMarker, uploadIdMarker, ''); + for (const upload of result.uploads) { + if (upload.key === objectName) { + if (!latestUpload || upload.initiated.getTime() > latestUpload.initiated.getTime()) { + latestUpload = upload; + } + } + } + if (result.isTruncated) { + keyMarker = result.nextKeyMarker; + uploadIdMarker = result.nextUploadIdMarker; + continue; + } + break; + } + return (_latestUpload = latestUpload) === null || _latestUpload === void 0 ? void 0 : _latestUpload.uploadId; + } + + /** + * this call will aggregate the parts on the server into a single object. + */ + async completeMultipartUpload(bucketName, objectName, uploadId, etags) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!(0, _helper.isString)(uploadId)) { + throw new TypeError('uploadId should be of type "string"'); + } + if (!(0, _helper.isObject)(etags)) { + throw new TypeError('etags should be of type "Array"'); + } + if (!uploadId) { + throw new errors.InvalidArgumentError('uploadId cannot be empty'); + } + const method = 'POST'; + const query = `uploadId=${(0, _helper.uriEscape)(uploadId)}`; + const builder = new _xml2js.Builder(); + const payload = builder.buildObject({ + CompleteMultipartUpload: { + $: { + xmlns: 'http://s3.amazonaws.com/doc/2006-03-01/' + }, + Part: etags.map(etag => { + return { + PartNumber: etag.part, + ETag: etag.etag + }; + }) + } + }); + const res = await this.makeRequestAsync({ + method, + bucketName, + objectName, + query + }, payload); + const body = await (0, _response.readAsBuffer)(res); + const result = (0, xmlParsers.parseCompleteMultipart)(body.toString()); + if (!result) { + throw new Error('BUG: failed to parse server response'); + } + if (result.errCode) { + // Multipart Complete API returns an error XML after a 200 http status + throw new errors.S3Error(result.errMessage); + } + return { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + etag: result.etag, + versionId: (0, _helper.getVersionId)(res.headers) + }; + } + + /** + * Get part-info of all parts of an incomplete upload specified by uploadId. + */ + async listParts(bucketName, objectName, uploadId) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!(0, _helper.isString)(uploadId)) { + throw new TypeError('uploadId should be of type "string"'); + } + if (!uploadId) { + throw new errors.InvalidArgumentError('uploadId cannot be empty'); + } + const parts = []; + let marker = 0; + let result; + do { + result = await this.listPartsQuery(bucketName, objectName, uploadId, marker); + marker = result.marker; + parts.push(...result.parts); + } while (result.isTruncated); + return parts; + } + + /** + * Called by listParts to fetch a batch of part-info + */ + async listPartsQuery(bucketName, objectName, uploadId, marker) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!(0, _helper.isString)(uploadId)) { + throw new TypeError('uploadId should be of type "string"'); + } + if (!(0, _helper.isNumber)(marker)) { + throw new TypeError('marker should be of type "number"'); + } + if (!uploadId) { + throw new errors.InvalidArgumentError('uploadId cannot be empty'); + } + let query = `uploadId=${(0, _helper.uriEscape)(uploadId)}`; + if (marker) { + query += `&part-number-marker=${marker}`; + } + const method = 'GET'; + const res = await this.makeRequestAsync({ + method, + bucketName, + objectName, + query + }); + return xmlParsers.parseListParts(await (0, _response.readAsString)(res)); + } + async listBuckets() { + const method = 'GET'; + const regionConf = this.region || _helpers.DEFAULT_REGION; + const httpRes = await this.makeRequestAsync({ + method + }, '', [200], regionConf); + const xmlResult = await (0, _response.readAsString)(httpRes); + return xmlParsers.parseListBucket(xmlResult); + } + + /** + * Calculate part size given the object size. Part size will be atleast this.partSize + */ + calculatePartSize(size) { + if (!(0, _helper.isNumber)(size)) { + throw new TypeError('size should be of type "number"'); + } + if (size > this.maxObjectSize) { + throw new TypeError(`size should not be more than ${this.maxObjectSize}`); + } + if (this.overRidePartSize) { + return this.partSize; + } + let partSize = this.partSize; + for (;;) { + // while(true) {...} throws linting error. + // If partSize is big enough to accomodate the object size, then use it. + if (partSize * 10000 > size) { + return partSize; + } + // Try part sizes as 64MB, 80MB, 96MB etc. + partSize += 16 * 1024 * 1024; + } + } + + /** + * Uploads the object using contents from a file + */ + async fPutObject(bucketName, objectName, filePath, metaData) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!(0, _helper.isString)(filePath)) { + throw new TypeError('filePath should be of type "string"'); + } + if (metaData && !(0, _helper.isObject)(metaData)) { + throw new TypeError('metaData should be of type "object"'); + } + + // Inserts correct `content-type` attribute based on metaData and filePath + metaData = (0, _helper.insertContentType)(metaData || {}, filePath); + const stat = await _async2.fsp.stat(filePath); + return await this.putObject(bucketName, objectName, fs.createReadStream(filePath), stat.size, metaData); + } + + /** + * Uploading a stream, "Buffer" or "string". + * It's recommended to pass `size` argument with stream. + */ + async putObject(bucketName, objectName, stream, size, metaData) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + + // We'll need to shift arguments to the left because of metaData + // and size being optional. + if ((0, _helper.isObject)(size)) { + metaData = size; + } + // Ensures Metadata has appropriate prefix for A3 API + const headers = (0, _helper.prependXAMZMeta)(metaData); + if (typeof stream === 'string' || stream instanceof Buffer) { + // Adapts the non-stream interface into a stream. + size = stream.length; + stream = (0, _helper.readableStream)(stream); + } else if (!(0, _helper.isReadableStream)(stream)) { + throw new TypeError('third argument should be of type "stream.Readable" or "Buffer" or "string"'); + } + if ((0, _helper.isNumber)(size) && size < 0) { + throw new errors.InvalidArgumentError(`size cannot be negative, given size: ${size}`); + } + + // Get the part size and forward that to the BlockStream. Default to the + // largest block size possible if necessary. + if (!(0, _helper.isNumber)(size)) { + size = this.maxObjectSize; + } + + // Get the part size and forward that to the BlockStream. Default to the + // largest block size possible if necessary. + if (size === undefined) { + const statSize = await (0, _helper.getContentLength)(stream); + if (statSize !== null) { + size = statSize; + } + } + if (!(0, _helper.isNumber)(size)) { + // Backward compatibility + size = this.maxObjectSize; + } + if (size === 0) { + return this.uploadBuffer(bucketName, objectName, headers, Buffer.from('')); + } + const partSize = this.calculatePartSize(size); + if (typeof stream === 'string' || Buffer.isBuffer(stream) || size <= partSize) { + const buf = (0, _helper.isReadableStream)(stream) ? await (0, _response.readAsBuffer)(stream) : Buffer.from(stream); + return this.uploadBuffer(bucketName, objectName, headers, buf); + } + return this.uploadStream(bucketName, objectName, headers, stream, partSize); + } + + /** + * method to upload buffer in one call + * @private + */ + async uploadBuffer(bucketName, objectName, headers, buf) { + const { + md5sum, + sha256sum + } = (0, _helper.hashBinary)(buf, this.enableSHA256); + headers['Content-Length'] = buf.length; + if (!this.enableSHA256) { + headers['Content-MD5'] = md5sum; + } + const res = await this.makeRequestStreamAsync({ + method: 'PUT', + bucketName, + objectName, + headers + }, buf, sha256sum, [200], ''); + await (0, _response.drainResponse)(res); + return { + etag: (0, _helper.sanitizeETag)(res.headers.etag), + versionId: (0, _helper.getVersionId)(res.headers) + }; + } + + /** + * upload stream with MultipartUpload + * @private + */ + async uploadStream(bucketName, objectName, headers, body, partSize) { + // A map of the previously uploaded chunks, for resuming a file upload. This + // will be null if we aren't resuming an upload. + const oldParts = {}; + + // Keep track of the etags for aggregating the chunks together later. Each + // etag represents a single chunk of the file. + const eTags = []; + const previousUploadId = await this.findUploadId(bucketName, objectName); + let uploadId; + if (!previousUploadId) { + uploadId = await this.initiateNewMultipartUpload(bucketName, objectName, headers); + } else { + uploadId = previousUploadId; + const oldTags = await this.listParts(bucketName, objectName, previousUploadId); + oldTags.forEach(e => { + oldParts[e.part] = e; + }); + } + const chunkier = new _blockStream({ + size: partSize, + zeroPadding: false + }); + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const [_, o] = await Promise.all([new Promise((resolve, reject) => { + body.pipe(chunkier).on('error', reject); + chunkier.on('end', resolve).on('error', reject); + }), (async () => { + let partNumber = 1; + for await (const chunk of chunkier) { + const md5 = crypto.createHash('md5').update(chunk).digest(); + const oldPart = oldParts[partNumber]; + if (oldPart) { + if (oldPart.etag === md5.toString('hex')) { + eTags.push({ + part: partNumber, + etag: oldPart.etag + }); + partNumber++; + continue; + } + } + partNumber++; + + // now start to upload missing part + const options = { + method: 'PUT', + query: qs.stringify({ + partNumber, + uploadId + }), + headers: { + 'Content-Length': chunk.length, + 'Content-MD5': md5.toString('base64') + }, + bucketName, + objectName + }; + const response = await this.makeRequestAsyncOmit(options, chunk); + let etag = response.headers.etag; + if (etag) { + etag = etag.replace(/^"/, '').replace(/"$/, ''); + } else { + etag = ''; + } + eTags.push({ + part: partNumber, + etag + }); + } + return await this.completeMultipartUpload(bucketName, objectName, uploadId, eTags); + })()]); + return o; + } + async removeBucketReplication(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'DELETE'; + const query = 'replication'; + await this.makeRequestAsyncOmit({ + method, + bucketName, + query + }, '', [200, 204], ''); + } + async setBucketReplication(bucketName, replicationConfig) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isObject)(replicationConfig)) { + throw new errors.InvalidArgumentError('replicationConfig should be of type "object"'); + } else { + if (_lodash.isEmpty(replicationConfig.role)) { + throw new errors.InvalidArgumentError('Role cannot be empty'); + } else if (replicationConfig.role && !(0, _helper.isString)(replicationConfig.role)) { + throw new errors.InvalidArgumentError('Invalid value for role', replicationConfig.role); + } + if (_lodash.isEmpty(replicationConfig.rules)) { + throw new errors.InvalidArgumentError('Minimum one replication rule must be specified'); + } + } + const method = 'PUT'; + const query = 'replication'; + const headers = {}; + const replicationParamsConfig = { + ReplicationConfiguration: { + Role: replicationConfig.role, + Rule: replicationConfig.rules + } + }; + const builder = new _xml2js.Builder({ + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(replicationParamsConfig); + headers['Content-MD5'] = (0, _helper.toMd5)(payload); + await this.makeRequestAsyncOmit({ + method, + bucketName, + query, + headers + }, payload); + } + async getBucketReplication(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'GET'; + const query = 'replication'; + const httpRes = await this.makeRequestAsync({ + method, + bucketName, + query + }, '', [200, 204]); + const xmlResult = await (0, _response.readAsString)(httpRes); + return xmlParsers.parseReplicationConfig(xmlResult); + } + async getObjectLegalHold(bucketName, objectName, getOpts) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (getOpts) { + if (!(0, _helper.isObject)(getOpts)) { + throw new TypeError('getOpts should be of type "Object"'); + } else if (Object.keys(getOpts).length > 0 && getOpts.versionId && !(0, _helper.isString)(getOpts.versionId)) { + throw new TypeError('versionId should be of type string.:', getOpts.versionId); + } + } + const method = 'GET'; + let query = 'legal-hold'; + if (getOpts !== null && getOpts !== void 0 && getOpts.versionId) { + query += `&versionId=${getOpts.versionId}`; + } + const httpRes = await this.makeRequestAsync({ + method, + bucketName, + objectName, + query + }, '', [200]); + const strRes = await (0, _response.readAsString)(httpRes); + return (0, xmlParsers.parseObjectLegalHoldConfig)(strRes); + } + async setObjectLegalHold(bucketName, objectName, setOpts = { + status: _helpers.LEGAL_HOLD_STATUS.ENABLED + }) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!(0, _helper.isObject)(setOpts)) { + throw new TypeError('setOpts should be of type "Object"'); + } else { + if (![_helpers.LEGAL_HOLD_STATUS.ENABLED, _helpers.LEGAL_HOLD_STATUS.DISABLED].includes(setOpts === null || setOpts === void 0 ? void 0 : setOpts.status)) { + throw new TypeError('Invalid status: ' + setOpts.status); + } + if (setOpts.versionId && !setOpts.versionId.length) { + throw new TypeError('versionId should be of type string.:' + setOpts.versionId); + } + } + const method = 'PUT'; + let query = 'legal-hold'; + if (setOpts.versionId) { + query += `&versionId=${setOpts.versionId}`; + } + const config = { + Status: setOpts.status + }; + const builder = new _xml2js.Builder({ + rootName: 'LegalHold', + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(config); + const headers = {}; + headers['Content-MD5'] = (0, _helper.toMd5)(payload); + await this.makeRequestAsyncOmit({ + method, + bucketName, + objectName, + query, + headers + }, payload); + } + + /** + * Get Tags associated with a Bucket + */ + async getBucketTagging(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + const method = 'GET'; + const query = 'tagging'; + const requestOptions = { + method, + bucketName, + query + }; + const response = await this.makeRequestAsync(requestOptions); + const body = await (0, _response.readAsString)(response); + return xmlParsers.parseTagging(body); + } + + /** + * Get the tags associated with a bucket OR an object + */ + async getObjectTagging(bucketName, objectName, getOpts) { + const method = 'GET'; + let query = 'tagging'; + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidBucketNameError('Invalid object name: ' + objectName); + } + if (getOpts && !(0, _helper.isObject)(getOpts)) { + throw new errors.InvalidArgumentError('getOpts should be of type "object"'); + } + if (getOpts && getOpts.versionId) { + query = `${query}&versionId=${getOpts.versionId}`; + } + const requestOptions = { + method, + bucketName, + query + }; + if (objectName) { + requestOptions['objectName'] = objectName; + } + const response = await this.makeRequestAsync(requestOptions); + const body = await (0, _response.readAsString)(response); + return xmlParsers.parseTagging(body); + } + + /** + * Set the policy on a bucket or an object prefix. + */ + async setBucketPolicy(bucketName, policy) { + // Validate arguments. + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!(0, _helper.isString)(policy)) { + throw new errors.InvalidBucketPolicyError(`Invalid bucket policy: ${policy} - must be "string"`); + } + const query = 'policy'; + let method = 'DELETE'; + if (policy) { + method = 'PUT'; + } + await this.makeRequestAsyncOmit({ + method, + bucketName, + query + }, policy, [204], ''); + } + + /** + * Get the policy on a bucket or an object prefix. + */ + async getBucketPolicy(bucketName) { + // Validate arguments. + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + const method = 'GET'; + const query = 'policy'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + return await (0, _response.readAsString)(res); + } + async putObjectRetention(bucketName, objectName, retentionOpts = {}) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!(0, _helper.isObject)(retentionOpts)) { + throw new errors.InvalidArgumentError('retentionOpts should be of type "object"'); + } else { + if (retentionOpts.governanceBypass && !(0, _helper.isBoolean)(retentionOpts.governanceBypass)) { + throw new errors.InvalidArgumentError(`Invalid value for governanceBypass: ${retentionOpts.governanceBypass}`); + } + if (retentionOpts.mode && ![_helpers.RETENTION_MODES.COMPLIANCE, _helpers.RETENTION_MODES.GOVERNANCE].includes(retentionOpts.mode)) { + throw new errors.InvalidArgumentError(`Invalid object retention mode: ${retentionOpts.mode}`); + } + if (retentionOpts.retainUntilDate && !(0, _helper.isString)(retentionOpts.retainUntilDate)) { + throw new errors.InvalidArgumentError(`Invalid value for retainUntilDate: ${retentionOpts.retainUntilDate}`); + } + if (retentionOpts.versionId && !(0, _helper.isString)(retentionOpts.versionId)) { + throw new errors.InvalidArgumentError(`Invalid value for versionId: ${retentionOpts.versionId}`); + } + } + const method = 'PUT'; + let query = 'retention'; + const headers = {}; + if (retentionOpts.governanceBypass) { + headers['X-Amz-Bypass-Governance-Retention'] = true; + } + const builder = new _xml2js.Builder({ + rootName: 'Retention', + renderOpts: { + pretty: false + }, + headless: true + }); + const params = {}; + if (retentionOpts.mode) { + params.Mode = retentionOpts.mode; + } + if (retentionOpts.retainUntilDate) { + params.RetainUntilDate = retentionOpts.retainUntilDate; + } + if (retentionOpts.versionId) { + query += `&versionId=${retentionOpts.versionId}`; + } + const payload = builder.buildObject(params); + headers['Content-MD5'] = (0, _helper.toMd5)(payload); + await this.makeRequestAsyncOmit({ + method, + bucketName, + objectName, + query, + headers + }, payload, [200, 204]); + } + async getObjectLockConfig(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'GET'; + const query = 'object-lock'; + const httpRes = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const xmlResult = await (0, _response.readAsString)(httpRes); + return xmlParsers.parseObjectLockConfig(xmlResult); + } + async setObjectLockConfig(bucketName, lockConfigOpts) { + const retentionModes = [_helpers.RETENTION_MODES.COMPLIANCE, _helpers.RETENTION_MODES.GOVERNANCE]; + const validUnits = [_helpers.RETENTION_VALIDITY_UNITS.DAYS, _helpers.RETENTION_VALIDITY_UNITS.YEARS]; + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (lockConfigOpts.mode && !retentionModes.includes(lockConfigOpts.mode)) { + throw new TypeError(`lockConfigOpts.mode should be one of ${retentionModes}`); + } + if (lockConfigOpts.unit && !validUnits.includes(lockConfigOpts.unit)) { + throw new TypeError(`lockConfigOpts.unit should be one of ${validUnits}`); + } + if (lockConfigOpts.validity && !(0, _helper.isNumber)(lockConfigOpts.validity)) { + throw new TypeError(`lockConfigOpts.validity should be a number`); + } + const method = 'PUT'; + const query = 'object-lock'; + const config = { + ObjectLockEnabled: 'Enabled' + }; + const configKeys = Object.keys(lockConfigOpts); + const isAllKeysSet = ['unit', 'mode', 'validity'].every(lck => configKeys.includes(lck)); + // Check if keys are present and all keys are present. + if (configKeys.length > 0) { + if (!isAllKeysSet) { + throw new TypeError(`lockConfigOpts.mode,lockConfigOpts.unit,lockConfigOpts.validity all the properties should be specified.`); + } else { + config.Rule = { + DefaultRetention: {} + }; + if (lockConfigOpts.mode) { + config.Rule.DefaultRetention.Mode = lockConfigOpts.mode; + } + if (lockConfigOpts.unit === _helpers.RETENTION_VALIDITY_UNITS.DAYS) { + config.Rule.DefaultRetention.Days = lockConfigOpts.validity; + } else if (lockConfigOpts.unit === _helpers.RETENTION_VALIDITY_UNITS.YEARS) { + config.Rule.DefaultRetention.Years = lockConfigOpts.validity; + } + } + } + const builder = new _xml2js.Builder({ + rootName: 'ObjectLockConfiguration', + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(config); + const headers = {}; + headers['Content-MD5'] = (0, _helper.toMd5)(payload); + await this.makeRequestAsyncOmit({ + method, + bucketName, + query, + headers + }, payload); + } + async getBucketVersioning(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'GET'; + const query = 'versioning'; + const httpRes = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const xmlResult = await (0, _response.readAsString)(httpRes); + return await xmlParsers.parseBucketVersioningConfig(xmlResult); + } + async setBucketVersioning(bucketName, versionConfig) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!Object.keys(versionConfig).length) { + throw new errors.InvalidArgumentError('versionConfig should be of type "object"'); + } + const method = 'PUT'; + const query = 'versioning'; + const builder = new _xml2js.Builder({ + rootName: 'VersioningConfiguration', + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(versionConfig); + await this.makeRequestAsyncOmit({ + method, + bucketName, + query + }, payload); + } + async setTagging(taggingParams) { + const { + bucketName, + objectName, + tags, + putOpts + } = taggingParams; + const method = 'PUT'; + let query = 'tagging'; + if (putOpts && putOpts !== null && putOpts !== void 0 && putOpts.versionId) { + query = `${query}&versionId=${putOpts.versionId}`; + } + const tagsList = []; + for (const [key, value] of Object.entries(tags)) { + tagsList.push({ + Key: key, + Value: value + }); + } + const taggingConfig = { + Tagging: { + TagSet: { + Tag: tagsList + } + } + }; + const headers = {}; + const builder = new _xml2js.Builder({ + headless: true, + renderOpts: { + pretty: false + } + }); + const payloadBuf = Buffer.from(builder.buildObject(taggingConfig)); + const requestOptions = { + method, + bucketName, + query, + headers, + ...(objectName && { + objectName: objectName + }) + }; + headers['Content-MD5'] = (0, _helper.toMd5)(payloadBuf); + await this.makeRequestAsyncOmit(requestOptions, payloadBuf); + } + async removeTagging({ + bucketName, + objectName, + removeOpts + }) { + const method = 'DELETE'; + let query = 'tagging'; + if (removeOpts && Object.keys(removeOpts).length && removeOpts.versionId) { + query = `${query}&versionId=${removeOpts.versionId}`; + } + const requestOptions = { + method, + bucketName, + objectName, + query + }; + if (objectName) { + requestOptions['objectName'] = objectName; + } + await this.makeRequestAsync(requestOptions, '', [200, 204]); + } + async setBucketTagging(bucketName, tags) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isPlainObject)(tags)) { + throw new errors.InvalidArgumentError('tags should be of type "object"'); + } + if (Object.keys(tags).length > 10) { + throw new errors.InvalidArgumentError('maximum tags allowed is 10"'); + } + await this.setTagging({ + bucketName, + tags + }); + } + async removeBucketTagging(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + await this.removeTagging({ + bucketName + }); + } + async setObjectTagging(bucketName, objectName, tags, putOpts) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidBucketNameError('Invalid object name: ' + objectName); + } + if (!(0, _helper.isPlainObject)(tags)) { + throw new errors.InvalidArgumentError('tags should be of type "object"'); + } + if (Object.keys(tags).length > 10) { + throw new errors.InvalidArgumentError('Maximum tags allowed is 10"'); + } + await this.setTagging({ + bucketName, + objectName, + tags, + putOpts + }); + } + async removeObjectTagging(bucketName, objectName, removeOpts) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidBucketNameError('Invalid object name: ' + objectName); + } + if (removeOpts && Object.keys(removeOpts).length && !(0, _helper.isObject)(removeOpts)) { + throw new errors.InvalidArgumentError('removeOpts should be of type "object"'); + } + await this.removeTagging({ + bucketName, + objectName, + removeOpts + }); + } + async selectObjectContent(bucketName, objectName, selectOpts) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (!_lodash.isEmpty(selectOpts)) { + if (!(0, _helper.isString)(selectOpts.expression)) { + throw new TypeError('sqlExpression should be of type "string"'); + } + if (!_lodash.isEmpty(selectOpts.inputSerialization)) { + if (!(0, _helper.isObject)(selectOpts.inputSerialization)) { + throw new TypeError('inputSerialization should be of type "object"'); + } + } else { + throw new TypeError('inputSerialization is required'); + } + if (!_lodash.isEmpty(selectOpts.outputSerialization)) { + if (!(0, _helper.isObject)(selectOpts.outputSerialization)) { + throw new TypeError('outputSerialization should be of type "object"'); + } + } else { + throw new TypeError('outputSerialization is required'); + } + } else { + throw new TypeError('valid select configuration is required'); + } + const method = 'POST'; + const query = `select&select-type=2`; + const config = [{ + Expression: selectOpts.expression + }, { + ExpressionType: selectOpts.expressionType || 'SQL' + }, { + InputSerialization: [selectOpts.inputSerialization] + }, { + OutputSerialization: [selectOpts.outputSerialization] + }]; + + // Optional + if (selectOpts.requestProgress) { + config.push({ + RequestProgress: selectOpts === null || selectOpts === void 0 ? void 0 : selectOpts.requestProgress + }); + } + // Optional + if (selectOpts.scanRange) { + config.push({ + ScanRange: selectOpts.scanRange + }); + } + const builder = new _xml2js.Builder({ + rootName: 'SelectObjectContentRequest', + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(config); + const res = await this.makeRequestAsync({ + method, + bucketName, + objectName, + query + }, payload); + const body = await (0, _response.readAsBuffer)(res); + return (0, xmlParsers.parseSelectObjectContentResponse)(body); + } + async applyBucketLifecycle(bucketName, policyConfig) { + const method = 'PUT'; + const query = 'lifecycle'; + const headers = {}; + const builder = new _xml2js.Builder({ + rootName: 'LifecycleConfiguration', + headless: true, + renderOpts: { + pretty: false + } + }); + const payload = builder.buildObject(policyConfig); + headers['Content-MD5'] = (0, _helper.toMd5)(payload); + await this.makeRequestAsyncOmit({ + method, + bucketName, + query, + headers + }, payload); + } + async removeBucketLifecycle(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'DELETE'; + const query = 'lifecycle'; + await this.makeRequestAsyncOmit({ + method, + bucketName, + query + }, '', [204]); + } + async setBucketLifecycle(bucketName, lifeCycleConfig) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (_lodash.isEmpty(lifeCycleConfig)) { + await this.removeBucketLifecycle(bucketName); + } else { + await this.applyBucketLifecycle(bucketName, lifeCycleConfig); + } + } + async getBucketLifecycle(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'GET'; + const query = 'lifecycle'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const body = await (0, _response.readAsString)(res); + return xmlParsers.parseLifecycleConfig(body); + } + async setBucketEncryption(bucketName, encryptionConfig) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!_lodash.isEmpty(encryptionConfig) && encryptionConfig.Rule.length > 1) { + throw new errors.InvalidArgumentError('Invalid Rule length. Only one rule is allowed.: ' + encryptionConfig.Rule); + } + let encryptionObj = encryptionConfig; + if (_lodash.isEmpty(encryptionConfig)) { + encryptionObj = { + // Default MinIO Server Supported Rule + Rule: [{ + ApplyServerSideEncryptionByDefault: { + SSEAlgorithm: 'AES256' + } + }] + }; + } + const method = 'PUT'; + const query = 'encryption'; + const builder = new _xml2js.Builder({ + rootName: 'ServerSideEncryptionConfiguration', + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(encryptionObj); + const headers = {}; + headers['Content-MD5'] = (0, _helper.toMd5)(payload); + await this.makeRequestAsyncOmit({ + method, + bucketName, + query, + headers + }, payload); + } + async getBucketEncryption(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'GET'; + const query = 'encryption'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const body = await (0, _response.readAsString)(res); + return xmlParsers.parseBucketEncryptionConfig(body); + } + async removeBucketEncryption(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'DELETE'; + const query = 'encryption'; + await this.makeRequestAsyncOmit({ + method, + bucketName, + query + }, '', [204]); + } + async getObjectRetention(bucketName, objectName, getOpts) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + if (getOpts && !(0, _helper.isObject)(getOpts)) { + throw new errors.InvalidArgumentError('getOpts should be of type "object"'); + } else if (getOpts !== null && getOpts !== void 0 && getOpts.versionId && !(0, _helper.isString)(getOpts.versionId)) { + throw new errors.InvalidArgumentError('versionId should be of type "string"'); + } + const method = 'GET'; + let query = 'retention'; + if (getOpts !== null && getOpts !== void 0 && getOpts.versionId) { + query += `&versionId=${getOpts.versionId}`; + } + const res = await this.makeRequestAsync({ + method, + bucketName, + objectName, + query + }); + const body = await (0, _response.readAsString)(res); + return xmlParsers.parseObjectRetentionConfig(body); + } + async removeObjects(bucketName, objectsList) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!Array.isArray(objectsList)) { + throw new errors.InvalidArgumentError('objectsList should be a list'); + } + const runDeleteObjects = async batch => { + const delObjects = batch.map(value => { + return (0, _helper.isObject)(value) ? { + Key: value.name, + VersionId: value.versionId + } : { + Key: value + }; + }); + const remObjects = { + Delete: { + Quiet: true, + Object: delObjects + } + }; + const payload = Buffer.from(new _xml2js.Builder({ + headless: true + }).buildObject(remObjects)); + const headers = { + 'Content-MD5': (0, _helper.toMd5)(payload) + }; + const res = await this.makeRequestAsync({ + method: 'POST', + bucketName, + query: 'delete', + headers + }, payload); + const body = await (0, _response.readAsString)(res); + return xmlParsers.removeObjectsParser(body); + }; + const maxEntries = 1000; // max entries accepted in server for DeleteMultipleObjects API. + // Client side batching + const batches = []; + for (let i = 0; i < objectsList.length; i += maxEntries) { + batches.push(objectsList.slice(i, i + maxEntries)); + } + const batchResults = await Promise.all(batches.map(runDeleteObjects)); + return batchResults.flat(); + } + async removeIncompleteUpload(bucketName, objectName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.IsValidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + const removeUploadId = await this.findUploadId(bucketName, objectName); + const method = 'DELETE'; + const query = `uploadId=${removeUploadId}`; + await this.makeRequestAsyncOmit({ + method, + bucketName, + objectName, + query + }, '', [204]); + } + async copyObjectV1(targetBucketName, targetObjectName, sourceBucketNameAndObjectName, conditions) { + if (typeof conditions == 'function') { + conditions = null; + } + if (!(0, _helper.isValidBucketName)(targetBucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + targetBucketName); + } + if (!(0, _helper.isValidObjectName)(targetObjectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${targetObjectName}`); + } + if (!(0, _helper.isString)(sourceBucketNameAndObjectName)) { + throw new TypeError('sourceBucketNameAndObjectName should be of type "string"'); + } + if (sourceBucketNameAndObjectName === '') { + throw new errors.InvalidPrefixError(`Empty source prefix`); + } + if (conditions != null && !(conditions instanceof _copyConditions.CopyConditions)) { + throw new TypeError('conditions should be of type "CopyConditions"'); + } + const headers = {}; + headers['x-amz-copy-source'] = (0, _helper.uriResourceEscape)(sourceBucketNameAndObjectName); + if (conditions) { + if (conditions.modified !== '') { + headers['x-amz-copy-source-if-modified-since'] = conditions.modified; + } + if (conditions.unmodified !== '') { + headers['x-amz-copy-source-if-unmodified-since'] = conditions.unmodified; + } + if (conditions.matchETag !== '') { + headers['x-amz-copy-source-if-match'] = conditions.matchETag; + } + if (conditions.matchETagExcept !== '') { + headers['x-amz-copy-source-if-none-match'] = conditions.matchETagExcept; + } + } + const method = 'PUT'; + const res = await this.makeRequestAsync({ + method, + bucketName: targetBucketName, + objectName: targetObjectName, + headers + }); + const body = await (0, _response.readAsString)(res); + return xmlParsers.parseCopyObject(body); + } + async copyObjectV2(sourceConfig, destConfig) { + if (!(sourceConfig instanceof _helpers.CopySourceOptions)) { + throw new errors.InvalidArgumentError('sourceConfig should of type CopySourceOptions '); + } + if (!(destConfig instanceof _helpers.CopyDestinationOptions)) { + throw new errors.InvalidArgumentError('destConfig should of type CopyDestinationOptions '); + } + if (!destConfig.validate()) { + return Promise.reject(); + } + if (!destConfig.validate()) { + return Promise.reject(); + } + const headers = Object.assign({}, sourceConfig.getHeaders(), destConfig.getHeaders()); + const bucketName = destConfig.Bucket; + const objectName = destConfig.Object; + const method = 'PUT'; + const res = await this.makeRequestAsync({ + method, + bucketName, + objectName, + headers + }); + const body = await (0, _response.readAsString)(res); + const copyRes = xmlParsers.parseCopyObject(body); + const resHeaders = res.headers; + const sizeHeaderValue = resHeaders && resHeaders['content-length']; + const size = typeof sizeHeaderValue === 'number' ? sizeHeaderValue : undefined; + return { + Bucket: destConfig.Bucket, + Key: destConfig.Object, + LastModified: copyRes.lastModified, + MetaData: (0, _helper.extractMetadata)(resHeaders), + VersionId: (0, _helper.getVersionId)(resHeaders), + SourceVersionId: (0, _helper.getSourceVersionId)(resHeaders), + Etag: (0, _helper.sanitizeETag)(resHeaders.etag), + Size: size + }; + } + async copyObject(...allArgs) { + if (typeof allArgs[0] === 'string') { + const [targetBucketName, targetObjectName, sourceBucketNameAndObjectName, conditions] = allArgs; + return await this.copyObjectV1(targetBucketName, targetObjectName, sourceBucketNameAndObjectName, conditions); + } + const [source, dest] = allArgs; + return await this.copyObjectV2(source, dest); + } + async uploadPart(partConfig, payload) { + const { + bucketName, + objectName, + uploadID, + partNumber, + headers + } = partConfig; + const method = 'PUT'; + const query = `uploadId=${uploadID}&partNumber=${partNumber}`; + const requestOptions = { + method, + bucketName, + objectName: objectName, + query, + headers + }; + const res = await this.makeRequestAsync(requestOptions, payload); + const body = await (0, _response.readAsString)(res); + const partRes = (0, xmlParsers.uploadPartParser)(body); + const partEtagVal = (0, _helper.sanitizeETag)(res.headers.etag) || (0, _helper.sanitizeETag)(partRes.ETag); + return { + etag: partEtagVal, + key: objectName, + part: partNumber + }; + } + async composeObject(destObjConfig, sourceObjList, { + maxConcurrency = 10 + } = {}) { + const sourceFilesLength = sourceObjList.length; + if (!Array.isArray(sourceObjList)) { + throw new errors.InvalidArgumentError('sourceConfig should an array of CopySourceOptions '); + } + if (!(destObjConfig instanceof _helpers.CopyDestinationOptions)) { + throw new errors.InvalidArgumentError('destConfig should of type CopyDestinationOptions '); + } + if (sourceFilesLength < 1 || sourceFilesLength > _helper.PART_CONSTRAINTS.MAX_PARTS_COUNT) { + throw new errors.InvalidArgumentError(`"There must be as least one and up to ${_helper.PART_CONSTRAINTS.MAX_PARTS_COUNT} source objects.`); + } + for (let i = 0; i < sourceFilesLength; i++) { + const sObj = sourceObjList[i]; + if (!sObj.validate()) { + return false; + } + } + if (!destObjConfig.validate()) { + return false; + } + const getStatOptions = srcConfig => { + let statOpts = {}; + if (!_lodash.isEmpty(srcConfig.VersionID)) { + statOpts = { + versionId: srcConfig.VersionID + }; + } + return statOpts; + }; + const srcObjectSizes = []; + let totalSize = 0; + let totalParts = 0; + const sourceObjStats = sourceObjList.map(srcItem => this.statObject(srcItem.Bucket, srcItem.Object, getStatOptions(srcItem))); + const srcObjectInfos = await Promise.all(sourceObjStats); + const validatedStats = srcObjectInfos.map((resItemStat, index) => { + const srcConfig = sourceObjList[index]; + let srcCopySize = resItemStat.size; + // Check if a segment is specified, and if so, is the + // segment within object bounds? + if (srcConfig && srcConfig.MatchRange) { + // Since range is specified, + // 0 <= src.srcStart <= src.srcEnd + // so only invalid case to check is: + const srcStart = srcConfig.Start; + const srcEnd = srcConfig.End; + if (srcEnd >= srcCopySize || srcStart < 0) { + throw new errors.InvalidArgumentError(`CopySrcOptions ${index} has invalid segment-to-copy [${srcStart}, ${srcEnd}] (size is ${srcCopySize})`); + } + srcCopySize = srcEnd - srcStart + 1; + } + + // Only the last source may be less than `absMinPartSize` + if (srcCopySize < _helper.PART_CONSTRAINTS.ABS_MIN_PART_SIZE && index < sourceFilesLength - 1) { + throw new errors.InvalidArgumentError(`CopySrcOptions ${index} is too small (${srcCopySize}) and it is not the last part.`); + } + + // Is data to copy too large? + totalSize += srcCopySize; + if (totalSize > _helper.PART_CONSTRAINTS.MAX_MULTIPART_PUT_OBJECT_SIZE) { + throw new errors.InvalidArgumentError(`Cannot compose an object of size ${totalSize} (> 5TiB)`); + } + + // record source size + srcObjectSizes[index] = srcCopySize; + + // calculate parts needed for current source + totalParts += (0, _helper.partsRequired)(srcCopySize); + // Do we need more parts than we are allowed? + if (totalParts > _helper.PART_CONSTRAINTS.MAX_PARTS_COUNT) { + throw new errors.InvalidArgumentError(`Your proposed compose object requires more than ${_helper.PART_CONSTRAINTS.MAX_PARTS_COUNT} parts`); + } + return resItemStat; + }); + if (totalParts === 1 && totalSize <= _helper.PART_CONSTRAINTS.MAX_PART_SIZE || totalSize === 0) { + return await this.copyObject(sourceObjList[0], destObjConfig); // use copyObjectV2 + } + + // preserve etag to avoid modification of object while copying. + for (let i = 0; i < sourceFilesLength; i++) { + ; + sourceObjList[i].MatchETag = validatedStats[i].etag; + } + const splitPartSizeList = validatedStats.map((resItemStat, idx) => { + return (0, _helper.calculateEvenSplits)(srcObjectSizes[idx], sourceObjList[idx]); + }); + const getUploadPartConfigList = uploadId => { + const uploadPartConfigList = []; + splitPartSizeList.forEach((splitSize, splitIndex) => { + if (splitSize) { + const { + startIndex: startIdx, + endIndex: endIdx, + objInfo: objConfig + } = splitSize; + const partIndex = splitIndex + 1; // part index starts from 1. + const totalUploads = Array.from(startIdx); + const headers = sourceObjList[splitIndex].getHeaders(); + totalUploads.forEach((splitStart, upldCtrIdx) => { + const splitEnd = endIdx[upldCtrIdx]; + const sourceObj = `${objConfig.Bucket}/${objConfig.Object}`; + headers['x-amz-copy-source'] = `${sourceObj}`; + headers['x-amz-copy-source-range'] = `bytes=${splitStart}-${splitEnd}`; + const uploadPartConfig = { + bucketName: destObjConfig.Bucket, + objectName: destObjConfig.Object, + uploadID: uploadId, + partNumber: partIndex, + headers: headers, + sourceObj: sourceObj + }; + uploadPartConfigList.push(uploadPartConfig); + }); + } + }); + return uploadPartConfigList; + }; + const uploadAllParts = async uploadList => { + const partUploads = []; + + // Process upload parts in batches to avoid too many concurrent requests + for (const batch of _lodash.chunk(uploadList, maxConcurrency)) { + const batchResults = await Promise.all(batch.map(item => this.uploadPart(item))); + partUploads.push(...batchResults); + } + + // Process results here if needed + return partUploads; + }; + const performUploadParts = async uploadId => { + const uploadList = getUploadPartConfigList(uploadId); + const partsRes = await uploadAllParts(uploadList); + return partsRes.map(partCopy => ({ + etag: partCopy.etag, + part: partCopy.part + })); + }; + const newUploadHeaders = destObjConfig.getHeaders(); + const uploadId = await this.initiateNewMultipartUpload(destObjConfig.Bucket, destObjConfig.Object, newUploadHeaders); + try { + const partsDone = await performUploadParts(uploadId); + return await this.completeMultipartUpload(destObjConfig.Bucket, destObjConfig.Object, uploadId, partsDone); + } catch (err) { + return await this.abortMultipartUpload(destObjConfig.Bucket, destObjConfig.Object, uploadId); + } + } + async presignedUrl(method, bucketName, objectName, expires, reqParams, requestDate) { + var _requestDate; + if (this.anonymous) { + throw new errors.AnonymousRequestError(`Presigned ${method} url cannot be generated for anonymous requests`); + } + if (!expires) { + expires = _helpers.PRESIGN_EXPIRY_DAYS_MAX; + } + if (!reqParams) { + reqParams = {}; + } + if (!requestDate) { + requestDate = new Date(); + } + + // Type assertions + if (expires && typeof expires !== 'number') { + throw new TypeError('expires should be of type "number"'); + } + if (reqParams && typeof reqParams !== 'object') { + throw new TypeError('reqParams should be of type "object"'); + } + if (requestDate && !(requestDate instanceof Date) || requestDate && isNaN((_requestDate = requestDate) === null || _requestDate === void 0 ? void 0 : _requestDate.getTime())) { + throw new TypeError('requestDate should be of type "Date" and valid'); + } + const query = reqParams ? qs.stringify(reqParams) : undefined; + try { + const region = await this.getBucketRegionAsync(bucketName); + await this.checkAndRefreshCreds(); + const reqOptions = this.getRequestOptions({ + method, + region, + bucketName, + objectName, + query + }); + return (0, _signing.presignSignatureV4)(reqOptions, this.accessKey, this.secretKey, this.sessionToken, region, requestDate, expires); + } catch (err) { + if (err instanceof errors.InvalidBucketNameError) { + throw new errors.InvalidArgumentError(`Unable to get bucket region for ${bucketName}.`); + } + throw err; + } + } + async presignedGetObject(bucketName, objectName, expires, respHeaders, requestDate) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + const validRespHeaders = ['response-content-type', 'response-content-language', 'response-expires', 'response-cache-control', 'response-content-disposition', 'response-content-encoding']; + validRespHeaders.forEach(header => { + // @ts-ignore + if (respHeaders !== undefined && respHeaders[header] !== undefined && !(0, _helper.isString)(respHeaders[header])) { + throw new TypeError(`response header ${header} should be of type "string"`); + } + }); + return this.presignedUrl('GET', bucketName, objectName, expires, respHeaders, requestDate); + } + async presignedPutObject(bucketName, objectName, expires) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`); + } + return this.presignedUrl('PUT', bucketName, objectName, expires); + } + newPostPolicy() { + return new _postPolicy.PostPolicy(); + } + async presignedPostPolicy(postPolicy) { + if (this.anonymous) { + throw new errors.AnonymousRequestError('Presigned POST policy cannot be generated for anonymous requests'); + } + if (!(0, _helper.isObject)(postPolicy)) { + throw new TypeError('postPolicy should be of type "object"'); + } + const bucketName = postPolicy.formData.bucket; + try { + const region = await this.getBucketRegionAsync(bucketName); + const date = new Date(); + const dateStr = (0, _helper.makeDateLong)(date); + await this.checkAndRefreshCreds(); + if (!postPolicy.policy.expiration) { + // 'expiration' is mandatory field for S3. + // Set default expiration date of 7 days. + const expires = new Date(); + expires.setSeconds(_helpers.PRESIGN_EXPIRY_DAYS_MAX); + postPolicy.setExpires(expires); + } + postPolicy.policy.conditions.push(['eq', '$x-amz-date', dateStr]); + postPolicy.formData['x-amz-date'] = dateStr; + postPolicy.policy.conditions.push(['eq', '$x-amz-algorithm', 'AWS4-HMAC-SHA256']); + postPolicy.formData['x-amz-algorithm'] = 'AWS4-HMAC-SHA256'; + postPolicy.policy.conditions.push(['eq', '$x-amz-credential', this.accessKey + '/' + (0, _helper.getScope)(region, date)]); + postPolicy.formData['x-amz-credential'] = this.accessKey + '/' + (0, _helper.getScope)(region, date); + if (this.sessionToken) { + postPolicy.policy.conditions.push(['eq', '$x-amz-security-token', this.sessionToken]); + postPolicy.formData['x-amz-security-token'] = this.sessionToken; + } + const policyBase64 = Buffer.from(JSON.stringify(postPolicy.policy)).toString('base64'); + postPolicy.formData.policy = policyBase64; + postPolicy.formData['x-amz-signature'] = (0, _signing.postPresignSignatureV4)(region, date, this.secretKey, policyBase64); + const opts = { + region: region, + bucketName: bucketName, + method: 'POST' + }; + const reqOptions = this.getRequestOptions(opts); + const portStr = this.port == 80 || this.port === 443 ? '' : `:${this.port.toString()}`; + const urlStr = `${reqOptions.protocol}//${reqOptions.host}${portStr}${reqOptions.path}`; + return { + postURL: urlStr, + formData: postPolicy.formData + }; + } catch (err) { + if (err instanceof errors.InvalidBucketNameError) { + throw new errors.InvalidArgumentError(`Unable to get bucket region for ${bucketName}.`); + } + throw err; + } + } + // list a batch of objects + async listObjectsQuery(bucketName, prefix, marker, listQueryOpts) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isString)(prefix)) { + throw new TypeError('prefix should be of type "string"'); + } + if (marker && !(0, _helper.isString)(marker)) { + throw new TypeError('marker should be of type "string"'); + } + if (listQueryOpts && !(0, _helper.isObject)(listQueryOpts)) { + throw new TypeError('listQueryOpts should be of type "object"'); + } + let { + Delimiter, + MaxKeys, + IncludeVersion, + versionIdMarker, + keyMarker + } = listQueryOpts; + if (!(0, _helper.isString)(Delimiter)) { + throw new TypeError('Delimiter should be of type "string"'); + } + if (!(0, _helper.isNumber)(MaxKeys)) { + throw new TypeError('MaxKeys should be of type "number"'); + } + const queries = []; + // escape every value in query string, except maxKeys + queries.push(`prefix=${(0, _helper.uriEscape)(prefix)}`); + queries.push(`delimiter=${(0, _helper.uriEscape)(Delimiter)}`); + queries.push(`encoding-type=url`); + if (IncludeVersion) { + queries.push(`versions`); + } + if (IncludeVersion) { + // v1 version listing.. + if (keyMarker) { + queries.push(`key-marker=${keyMarker}`); + } + if (versionIdMarker) { + queries.push(`version-id-marker=${versionIdMarker}`); + } + } else if (marker) { + marker = (0, _helper.uriEscape)(marker); + queries.push(`marker=${marker}`); + } + + // no need to escape maxKeys + if (MaxKeys) { + if (MaxKeys >= 1000) { + MaxKeys = 1000; + } + queries.push(`max-keys=${MaxKeys}`); + } + queries.sort(); + let query = ''; + if (queries.length > 0) { + query = `${queries.join('&')}`; + } + const method = 'GET'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const body = await (0, _response.readAsString)(res); + const listQryList = (0, xmlParsers.parseListObjects)(body); + return listQryList; + } + listObjects(bucketName, prefix, recursive, listOpts) { + if (prefix === undefined) { + prefix = ''; + } + if (recursive === undefined) { + recursive = false; + } + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidPrefix)(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`); + } + if (!(0, _helper.isString)(prefix)) { + throw new TypeError('prefix should be of type "string"'); + } + if (!(0, _helper.isBoolean)(recursive)) { + throw new TypeError('recursive should be of type "boolean"'); + } + if (listOpts && !(0, _helper.isObject)(listOpts)) { + throw new TypeError('listOpts should be of type "object"'); + } + let marker = ''; + let keyMarker = ''; + let versionIdMarker = ''; + let objects = []; + let ended = false; + const readStream = new stream.Readable({ + objectMode: true + }); + readStream._read = async () => { + // push one object per _read() + if (objects.length) { + readStream.push(objects.shift()); + return; + } + if (ended) { + return readStream.push(null); + } + try { + const listQueryOpts = { + Delimiter: recursive ? '' : '/', + // if recursive is false set delimiter to '/' + MaxKeys: 1000, + IncludeVersion: listOpts === null || listOpts === void 0 ? void 0 : listOpts.IncludeVersion, + // version listing specific options + keyMarker: keyMarker, + versionIdMarker: versionIdMarker + }; + const result = await this.listObjectsQuery(bucketName, prefix, marker, listQueryOpts); + if (result.isTruncated) { + marker = result.nextMarker || undefined; + if (result.keyMarker) { + keyMarker = result.keyMarker; + } + if (result.versionIdMarker) { + versionIdMarker = result.versionIdMarker; + } + } else { + ended = true; + } + if (result.objects) { + objects = result.objects; + } + // @ts-ignore + readStream._read(); + } catch (err) { + readStream.emit('error', err); + } + }; + return readStream; + } + async listObjectsV2Query(bucketName, prefix, continuationToken, delimiter, maxKeys, startAfter) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isString)(prefix)) { + throw new TypeError('prefix should be of type "string"'); + } + if (!(0, _helper.isString)(continuationToken)) { + throw new TypeError('continuationToken should be of type "string"'); + } + if (!(0, _helper.isString)(delimiter)) { + throw new TypeError('delimiter should be of type "string"'); + } + if (!(0, _helper.isNumber)(maxKeys)) { + throw new TypeError('maxKeys should be of type "number"'); + } + if (!(0, _helper.isString)(startAfter)) { + throw new TypeError('startAfter should be of type "string"'); + } + const queries = []; + queries.push(`list-type=2`); + queries.push(`encoding-type=url`); + queries.push(`prefix=${(0, _helper.uriEscape)(prefix)}`); + queries.push(`delimiter=${(0, _helper.uriEscape)(delimiter)}`); + if (continuationToken) { + queries.push(`continuation-token=${(0, _helper.uriEscape)(continuationToken)}`); + } + if (startAfter) { + queries.push(`start-after=${(0, _helper.uriEscape)(startAfter)}`); + } + if (maxKeys) { + if (maxKeys >= 1000) { + maxKeys = 1000; + } + queries.push(`max-keys=${maxKeys}`); + } + queries.sort(); + let query = ''; + if (queries.length > 0) { + query = `${queries.join('&')}`; + } + const method = 'GET'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const body = await (0, _response.readAsString)(res); + return (0, xmlParsers.parseListObjectsV2)(body); + } + listObjectsV2(bucketName, prefix, recursive, startAfter) { + if (prefix === undefined) { + prefix = ''; + } + if (recursive === undefined) { + recursive = false; + } + if (startAfter === undefined) { + startAfter = ''; + } + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidPrefix)(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`); + } + if (!(0, _helper.isString)(prefix)) { + throw new TypeError('prefix should be of type "string"'); + } + if (!(0, _helper.isBoolean)(recursive)) { + throw new TypeError('recursive should be of type "boolean"'); + } + if (!(0, _helper.isString)(startAfter)) { + throw new TypeError('startAfter should be of type "string"'); + } + const delimiter = recursive ? '' : '/'; + const prefixStr = prefix; + const startAfterStr = startAfter; + let continuationToken = ''; + let objects = []; + let ended = false; + const readStream = new stream.Readable({ + objectMode: true + }); + readStream._read = async () => { + if (objects.length) { + readStream.push(objects.shift()); + return; + } + if (ended) { + return readStream.push(null); + } + try { + const result = await this.listObjectsV2Query(bucketName, prefixStr, continuationToken, delimiter, 1000, startAfterStr); + if (result.isTruncated) { + continuationToken = result.nextContinuationToken; + } else { + ended = true; + } + objects = result.objects; + // @ts-ignore + readStream._read(); + } catch (err) { + readStream.emit('error', err); + } + }; + return readStream; + } + async setBucketNotification(bucketName, config) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isObject)(config)) { + throw new TypeError('notification config should be of type "Object"'); + } + const method = 'PUT'; + const query = 'notification'; + const builder = new _xml2js.Builder({ + rootName: 'NotificationConfiguration', + renderOpts: { + pretty: false + }, + headless: true + }); + const payload = builder.buildObject(config); + await this.makeRequestAsyncOmit({ + method, + bucketName, + query + }, payload); + } + async removeAllBucketNotification(bucketName) { + await this.setBucketNotification(bucketName, new _notification.NotificationConfig()); + } + async getBucketNotification(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + const method = 'GET'; + const query = 'notification'; + const res = await this.makeRequestAsync({ + method, + bucketName, + query + }); + const body = await (0, _response.readAsString)(res); + return (0, xmlParsers.parseBucketNotification)(body); + } + listenBucketNotification(bucketName, prefix, suffix, events) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`); + } + if (!(0, _helper.isString)(prefix)) { + throw new TypeError('prefix must be of type string'); + } + if (!(0, _helper.isString)(suffix)) { + throw new TypeError('suffix must be of type string'); + } + if (!Array.isArray(events)) { + throw new TypeError('events must be of type Array'); + } + const listener = new _notification.NotificationPoller(this, bucketName, prefix, suffix, events); + listener.start(); + return listener; + } +} +exports.TypedClient = TypedClient; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjcnlwdG8iLCJfaW50ZXJvcFJlcXVpcmVXaWxkY2FyZCIsInJlcXVpcmUiLCJmcyIsImh0dHAiLCJodHRwcyIsInBhdGgiLCJzdHJlYW0iLCJhc3luYyIsIl9ibG9ja1N0cmVhbSIsIl9icm93c2VyT3JOb2RlIiwiX2xvZGFzaCIsInFzIiwiX3htbDJqcyIsIl9DcmVkZW50aWFsUHJvdmlkZXIiLCJlcnJvcnMiLCJfaGVscGVycyIsIl9ub3RpZmljYXRpb24iLCJfc2lnbmluZyIsIl9hc3luYzIiLCJfY29weUNvbmRpdGlvbnMiLCJfZXh0ZW5zaW9ucyIsIl9oZWxwZXIiLCJfam9pbkhv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emVzIG9mIGl0cyB1cGxvYWRlZCBwYXJ0c1xuICAgICAgICAgICAgICAvLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgQHR5cGVzY3JpcHQtZXNsaW50L2Jhbi10cy1jb21tZW50XG4gICAgICAgICAgICAgIC8vIEB0cy1pZ25vcmVcbiAgICAgICAgICAgICAgdGhpcy5saXN0UGFydHMoYnVja2V0LCB1cGxvYWQua2V5LCB1cGxvYWQudXBsb2FkSWQpLnRoZW4oXG4gICAgICAgICAgICAgICAgKHBhcnRzOiBQYXJ0W10pID0+IHtcbiAgICAgICAgICAgICAgICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBAdHlwZXNjcmlwdC1lc2xpbnQvYmFuLXRzLWNvbW1lbnRcbiAgICAgICAgICAgICAgICAgIC8vIEB0cy1pZ25vcmVcbiAgICAgICAgICAgICAgICAgIHVwbG9hZC5zaXplID0gcGFydHMucmVkdWNlKChhY2MsIGl0ZW0pID0+IGFjYyArIGl0ZW0uc2l6ZSwgMClcbiAgICAgICAgICAgICAgICAgIHVwbG9hZHMucHVzaCh1cGxvYWQpXG4gICAgICAgICAgICAgICAgICBjYigpXG4gICAgICAgICAgICAgICAgfSxcbiAgICAgICAgICAgICAgICAoZXJyOiBFcnJvcikgPT4gY2IoZXJyKSxcbiAgICAgICAgICAgICAgKVxuICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIChlcnIpID0+IHtcbiAgICAgICAgICAgICAgaWYgKGVycikge1xuICAgICAgICAgICAgICAgIHJlYWRTdHJlYW0uZW1pdCgnZXJyb3InLCBlcnIpXG4gICAgICAgICAgICAgICAgcmV0dXJuXG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgaWYgKHJlc3VsdC5pc1RydW5jYXRlZCkge1xuICAgICAgICAgICAgICAgIGtleU1hcmtlciA9IHJlc3VsdC5uZXh0S2V5TWFya2VyXG4gICAgICAgICAgICAgICAgdXBsb2FkSWRNYXJrZXIgPSByZXN1bH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mRpZ2VzdCgpXG5cbiAgICAgICAgICBjb25zdCBvbGRQYXJ0ID0gb2xkUGFydHNbcGFydE51bWJlcl1cbiAgICAgICAgICBpZiAob2xkUGFydCkge1xuICAgICAgICAgICAgaWYgKG9sZFBhcnQuZXRhZyA9PT0gbWQ1LnRvU3RyaW5nKCdoZXgnKSkge1xuICAgICAgICAgICAgICBlVGFncy5wdXNoKHsgcGFydDogcGFydE51bWJlciwgZXRhZzogb2xkUGFydC5ldGFnIH0pXG4gICAgICAgICAgICAgIHBhcnROdW1iZXIrK1xuICAgICAgICAgICAgICBjb250aW51ZVxuICAgICAgICAgICAgfVxuICAgICAgICAgIH1cblxuICAgICAgICAgIHBhcnROdW1iZXIrK1xuXG4gICAgICAgICAgLy8gbm93IHN0YXJ0IHRvIHVwbG9hZCBtaXNzaW5nIHBhcnRcbiAgICAgICAgICBjb25zdCBvcHRpb25zOiBSZXF1ZXN0T3B0aW9uID0ge1xuICAgICAgICAgICAgbWV0aG9kOiAnUFVUJyxcbiAgICAgICAgICAgIHF1ZXJ5OiBxcy5zdHJpbmdpZnkoeyBwYXJ0TnVtYmVyLCB1cGxvYWRJZCB9KSxcbiAgICAgICAgICAgIGhlYWRlcnM6IHtcbiAgICAgICAgICAgICAgJ0NvbnRlbnQtTGVuZ3RoJzogY2h1bmsubGVuZ3RoLFxuICAgICAgICAgICAgICAnQ29udGVudC1NRDUnOiBtZDUudG9TdHJpbmcoJ2Jhc2U2NCcpLFxuICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIGJ1Y2tldE5hbWUsXG4gICAgICAgICAgICBvYmplY3ROYW1lLFxuICAgICAgICAgIH1cblxuICAgICAgICAgIGNvbnN0IHJlc3BvbnNlID0gYXdhaXQgdGhpcy5tYWtlUmVxdWVzdEFzeW5jT21pdChvcHRpb25zLCBjaHVuaylcblxuICAgICAgICAgIGxldCBldGFnID0gcmVzcG9uc2UuaGVhZGVycy5ldGFnXG4gICAgICAgICAgaWYgKGV0YWcpIHtcbiA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GFsVXBsb2FkcyA9IEFycmF5LmZyb20oc3RhcnRJZHgpXG5cbiAgICAgICAgICBjb25zdCBoZWFkZXJzID0gKHNvdXJjZU9iakxpc3Rbc3BsaXRJbmRleF0gYXMgQ29weVNvdXJjZU9wdGlvbnMpLmdldEhlYWRlcnMoKVxuXG4gICAgICAgICAgdG90YWxVcGxvYWRzLmZvckVhY2goKHNwbGl0U3RhcnQsIHVwbGRDdHJJZHgpID0+IHtcbiAgICAgICAgICAgIGNvbnN0IHNwbGl0RW5kID0gZW5kSWR4W3VwbGRDdHJJZHhdXG5cbiAgICAgICAgICAgIGNvbnN0IHNvdXJjZU9iaiA9IGAke29iakNvbmZpZy5CdWNrZXR9LyR7b2JqQ29uZmlnLk9iamVjdH1gXG4gICAgICAgICAgICBoZWFkZXJzWyd4LWFtei1jb3B5LXNvdXJjZSddID0gYCR7c291cmNlT2JqfWBcbiAgICAgICAgICAgIGhlYWRlcnNbJ3gtYW16LWNvcHktc291cmNlLXJhbmdlJ10gPSBgYnl0ZXM9JHtzcGxpdFN0YXJ0fS0ke3NwbGl0RW5kfWBcblxuICAgICAgICAgICAgY29uc3QgdXBsb2FkUGFydENvbmZpZyA9IHtcbiAgICAgICAgICAgICAgYnVja2V0TmFtZTogZGVzdE9iakNvbmZpZy5CdWNrZXQsXG4gICAgICAgICAgICAgIG9iamVjdE5hbWU6IGRlc3RPYmpDb25maWcuT2JqZWN0LFxuICAgICAgICAgICAgICB1cGxvYWRJRDogdXBsb2FkSWQsXG4gICAgICAgICAgICAgIHBhcnROdW1iZXI6IHBhcnRJbmRleCxcbiAgICAgICAgICAgICAgaGVhZGVyczogaGVhZGVycyxcbiAgICAgICAgICAgICAgc291cmNlT2JqOiBzb3VyY2VPYmosXG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIHVwbG9hZFBhcnRDb25maWdMaXN0LnB1c2godXBsb2FkUGFydENvbmZpZylcbiAgICAgICAgICB9KVxuICAgICAgICB9XG4gICAgICB9KVxuXG4g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mIChvYmplY3RzLmxlbmd0aCkge1xuICAgICAgICByZWFkU3RyZWFtLnB1c2gob2JqZWN0cy5zaGlmdCgpKVxuICAgICAgICByZXR1cm5cbiAgICAgIH1cbiAgICAgIGlmIChlbmRlZCkge1xuICAgICAgICByZXR1cm4gcmVhZFN0cmVhbS5wdXNoKG51bGwpXG4gICAgICB9XG5cbiAgICAgIHRyeSB7XG4gICAgICAgIGNvbnN0IHJlc3VsdCA9IGF3YWl0IHRoaXMubGlzdE9iamVjdHNWMlF1ZXJ5KFxuICAgICAgICAgIGJ1Y2tldE5hbWUsXG4gICAgICAgICAgcHJlZml4U3RyLFxuICAgICAgICAgIGNvbnRpbnVhdGlvblRva2VuLFxuICAgICAgICAgIGRlbGltaXRlcixcbiAgICAgICAgICAxMDAwLFxuICAgICAgICAgIHN0YXJ0QWZ0ZXJTdHIsXG4gICAgICAgIClcbiAgICAgICAgaWYgKHJlc3VsdC5pc1RydW5jYXRlZCkge1xuICAgICAgICAgIGNvbnRpbnVhdGlvblRva2VuID0gcmVzdWx0Lm5leHRDb250aW51YXRpb25Ub2tlblxuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIGVuZGVkID0gdHJ1ZVxuICAgICAgICB9XG4gICAgICAgIG9iamVjdHMgPSByZXN1bHQub2JqZWN0c1xuICAgICAgICAvLyBAdHMtaWdub3JlXG4gICAgICAgIHJlYWRTdHJlYW0uX3JlYWQoKVxuICAgICAgfSBjYXRjaCAoZXJyKSB7XG4gICAgICAgIHJlYWRTdHJlYW0uZW1pdCgnZXJyb3InLCBlcnIpXG4gICAgICB9XG4gICAgfVxuICAgIHJldHVybiByZWFkU3RyZWFtXG4gIH1cblxuICBhc3luYyBzZXRCdWNrZXROb3RpZmljYXRpb24oYnVja2V0TmFtZTogc3RyaW5nLCBjb25maWc6IE5vdGlmaWNhdGlvbkNvbmZpZyk6IFByb21pc2U8dm9pZD4ge1xuICAgIGlmICghaXNWYWxpZEJ1Y2tldE5hbWUoYnVja2V0TmF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pWSxNQUFNLEVBQUVDLE1BQU0sQ0FBQztJQUNqRkMsUUFBUSxDQUFDRSxLQUFLLENBQUMsQ0FBQztJQUNoQixPQUFPRixRQUFRO0VBQ2pCO0FBQ0Y7QUFBQ0csT0FBQSxDQUFBdm1CLFdBQUEsR0FBQUEsV0FBQSJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/copy-conditions.d.ts b/node_modules/minio/dist/main/internal/copy-conditions.d.ts new file mode 100644 index 0000000..f5d6e8b --- /dev/null +++ b/node_modules/minio/dist/main/internal/copy-conditions.d.ts @@ -0,0 +1,10 @@ +export declare class CopyConditions { + modified: string; + unmodified: string; + matchETag: string; + matchETagExcept: string; + setModified(date: Date): void; + setUnmodified(date: Date): void; + setMatchETag(etag: string): void; + setMatchETagExcept(etag: string): void; +} \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/copy-conditions.js b/node_modules/minio/dist/main/internal/copy-conditions.js new file mode 100644 index 0000000..eb4f612 --- /dev/null +++ b/node_modules/minio/dist/main/internal/copy-conditions.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +class CopyConditions { + modified = ''; + unmodified = ''; + matchETag = ''; + matchETagExcept = ''; + setModified(date) { + if (!(date instanceof Date)) { + throw new TypeError('date must be of type Date'); + } + this.modified = date.toUTCString(); + } + setUnmodified(date) { + if (!(date instanceof Date)) { + throw new TypeError('date must be of type Date'); + } + this.unmodified = date.toUTCString(); + } + setMatchETag(etag) { + this.matchETag = etag; + } + setMatchETagExcept(etag) { + this.matchETagExcept = etag; + } +} +exports.CopyConditions = CopyConditions; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDb3B5Q29uZGl0aW9ucyIsIm1vZGlmaWVkIiwidW5tb2RpZmllZCIsIm1hdGNoRVRhZyIsIm1hdGNoRVRhZ0V4Y2VwdCIsInNldE1vZGlmaWVkIiwiZGF0ZSIsIkRhdGU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1xuICB9XG59XG4iXSwibWFwcGluZ3MiOiI7Ozs7O0FBQU8sTUFBTUEsY0FBYyxDQUFDO0VBQ25CQyxRQUFRLEdBQUcsRUFBRTtFQUNiQyxVQUFVLEdBQUcsRUFBRTtFQUNmQyxTQUFTLEdBQUcsRUFBRTtFQUNkQyxlQUFlLEdBQUcsRUFBRTtFQUUzQkMsV0FBV0EsQ0FBQ0MsSUFBVSxFQUFRO0lBQzVCLElBQUksRUFBRUEsSUFBSSxZQUFZQyxJQUFJLENBQUMsRUFBRTtNQUMzQixNQUFNLElBQUlDLFNBQVMsQ0FBQywyQkFBMkIsQ0FBQztJQUNsRDtJQUVBLElBQUksQ0FBQ1AsUUFBUSxHQUFHSyxJQUFJLENBQUNHLFdBQVcsQ0FBQyxDQUFDO0VBQ3BDO0VBRUFDLGFBQWFBLENBQUNKLElBQVUsRUFBUTtJQUM5QixJQUFJLEVBQUVBLElBQUksWUFBWUMsSUFBSSxDQUFDLEVBQUU7TUFDM0IsTUFBTSxJQUFJQyxTQUFTLENBQUMsMkJBQTJCLENBQUM7SUFDbEQ7SUFFQSxJQUFJLENBQUNOLFVBQVUsR0FBR0ksSUFBSSxDQUFDRyxXQUFXLENBQUMsQ0FBQztFQUN0QztFQUVBRSxZQUFZQSxDQUFDQyxJQUFZLEVBQVE7SUFDL0IsSUFBSSxDQUFDVCxTQUFTLEdBQUdTLElBQUk7RUFDdkI7RUFFQUMsa0JBQWtCQSxDQUFDRCxJQUFZLEVBQVE7SUFDckMsSUFBSSxDQUFDUixlQUFlLEdBQUdRLElBQUk7RUFDN0I7QUFDRjtBQUFDRSxPQUFBLENBQUFkLGNBQUEsR0FBQUEsY0FBQSJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/extensions.d.ts b/node_modules/minio/dist/main/internal/extensions.d.ts new file mode 100644 index 0000000..b3b73d1 --- /dev/null +++ b/node_modules/minio/dist/main/internal/extensions.d.ts @@ -0,0 +1,18 @@ +import type { TypedClient } from "./client.js"; +import type { BucketItemWithMetadata, BucketStream } from "./type.js"; +export declare class Extensions { + private readonly client; + constructor(client: TypedClient); + /** + * List the objects in the bucket using S3 ListObjects V2 With Metadata + * + * @param bucketName - name of the bucket + * @param prefix - the prefix of the objects that should be listed (optional, default `''`) + * @param recursive - `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'. (optional, default `false`) + * @param startAfter - Specifies the key to start after when listing objects in a bucket. (optional, default `''`) + * @returns stream emitting the objects in the bucket, the object is of the format: + */ + listObjectsV2WithMetadata(bucketName: string, prefix?: string, recursive?: boolean, startAfter?: string): BucketStream; + private listObjectsV2WithMetadataGen; + private listObjectsV2WithMetadataQuery; +} \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/extensions.js b/node_modules/minio/dist/main/internal/extensions.js new file mode 100644 index 0000000..ba602ce --- /dev/null +++ b/node_modules/minio/dist/main/internal/extensions.js @@ -0,0 +1,121 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var stream = _interopRequireWildcard(require("stream"), true); +var errors = _interopRequireWildcard(require("../errors.js"), true); +var _helper = require("./helper.js"); +var _response = require("./response.js"); +var _xmlParser = require("./xml-parser.js"); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2020 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Extensions { + constructor(client) { + this.client = client; + } + + /** + * List the objects in the bucket using S3 ListObjects V2 With Metadata + * + * @param bucketName - name of the bucket + * @param prefix - the prefix of the objects that should be listed (optional, default `''`) + * @param recursive - `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'. (optional, default `false`) + * @param startAfter - Specifies the key to start after when listing objects in a bucket. (optional, default `''`) + * @returns stream emitting the objects in the bucket, the object is of the format: + */ + listObjectsV2WithMetadata(bucketName, prefix, recursive, startAfter) { + if (prefix === undefined) { + prefix = ''; + } + if (recursive === undefined) { + recursive = false; + } + if (startAfter === undefined) { + startAfter = ''; + } + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName); + } + if (!(0, _helper.isValidPrefix)(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`); + } + if (!(0, _helper.isString)(prefix)) { + throw new TypeError('prefix should be of type "string"'); + } + if (!(0, _helper.isBoolean)(recursive)) { + throw new TypeError('recursive should be of type "boolean"'); + } + if (!(0, _helper.isString)(startAfter)) { + throw new TypeError('startAfter should be of type "string"'); + } + + // if recursive is false set delimiter to '/' + const delimiter = recursive ? '' : '/'; + return stream.Readable.from(this.listObjectsV2WithMetadataGen(bucketName, prefix, delimiter, startAfter), { + objectMode: true + }); + } + async *listObjectsV2WithMetadataGen(bucketName, prefix, delimiter, startAfter) { + let ended = false; + let continuationToken = ''; + do { + const result = await this.listObjectsV2WithMetadataQuery(bucketName, prefix, continuationToken, delimiter, startAfter); + ended = !result.isTruncated; + continuationToken = result.nextContinuationToken; + for (const obj of result.objects) { + yield obj; + } + } while (!ended); + } + async listObjectsV2WithMetadataQuery(bucketName, prefix, continuationToken, delimiter, startAfter) { + const queries = []; + + // Call for listing objects v2 API + queries.push(`list-type=2`); + queries.push(`encoding-type=url`); + // escape every value in query string, except maxKeys + queries.push(`prefix=${(0, _helper.uriEscape)(prefix)}`); + queries.push(`delimiter=${(0, _helper.uriEscape)(delimiter)}`); + queries.push(`metadata=true`); + if (continuationToken) { + continuationToken = (0, _helper.uriEscape)(continuationToken); + queries.push(`continuation-token=${continuationToken}`); + } + // Set start-after + if (startAfter) { + startAfter = (0, _helper.uriEscape)(startAfter); + queries.push(`start-after=${startAfter}`); + } + queries.push(`max-keys=1000`); + queries.sort(); + let query = ''; + if (queries.length > 0) { + query = `${queries.join('&')}`; + } + const method = 'GET'; + const res = await this.client.makeRequestAsync({ + method, + bucketName, + query + }); + return (0, _xmlParser.parseListObjectsV2WithMetadata)(await (0, _response.readAsString)(res)); + } +} +exports.Extensions = Extensions; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJzdHJlYW0iLCJfaW50ZXJvcFJlcXVpcmVXaWxkY2FyZCIsInJlcXVpcmUiLCJlcnJvcnMiLCJfaGVscGVyIiwiX3Jlc3BvbnNlIiwiX3htbFBhcnNlciIsImUiLCJ0IiwiV2Vha01hcCIsInIiLCJuIiwiX19lc01vZHVsZSIsIm8iLCJpIiwiZiIsIl9fcHJvdG9fXyIsImRlZmF1bHQiLCJoYXMiLCJnZXQiLCJzZXQiLCJoYXNPd25Qcm9wZXJ0eSIsImNhbGwiLCJPYmplY3QiLCJkZWZpbmVQcm9wZXJ0eSIsImdldE93blByb3BlcnR5RGVzY3JpcHRvciIsIkV4dGVuc2lvbnMiLCJjb25zdHJ1Y3RvciIsImNsaWVudCIsImxpc3RPYmplY3RzVjJXaXRoTWV0YWRhdGEiLCJidWNrZXROYW1lIiwicHJlZml4IiwicmVjdXJzaXZlIiwic3RhcnRBZnRlciIsInVuZGVmaW5lZCIsImlzVmFsaWRCdWNrZXROYW1lIiwiSW52YWxpZEJ1Y2tldE5hbW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BCLE1BQU1DLEdBQUcsR0FBRyxNQUFNLElBQUksQ0FBQ25DLE1BQU0sQ0FBQ29DLGdCQUFnQixDQUFDO01BQUVGLE1BQU07TUFBRWhDLFVBQVU7TUFBRTZCO0lBQU0sQ0FBQyxDQUFDO0lBQzdFLE9BQU8sSUFBQU0seUNBQThCLEVBQUMsTUFBTSxJQUFBQyxzQkFBWSxFQUFDSCxHQUFHLENBQUMsQ0FBQztFQUNoRTtBQUNGO0FBQUNJLE9BQUEsQ0FBQXpDLFVBQUEsR0FBQUEsVUFBQSJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/helper.d.ts b/node_modules/minio/dist/main/internal/helper.d.ts new file mode 100644 index 0000000..961c8ae --- /dev/null +++ b/node_modules/minio/dist/main/internal/helper.d.ts @@ -0,0 +1,177 @@ +/// +/// +import * as stream from 'node:stream'; +import _ from 'lodash'; +import type { Binary, Encryption, ObjectMetaData, RequestHeaders, ResponseHeader } from "./type.js"; +export declare function hashBinary(buf: Buffer, enableSHA256: boolean): { + md5sum: string; + sha256sum: string; +}; +export declare function uriEscape(uriStr: string): string; +export declare function uriResourceEscape(string: string): string; +export declare function getScope(region: string, date: Date, serviceName?: string): string; +/** + * isAmazonEndpoint - true if endpoint is 's3.amazonaws.com' or 's3.cn-north-1.amazonaws.com.cn' + */ +export declare function isAmazonEndpoint(endpoint: string): boolean; +/** + * isVirtualHostStyle - verify if bucket name is support with virtual + * hosts. bucketNames with periods should be always treated as path + * style if the protocol is 'https:', this is due to SSL wildcard + * limitation. For all other buckets and Amazon S3 endpoint we will + * default to virtual host style. + */ +export declare function isVirtualHostStyle(endpoint: string, protocol: string, bucket: string, pathStyle: boolean): boolean; +export declare function isValidIP(ip: string): boolean; +/** + * @returns if endpoint is valid domain. + */ +export declare function isValidEndpoint(endpoint: string): boolean; +/** + * @returns if input host is a valid domain. + */ +export declare function isValidDomain(host: string): boolean; +/** + * Probes contentType using file extensions. + * + * @example + * ``` + * // return 'image/png' + * probeContentType('file.png') + * ``` + */ +export declare function probeContentType(path: string): string; +/** + * is input port valid. + */ +export declare function isValidPort(port: unknown): port is number; +export declare function isValidBucketName(bucket: unknown): boolean; +/** + * check if objectName is a valid object name + */ +export declare function isValidObjectName(objectName: unknown): boolean; +/** + * check if prefix is valid + */ +export declare function isValidPrefix(prefix: unknown): prefix is string; +/** + * check if typeof arg number + */ +export declare function isNumber(arg: unknown): arg is number; +export type AnyFunction = (...args: any[]) => any; +/** + * check if typeof arg function + */ +export declare function isFunction(arg: unknown): arg is AnyFunction; +/** + * check if typeof arg string + */ +export declare function isString(arg: unknown): arg is string; +/** + * check if typeof arg object + */ +export declare function isObject(arg: unknown): arg is object; +/** + * check if typeof arg is plain object + */ +export declare function isPlainObject(arg: unknown): arg is Record; +/** + * check if object is readable stream + */ +export declare function isReadableStream(arg: unknown): arg is stream.Readable; +/** + * check if arg is boolean + */ +export declare function isBoolean(arg: unknown): arg is boolean; +export declare function isEmpty(o: unknown): o is null | undefined; +export declare function isEmptyObject(o: Record): boolean; +export declare function isDefined(o: T): o is Exclude; +/** + * check if arg is a valid date + */ +export declare function isValidDate(arg: unknown): arg is Date; +/** + * Create a Date string with format: 'YYYYMMDDTHHmmss' + Z + */ +export declare function makeDateLong(date?: Date): string; +/** + * Create a Date string with format: 'YYYYMMDD' + */ +export declare function makeDateShort(date?: Date): string; +/** + * pipesetup sets up pipe() from left to right os streams array + * pipesetup will also make sure that error emitted at any of the upstream Stream + * will be emitted at the last stream. This makes error handling simple + */ +export declare function pipesetup(...streams: [stream.Readable, ...stream.Duplex[], stream.Writable]): stream.Readable | stream.Duplex | stream.Writable; +/** + * return a Readable stream that emits data + */ +export declare function readableStream(data: unknown): stream.Readable; +/** + * Process metadata to insert appropriate value to `content-type` attribute + */ +export declare function insertContentType(metaData: ObjectMetaData, filePath: string): ObjectMetaData; +/** + * Function prepends metadata with the appropriate prefix if it is not already on + */ +export declare function prependXAMZMeta(metaData?: ObjectMetaData): RequestHeaders; +/** + * Checks if it is a valid header according to the AmazonS3 API + */ +export declare function isAmzHeader(key: string): boolean; +/** + * Checks if it is a supported Header + */ +export declare function isSupportedHeader(key: string): boolean; +/** + * Checks if it is a storage header + */ +export declare function isStorageClassHeader(key: string): boolean; +export declare function extractMetadata(headers: ResponseHeader): _.Dictionary; +export declare function getVersionId(headers?: ResponseHeader): string | null; +export declare function getSourceVersionId(headers?: ResponseHeader): string | null; +export declare function sanitizeETag(etag?: string): string; +export declare function toMd5(payload: Binary): string; +export declare function toSha256(payload: Binary): string; +/** + * toArray returns a single element array with param being the element, + * if param is just a string, and returns 'param' back if it is an array + * So, it makes sure param is always an array + */ +export declare function toArray(param: T | T[]): Array; +export declare function sanitizeObjectKey(objectName: string): string; +export declare function sanitizeSize(size?: string): number | undefined; +export declare const PART_CONSTRAINTS: { + ABS_MIN_PART_SIZE: number; + MIN_PART_SIZE: number; + MAX_PARTS_COUNT: number; + MAX_PART_SIZE: number; + MAX_SINGLE_PUT_OBJECT_SIZE: number; + MAX_MULTIPART_PUT_OBJECT_SIZE: number; +}; +/** + * Return Encryption headers + * @param encConfig + * @returns an object with key value pairs that can be used in headers. + */ +export declare function getEncryptionHeaders(encConfig: Encryption): RequestHeaders; +export declare function partsRequired(size: number): number; +/** + * calculateEvenSplits - computes splits for a source and returns + * start and end index slices. Splits happen evenly to be sure that no + * part is less than 5MiB, as that could fail the multipart request if + * it is not the last part. + */ +export declare function calculateEvenSplits(size: number, objInfo: T): { + startIndex: number[]; + objInfo: T; + endIndex: number[]; +} | null; +export declare function parseXml(xml: string): any; +/** + * get content size of object content to upload + */ +export declare function getContentLength(s: stream.Readable | Buffer | string): Promise; \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/helper.js b/node_modules/minio/dist/main/internal/helper.js new file mode 100644 index 0000000..a61f5b2 --- /dev/null +++ b/node_modules/minio/dist/main/internal/helper.js @@ -0,0 +1,607 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.calculateEvenSplits = calculateEvenSplits; +exports.extractMetadata = extractMetadata; +exports.getContentLength = getContentLength; +exports.getEncryptionHeaders = getEncryptionHeaders; +exports.getScope = getScope; +exports.getSourceVersionId = getSourceVersionId; +exports.getVersionId = getVersionId; +exports.hashBinary = hashBinary; +exports.insertContentType = insertContentType; +exports.isAmazonEndpoint = isAmazonEndpoint; +exports.isAmzHeader = isAmzHeader; +exports.isBoolean = isBoolean; +exports.isDefined = isDefined; +exports.isEmpty = isEmpty; +exports.isEmptyObject = isEmptyObject; +exports.isFunction = isFunction; +exports.isNumber = isNumber; +exports.isObject = isObject; +exports.isPlainObject = isPlainObject; +exports.isReadableStream = isReadableStream; +exports.isStorageClassHeader = isStorageClassHeader; +exports.isString = isString; +exports.isSupportedHeader = isSupportedHeader; +exports.isValidBucketName = isValidBucketName; +exports.isValidDate = isValidDate; +exports.isValidDomain = isValidDomain; +exports.isValidEndpoint = isValidEndpoint; +exports.isValidIP = isValidIP; +exports.isValidObjectName = isValidObjectName; +exports.isValidPort = isValidPort; +exports.isValidPrefix = isValidPrefix; +exports.isVirtualHostStyle = isVirtualHostStyle; +exports.makeDateLong = makeDateLong; +exports.makeDateShort = makeDateShort; +exports.parseXml = parseXml; +exports.partsRequired = partsRequired; +exports.pipesetup = pipesetup; +exports.prependXAMZMeta = prependXAMZMeta; +exports.probeContentType = probeContentType; +exports.readableStream = readableStream; +exports.sanitizeETag = sanitizeETag; +exports.sanitizeObjectKey = sanitizeObjectKey; +exports.sanitizeSize = sanitizeSize; +exports.toArray = toArray; +exports.toMd5 = toMd5; +exports.toSha256 = toSha256; +exports.uriEscape = uriEscape; +exports.uriResourceEscape = uriResourceEscape; +var crypto = _interopRequireWildcard(require("crypto"), true); +var stream = _interopRequireWildcard(require("stream"), true); +var _fastXmlParser = require("fast-xml-parser"); +var _ipaddr = require("ipaddr.js"); +var _lodash = require("lodash"); +var mime = _interopRequireWildcard(require("mime-types"), true); +var _async = require("./async.js"); +var _type = require("./type.js"); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const MetaDataHeaderPrefix = 'x-amz-meta-'; +function hashBinary(buf, enableSHA256) { + let sha256sum = ''; + if (enableSHA256) { + sha256sum = crypto.createHash('sha256').update(buf).digest('hex'); + } + const md5sum = crypto.createHash('md5').update(buf).digest('base64'); + return { + md5sum, + sha256sum + }; +} + +// S3 percent-encodes some extra non-standard characters in a URI . So comply with S3. +const encodeAsHex = c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; +function uriEscape(uriStr) { + return encodeURIComponent(uriStr).replace(/[!'()*]/g, encodeAsHex); +} +function uriResourceEscape(string) { + return uriEscape(string).replace(/%2F/g, '/'); +} +function getScope(region, date, serviceName = 's3') { + return `${makeDateShort(date)}/${region}/${serviceName}/aws4_request`; +} + +/** + * isAmazonEndpoint - true if endpoint is 's3.amazonaws.com' or 's3.cn-north-1.amazonaws.com.cn' + */ +function isAmazonEndpoint(endpoint) { + return endpoint === 's3.amazonaws.com' || endpoint === 's3.cn-north-1.amazonaws.com.cn'; +} + +/** + * isVirtualHostStyle - verify if bucket name is support with virtual + * hosts. bucketNames with periods should be always treated as path + * style if the protocol is 'https:', this is due to SSL wildcard + * limitation. For all other buckets and Amazon S3 endpoint we will + * default to virtual host style. + */ +function isVirtualHostStyle(endpoint, protocol, bucket, pathStyle) { + if (protocol === 'https:' && bucket.includes('.')) { + return false; + } + return isAmazonEndpoint(endpoint) || !pathStyle; +} +function isValidIP(ip) { + return _ipaddr.isValid(ip); +} + +/** + * @returns if endpoint is valid domain. + */ +function isValidEndpoint(endpoint) { + return isValidDomain(endpoint) || isValidIP(endpoint); +} + +/** + * @returns if input host is a valid domain. + */ +function isValidDomain(host) { + if (!isString(host)) { + return false; + } + // See RFC 1035, RFC 3696. + if (host.length === 0 || host.length > 255) { + return false; + } + // Host cannot start or end with a '-' + if (host[0] === '-' || host.slice(-1) === '-') { + return false; + } + // Host cannot start or end with a '_' + if (host[0] === '_' || host.slice(-1) === '_') { + return false; + } + // Host cannot start with a '.' + if (host[0] === '.') { + return false; + } + const nonAlphaNumerics = '`~!@#$%^&*()+={}[]|\\"\';:> 63) { + return false; + } + // bucket with successive periods is invalid. + if (bucket.includes('..')) { + return false; + } + // bucket cannot have ip address style. + if (/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/.test(bucket)) { + return false; + } + // bucket should begin with alphabet/number and end with alphabet/number, + // with alphabet/number/.- in the middle. + if (/^[a-z0-9][a-z0-9.-]+[a-z0-9]$/.test(bucket)) { + return true; + } + return false; +} + +/** + * check if objectName is a valid object name + */ +function isValidObjectName(objectName) { + if (!isValidPrefix(objectName)) { + return false; + } + return objectName.length !== 0; +} + +/** + * check if prefix is valid + */ +function isValidPrefix(prefix) { + if (!isString(prefix)) { + return false; + } + if (prefix.length > 1024) { + return false; + } + return true; +} + +/** + * check if typeof arg number + */ +function isNumber(arg) { + return typeof arg === 'number'; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any + +/** + * check if typeof arg function + */ +function isFunction(arg) { + return typeof arg === 'function'; +} + +/** + * check if typeof arg string + */ +function isString(arg) { + return typeof arg === 'string'; +} + +/** + * check if typeof arg object + */ +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +/** + * check if typeof arg is plain object + */ +function isPlainObject(arg) { + return Object.prototype.toString.call(arg) === '[object Object]'; +} +/** + * check if object is readable stream + */ +function isReadableStream(arg) { + // eslint-disable-next-line @typescript-eslint/unbound-method + return isObject(arg) && isFunction(arg._read); +} + +/** + * check if arg is boolean + */ +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +function isEmpty(o) { + return _lodash.isEmpty(o); +} +function isEmptyObject(o) { + return Object.values(o).filter(x => x !== undefined).length !== 0; +} +function isDefined(o) { + return o !== null && o !== undefined; +} + +/** + * check if arg is a valid date + */ +function isValidDate(arg) { + // @ts-expect-error checknew Date(Math.NaN) + return arg instanceof Date && !isNaN(arg); +} + +/** + * Create a Date string with format: 'YYYYMMDDTHHmmss' + Z + */ +function makeDateLong(date) { + date = date || new Date(); + + // Gives format like: '2017-08-07T16:28:59.889Z' + const s = date.toISOString(); + return s.slice(0, 4) + s.slice(5, 7) + s.slice(8, 13) + s.slice(14, 16) + s.slice(17, 19) + 'Z'; +} + +/** + * Create a Date string with format: 'YYYYMMDD' + */ +function makeDateShort(date) { + date = date || new Date(); + + // Gives format like: '2017-08-07T16:28:59.889Z' + const s = date.toISOString(); + return s.slice(0, 4) + s.slice(5, 7) + s.slice(8, 10); +} + +/** + * pipesetup sets up pipe() from left to right os streams array + * pipesetup will also make sure that error emitted at any of the upstream Stream + * will be emitted at the last stream. This makes error handling simple + */ +function pipesetup(...streams) { + // @ts-expect-error ts can't narrow this + return streams.reduce((src, dst) => { + src.on('error', err => dst.emit('error', err)); + return src.pipe(dst); + }); +} + +/** + * return a Readable stream that emits data + */ +function readableStream(data) { + const s = new stream.Readable(); + s._read = () => {}; + s.push(data); + s.push(null); + return s; +} + +/** + * Process metadata to insert appropriate value to `content-type` attribute + */ +function insertContentType(metaData, filePath) { + // check if content-type attribute present in metaData + for (const key in metaData) { + if (key.toLowerCase() === 'content-type') { + return metaData; + } + } + + // if `content-type` attribute is not present in metadata, then infer it from the extension in filePath + return { + ...metaData, + 'content-type': probeContentType(filePath) + }; +} + +/** + * Function prepends metadata with the appropriate prefix if it is not already on + */ +function prependXAMZMeta(metaData) { + if (!metaData) { + return {}; + } + return _lodash.mapKeys(metaData, (value, key) => { + if (isAmzHeader(key) || isSupportedHeader(key) || isStorageClassHeader(key)) { + return key; + } + return MetaDataHeaderPrefix + key; + }); +} + +/** + * Checks if it is a valid header according to the AmazonS3 API + */ +function isAmzHeader(key) { + const temp = key.toLowerCase(); + return temp.startsWith(MetaDataHeaderPrefix) || temp === 'x-amz-acl' || temp.startsWith('x-amz-server-side-encryption-') || temp === 'x-amz-server-side-encryption'; +} + +/** + * Checks if it is a supported Header + */ +function isSupportedHeader(key) { + const supported_headers = ['content-type', 'cache-control', 'content-encoding', 'content-disposition', 'content-language', 'x-amz-website-redirect-location', 'if-none-match', 'if-match']; + return supported_headers.includes(key.toLowerCase()); +} + +/** + * Checks if it is a storage header + */ +function isStorageClassHeader(key) { + return key.toLowerCase() === 'x-amz-storage-class'; +} +function extractMetadata(headers) { + return _lodash.mapKeys(_lodash.pickBy(headers, (value, key) => isSupportedHeader(key) || isStorageClassHeader(key) || isAmzHeader(key)), (value, key) => { + const lower = key.toLowerCase(); + if (lower.startsWith(MetaDataHeaderPrefix)) { + return lower.slice(MetaDataHeaderPrefix.length); + } + return key; + }); +} +function getVersionId(headers = {}) { + return headers['x-amz-version-id'] || null; +} +function getSourceVersionId(headers = {}) { + return headers['x-amz-copy-source-version-id'] || null; +} +function sanitizeETag(etag = '') { + const replaceChars = { + '"': '', + '"': '', + '"': '', + '"': '', + '"': '' + }; + return etag.replace(/^("|"|")|("|"|")$/g, m => replaceChars[m]); +} +function toMd5(payload) { + // use string from browser and buffer from nodejs + // browser support is tested only against minio server + return crypto.createHash('md5').update(Buffer.from(payload)).digest().toString('base64'); +} +function toSha256(payload) { + return crypto.createHash('sha256').update(payload).digest('hex'); +} + +/** + * toArray returns a single element array with param being the element, + * if param is just a string, and returns 'param' back if it is an array + * So, it makes sure param is always an array + */ +function toArray(param) { + if (!Array.isArray(param)) { + return [param]; + } + return param; +} +function sanitizeObjectKey(objectName) { + // + symbol characters are not decoded as spaces in JS. so replace them first and decode to get the correct result. + const asStrName = (objectName ? objectName.toString() : '').replace(/\+/g, ' '); + return decodeURIComponent(asStrName); +} +function sanitizeSize(size) { + return size ? Number.parseInt(size) : undefined; +} +const PART_CONSTRAINTS = { + // absMinPartSize - absolute minimum part size (5 MiB) + ABS_MIN_PART_SIZE: 1024 * 1024 * 5, + // MIN_PART_SIZE - minimum part size 16MiB per object after which + MIN_PART_SIZE: 1024 * 1024 * 16, + // MAX_PARTS_COUNT - maximum number of parts for a single multipart session. + MAX_PARTS_COUNT: 10000, + // MAX_PART_SIZE - maximum part size 5GiB for a single multipart upload + // operation. + MAX_PART_SIZE: 1024 * 1024 * 1024 * 5, + // MAX_SINGLE_PUT_OBJECT_SIZE - maximum size 5GiB of object per PUT + // operation. + MAX_SINGLE_PUT_OBJECT_SIZE: 1024 * 1024 * 1024 * 5, + // MAX_MULTIPART_PUT_OBJECT_SIZE - maximum size 5TiB of object for + // Multipart operation. + MAX_MULTIPART_PUT_OBJECT_SIZE: 1024 * 1024 * 1024 * 1024 * 5 +}; +exports.PART_CONSTRAINTS = PART_CONSTRAINTS; +const GENERIC_SSE_HEADER = 'X-Amz-Server-Side-Encryption'; +const ENCRYPTION_HEADERS = { + // sseGenericHeader is the AWS SSE header used for SSE-S3 and SSE-KMS. + sseGenericHeader: GENERIC_SSE_HEADER, + // sseKmsKeyID is the AWS SSE-KMS key id. + sseKmsKeyID: GENERIC_SSE_HEADER + '-Aws-Kms-Key-Id' +}; + +/** + * Return Encryption headers + * @param encConfig + * @returns an object with key value pairs that can be used in headers. + */ +function getEncryptionHeaders(encConfig) { + const encType = encConfig.type; + if (!isEmpty(encType)) { + if (encType === _type.ENCRYPTION_TYPES.SSEC) { + return { + [ENCRYPTION_HEADERS.sseGenericHeader]: 'AES256' + }; + } else if (encType === _type.ENCRYPTION_TYPES.KMS) { + return { + [ENCRYPTION_HEADERS.sseGenericHeader]: encConfig.SSEAlgorithm, + [ENCRYPTION_HEADERS.sseKmsKeyID]: encConfig.KMSMasterKeyID + }; + } + } + return {}; +} +function partsRequired(size) { + const maxPartSize = PART_CONSTRAINTS.MAX_MULTIPART_PUT_OBJECT_SIZE / (PART_CONSTRAINTS.MAX_PARTS_COUNT - 1); + let requiredPartSize = size / maxPartSize; + if (size % maxPartSize > 0) { + requiredPartSize++; + } + requiredPartSize = Math.trunc(requiredPartSize); + return requiredPartSize; +} + +/** + * calculateEvenSplits - computes splits for a source and returns + * start and end index slices. Splits happen evenly to be sure that no + * part is less than 5MiB, as that could fail the multipart request if + * it is not the last part. + */ +function calculateEvenSplits(size, objInfo) { + if (size === 0) { + return null; + } + const reqParts = partsRequired(size); + const startIndexParts = []; + const endIndexParts = []; + let start = objInfo.Start; + if (isEmpty(start) || start === -1) { + start = 0; + } + const divisorValue = Math.trunc(size / reqParts); + const reminderValue = size % reqParts; + let nextStart = start; + for (let i = 0; i < reqParts; i++) { + let curPartSize = divisorValue; + if (i < reminderValue) { + curPartSize++; + } + const currentStart = nextStart; + const currentEnd = currentStart + curPartSize - 1; + nextStart = currentEnd + 1; + startIndexParts.push(currentStart); + endIndexParts.push(currentEnd); + } + return { + startIndex: startIndexParts, + endIndex: endIndexParts, + objInfo: objInfo + }; +} +const fxp = new _fastXmlParser.XMLParser({ + numberParseOptions: { + eNotation: false, + hex: true, + leadingZeros: true + } +}); + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function parseXml(xml) { + const result = fxp.parse(xml); + if (result.Error) { + throw result.Error; + } + return result; +} + +/** + * get content size of object content to upload + */ +async function getContentLength(s) { + // use length property of string | Buffer + if (typeof s === 'string' || Buffer.isBuffer(s)) { + return s.length; + } + + // property of `fs.ReadStream` + const filePath = s.path; + if (filePath && typeof filePath === 'string') { + const stat = await _async.fsp.lstat(filePath); + return stat.size; + } + + // property of `fs.ReadStream` + const fd = s.fd; + if (fd && typeof fd === 'number') { + const stat = await (0, _async.fstat)(fd); + return stat.size; + } + return null; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjcnlwdG8iLCJfaW50ZXJvcFJlcXVpcmVXaWxkY2FyZCIsInJlcXVpcmUiLCJzdHJlYW0iLCJfZmFzdFhtbFBhcnNlciIsIl9pcGFkZHIiLCJfbG9kYXNoIiwibWltZSIsIl9hc3luYyIsIl90eXBlIiwiZSIsInQiLCJXZWFrTWFwIiwiciIsIm4iLCJfX2VzTW9kdWxlIiwibyIsImkiLCJmIiwiX19wcm90b19fIiwiZGVmYXVsdCIsImhhcyIsImdldCIsInNldCIsImhhc093blByb3BlcnR5IiwiY2FsbCIsIk9iamVjdCIsImRlZmluZVByb3BlcnR5IiwiZ2V0T3duUHJvcGVydHlEZXNjcmlwdG9yIiwiTWV0YURhdGFIZWFkZXJQcmVmaXgiLCJoYXNoQmluYXJ5IiwiYnVmIiwiZW5hYmxlU0hBMjU2Iiwic2hhMjU2c3VtIiwiY3JlYXRlSGFzaCIsInVwZGF0ZSIsImRpZ2VzdCIsIm1kNXN1bSIsImVuY29kZUFzSGV4IiwiYyIsImNoYXJDb2RlQXQiLCJ0b1N0cmluZyIsInRvVXBwZXJDYXNlIiwidXJpRXNjYXBlIiwidXJpU3RyIiwiZW5jb2RlVVJJQ29tcG9uZW50IiwicmVwbGFjZSIsInVyaVJlc291cmNlRXNjYXBlIiwic3RyaW5nIiwiZ2V0U2NvcGUiLCJyZWdpb24iLCJkYXRlIiwic2VydmljZU5hbWUiLCJtYWtlRGF0ZVNob3J0IiwiaXNBbWF6b25FbmRwb2ludCIsImVuZHBvaW50IiwiaXNWaXJ0dWFsSG9zdFN0eWxlIiwicHJvdG9jb2wiLCJidWN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UFDQyxLQUFLLENBQUM3RixRQUFRLENBQUM7SUFDdEMsT0FBTzJGLElBQUksQ0FBQ3hELElBQUk7RUFDbEI7O0VBRUE7RUFDQSxNQUFNMkQsRUFBRSxHQUFJL0csQ0FBQyxDQUF3QytHLEVBQStCO0VBQ3BGLElBQUlBLEVBQUUsSUFBSSxPQUFPQSxFQUFFLEtBQUssUUFBUSxFQUFFO0lBQ2hDLE1BQU1ILElBQUksR0FBRyxNQUFNLElBQUFJLFlBQUssRUFBQ0QsRUFBRSxDQUFDO0lBQzVCLE9BQU9ILElBQUksQ0FBQ3hELElBQUk7RUFDbEI7RUFFQSxPQUFPLElBQUk7QUFDYiJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/join-host-port.d.ts b/node_modules/minio/dist/main/internal/join-host-port.d.ts new file mode 100644 index 0000000..51bf708 --- /dev/null +++ b/node_modules/minio/dist/main/internal/join-host-port.d.ts @@ -0,0 +1,11 @@ +/** + * joinHostPort combines host and port into a network address of the + * form "host:port". If host contains a colon, as found in literal + * IPv6 addresses, then JoinHostPort returns "[host]:port". + * + * @param host + * @param port + * @returns Cleaned up host + * @internal + */ +export declare function joinHostPort(host: string, port?: number): string; \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/join-host-port.js b/node_modules/minio/dist/main/internal/join-host-port.js new file mode 100644 index 0000000..114bb52 --- /dev/null +++ b/node_modules/minio/dist/main/internal/join-host-port.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.joinHostPort = joinHostPort; +/** + * joinHostPort combines host and port into a network address of the + * form "host:port". If host contains a colon, as found in literal + * IPv6 addresses, then JoinHostPort returns "[host]:port". + * + * @param host + * @param port + * @returns Cleaned up host + * @internal + */ +function joinHostPort(host, port) { + if (port === undefined) { + return host; + } + + // We assume that host is a literal IPv6 address if host has + // colons. + if (host.includes(':')) { + return `[${host}]:${port.toString()}`; + } + return `${host}:${port.toString()}`; +} +//# sourceMappingURL=data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NBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNPLFNBQVNBLFlBQVlBLENBQUNDLElBQVksRUFBRUMsSUFBYSxFQUFVO0VBQ2hFLElBQUlBLElBQUksS0FBS0MsU0FBUyxFQUFFO0lBQ3RCLE9BQU9GLElBQUk7RUFDYjs7RUFFQTtFQUNBO0VBQ0EsSUFBSUEsSUFBSSxDQUFDRyxRQUFRLENBQUMsR0FBRyxDQUFDLEVBQUU7SUFDdEIsT0FBUSxJQUFHSCxJQUFLLEtBQUlDLElBQUksQ0FBQ0csUUFBUSxDQUFDLENBQUUsRUFBQztFQUN2QztFQUVBLE9BQVEsR0FBRUosSUFBSyxJQUFHQyxJQUFJLENBQUNHLFFBQVEsQ0FBQyxDQUFFLEVBQUM7QUFDckMifQ== \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/post-policy.d.ts b/node_modules/minio/dist/main/internal/post-policy.d.ts new file mode 100644 index 0000000..a92f82c --- /dev/null +++ b/node_modules/minio/dist/main/internal/post-policy.d.ts @@ -0,0 +1,17 @@ +import type { ObjectMetaData } from "./type.js"; +export declare class PostPolicy { + policy: { + conditions: (string | number)[][]; + expiration?: string; + }; + formData: Record; + setExpires(date: Date): void; + setKey(objectName: string): void; + setKeyStartsWith(prefix: string): void; + setBucket(bucketName: string): void; + setContentType(type: string): void; + setContentTypeStartsWith(prefix: string): void; + setContentDisposition(value: string): void; + setContentLengthRange(min: number, max: number): void; + setUserMetaData(metaData: ObjectMetaData): void; +} \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/post-policy.js b/node_modules/minio/dist/main/internal/post-policy.js new file mode 100644 index 0000000..0629e69 --- /dev/null +++ b/node_modules/minio/dist/main/internal/post-policy.js @@ -0,0 +1,106 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var errors = _interopRequireWildcard(require("../errors.js"), true); +var _helper = require("./helper.js"); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +// Build PostPolicy object that can be signed by presignedPostPolicy + +class PostPolicy { + policy = { + conditions: [] + }; + formData = {}; + + // set expiration date + setExpires(date) { + if (!date) { + throw new errors.InvalidDateError('Invalid date: cannot be null'); + } + this.policy.expiration = date.toISOString(); + } + + // set object name + setKey(objectName) { + if (!(0, _helper.isValidObjectName)(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name : ${objectName}`); + } + this.policy.conditions.push(['eq', '$key', objectName]); + this.formData.key = objectName; + } + + // set object name prefix, i.e policy allows any keys with this prefix + setKeyStartsWith(prefix) { + if (!(0, _helper.isValidPrefix)(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`); + } + this.policy.conditions.push(['starts-with', '$key', prefix]); + this.formData.key = prefix; + } + + // set bucket name + setBucket(bucketName) { + if (!(0, _helper.isValidBucketName)(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name : ${bucketName}`); + } + this.policy.conditions.push(['eq', '$bucket', bucketName]); + this.formData.bucket = bucketName; + } + + // set Content-Type + setContentType(type) { + if (!type) { + throw new Error('content-type cannot be null'); + } + this.policy.conditions.push(['eq', '$Content-Type', type]); + this.formData['Content-Type'] = type; + } + + // set Content-Type prefix, i.e image/ allows any image + setContentTypeStartsWith(prefix) { + if (!prefix) { + throw new Error('content-type cannot be null'); + } + this.policy.conditions.push(['starts-with', '$Content-Type', prefix]); + this.formData['Content-Type'] = prefix; + } + + // set Content-Disposition + setContentDisposition(value) { + if (!value) { + throw new Error('content-disposition cannot be null'); + } + this.policy.conditions.push(['eq', '$Content-Disposition', value]); + this.formData['Content-Disposition'] = value; + } + + // set minimum/maximum length of what Content-Length can be. + setContentLengthRange(min, max) { + if (min > max) { + throw new Error('min cannot be more than max'); + } + if (min < 0) { + throw new Error('min should be > 0'); + } + if (max < 0) { + throw new Error('max should be > 0'); + } + this.policy.conditions.push(['content-length-range', min, max]); + } + + // set user defined metadata + setUserMetaData(metaData) { + if (!(0, _helper.isObject)(metaData)) { + throw new TypeError('metadata should be of type "object"'); + } + Object.entries(metaData).forEach(([key, value]) => { + const amzMetaDataKey = `x-amz-meta-${key}`; + this.policy.conditions.push(['eq', `$${amzMetaDataKey}`, value]); + this.formData[amzMetaDataKey] = value.toString(); + }); + } +} +exports.PostPolicy = PostPolicy; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJlcnJvcnMiLCJfaW50ZXJvcFJlcXVpcmVXaWxkY2FyZCIsInJlcXVpcmUiLCJfaGVscGVyIiwiZSIsInQiLCJXZWFrTWFwIiwiciIsIm4iLCJfX2VzTW9kdWxlIiwibyIsImkiLCJmIiwiX19wcm90b19fIiwiZGVmYXVsdCIsImhhcyIsImdldCIsInNldCIsImhhc093blByb3BlcnR5IiwiY2FsbCIsIk9iamVjdCIsImRlZmluZVByb3BlcnR5IiwiZ2V0T3duUHJvcGVydHlEZXNjcmlwdG9yIiwiUG9zdFBvbGljeSIsInBvbGljeSIsImNvbmRpdGlvbnMiLCJmb3JtRGF0YSIsInNldEV4cGlyZXMiLCJkYXRlIiwiSW52YWxpZERhdGVFcnJvciIsImV4cGlyYXRpb24iLCJ0b0lTT1N0cmluZyIsInNldEtleSIsIm9iamVjdE5hbWUiLCJpc1ZhbGlkT2JqZWN0TmFtZSIsIkludmFsaWRPYmplY3ROYW1lRXJyb3IiLCJwdXNoIiwia2V5Iiwic2V0S2V5U3RhcnRzV2l0aCIsInByZWZpeCIsImlzVmFsaWRQcmVmaXgiLC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ixRQUFRLENBQUNvQyxjQUFjLENBQUMsR0FBR1YsS0FBSyxDQUFDVyxRQUFRLENBQUMsQ0FBQztJQUNsRCxDQUFDLENBQUM7RUFDSjtBQUNGO0FBQUNDLE9BQUEsQ0FBQXpDLFVBQUEsR0FBQUEsVUFBQSJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/request.d.ts b/node_modules/minio/dist/main/internal/request.d.ts new file mode 100644 index 0000000..45ea301 --- /dev/null +++ b/node_modules/minio/dist/main/internal/request.d.ts @@ -0,0 +1,11 @@ +/// +/// +/// +/// +import type * as http from 'node:http'; +import type * as https from 'node:https'; +import type * as stream from 'node:stream'; +import type { Transport } from "./type.js"; +export declare function request(transport: Transport, opt: https.RequestOptions, body?: Buffer | string | stream.Readable | null): Promise; +export declare const retryHttpCodes: Record; +export declare function requestWithRetry(transport: Transport, opt: https.RequestOptions, body?: Buffer | string | stream.Readable | null, maxRetries?: number, baseDelayMs?: number, maximumDelayMs?: number): Promise; \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/request.js b/node_modules/minio/dist/main/internal/request.js new file mode 100644 index 0000000..46b9f6b --- /dev/null +++ b/node_modules/minio/dist/main/internal/request.js @@ -0,0 +1,83 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.request = request; +exports.requestWithRetry = requestWithRetry; +var _stream = require("stream"); +var _util = require("util"); +const pipelineAsync = (0, _util.promisify)(_stream.pipeline); +async function request(transport, opt, body = null) { + return new Promise((resolve, reject) => { + const requestObj = transport.request(opt, response => { + resolve(response); + }); + requestObj.on('error', reject); + if (!body || Buffer.isBuffer(body) || typeof body === 'string') { + requestObj.end(body); + } else { + pipelineAsync(body, requestObj).catch(reject); + } + }); +} +const MAX_RETRIES = 1; +const BASE_DELAY_MS = 100; // Base delay for exponential backoff +const MAX_DELAY_MS = 60000; // Max delay for exponential backoff + +// Retryable error codes for HTTP ( ref: minio-go) +const retryHttpCodes = { + 408: true, + 429: true, + 499: true, + 500: true, + 502: true, + 503: true, + 504: true, + 520: true +}; +exports.retryHttpCodes = retryHttpCodes; +const isHttpRetryable = httpResCode => { + return retryHttpCodes[httpResCode] !== undefined; +}; +const sleep = ms => { + return new Promise(resolve => setTimeout(resolve, ms)); +}; +const getExpBackOffDelay = (retryCount, baseDelayMs, maximumDelayMs) => { + const backOffBy = baseDelayMs * (1 << retryCount); + const additionalDelay = Math.random() * backOffBy; + return Math.min(backOffBy + additionalDelay, maximumDelayMs); +}; +async function requestWithRetry(transport, opt, body = null, maxRetries = MAX_RETRIES, baseDelayMs = BASE_DELAY_MS, maximumDelayMs = MAX_DELAY_MS) { + let attempt = 0; + let isRetryable = false; + while (attempt <= maxRetries) { + try { + const response = await request(transport, opt, body); + // Check if the HTTP status code is retryable + if (isHttpRetryable(response.statusCode)) { + isRetryable = true; + throw new Error(`Retryable HTTP status: ${response.statusCode}`); // trigger retry attempt with calculated delay + } + + return response; // Success, return the raw response + } catch (err) { + if (isRetryable) { + attempt++; + isRetryable = false; + if (attempt > maxRetries) { + throw new Error(`Request failed after ${maxRetries} retries: ${err}`); + } + const delay = getExpBackOffDelay(attempt, baseDelayMs, maximumDelayMs); + // eslint-disable-next-line no-console + console.warn(`${new Date().toLocaleString()} Retrying request (attempt ${attempt}/${maxRetries}) after ${delay}ms due to: ${err}`); + await sleep(delay); + } else { + throw err; // re-throw if any request, syntax errors + } + } + } + + throw new Error(`${MAX_RETRIES} Retries exhausted, request failed.`); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfc3RyZWFtIiwicmVxdWlyZSIsIl91dGlsIiwicGlwZWxpbmVBc3luYyIsInByb21pc2lmeSIsInBpcGVsaW5lIiwicmVxdWVzdCIsInRyYW5zcG9ydCIsIm9wdCIsImJvZHkiLCJQcm9taXNlIiwicmVzb2x2ZSIsInJlamVjdCIsInJlcXVlc3RPYmoiLCJyZXNwb25zZSIsIm9uIiwiQnVmZmVyIiwiaXN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OUIsUUFBUSxFQUFDO0lBQ2xCLENBQUMsQ0FBQyxPQUFPZ0MsR0FBWSxFQUFFO01BQ3JCLElBQUlILFdBQVcsRUFBRTtRQUNmRCxPQUFPLEVBQUU7UUFDVEMsV0FBVyxHQUFHLEtBQUs7UUFFbkIsSUFBSUQsT0FBTyxHQUFHRCxVQUFVLEVBQUU7VUFDeEIsTUFBTSxJQUFJSSxLQUFLLENBQUUsd0JBQXVCSixVQUFXLGFBQVlLLEdBQUksRUFBQyxDQUFDO1FBQ3ZFO1FBQ0EsTUFBTUMsS0FBSyxHQUFHaEIsa0JBQWtCLENBQUNXLE9BQU8sRUFBRVQsV0FBVyxFQUFFQyxjQUFjLENBQUM7UUFDdEU7UUFDQWMsT0FBTyxDQUFDQyxJQUFJLENBQ1QsR0FBRSxJQUFJQyxJQUFJLENBQUMsQ0FBQyxDQUFDQyxjQUFjLENBQUMsQ0FBRSw4QkFBNkJULE9BQVEsSUFBR0QsVUFBVyxXQUFVTSxLQUFNLGNBQWFELEdBQUksRUFDckgsQ0FBQztRQUNELE1BQU1sQixLQUFLLENBQUNtQixLQUFLLENBQUM7TUFDcEIsQ0FBQyxNQUFNO1FBQ0wsTUFBTUQsR0FBRyxFQUFDO01BQ1o7SUFDRjtFQUNGOztFQUVBLE1BQU0sSUFBSUQsS0FBSyxDQUFFLEdBQUV6QixXQUFZLHFDQUFvQyxDQUFDO0FBQ3RFIn0= \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/response.d.ts b/node_modules/minio/dist/main/internal/response.d.ts new file mode 100644 index 0000000..6676ad9 --- /dev/null +++ b/node_modules/minio/dist/main/internal/response.d.ts @@ -0,0 +1,8 @@ +/// +/// +/// +import type http from 'node:http'; +import type stream from 'node:stream'; +export declare function readAsBuffer(res: stream.Readable): Promise; +export declare function readAsString(res: http.IncomingMessage): Promise; +export declare function drainResponse(res: stream.Readable): Promise; \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/response.js b/node_modules/minio/dist/main/internal/response.js new file mode 100644 index 0000000..5cb26df --- /dev/null +++ b/node_modules/minio/dist/main/internal/response.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.drainResponse = drainResponse; +exports.readAsBuffer = readAsBuffer; +exports.readAsString = readAsString; +async function readAsBuffer(res) { + return new Promise((resolve, reject) => { + const body = []; + res.on('data', chunk => body.push(chunk)).on('error', e => reject(e)).on('end', () => resolve(Buffer.concat(body))); + }); +} +async function readAsString(res) { + const body = await readAsBuffer(res); + return body.toString(); +} +async function drainResponse(res) { + return new Promise((resolve, reject) => { + res.on('data', () => {}).on('error', e => reject(e)).on('end', () => resolve()); + }); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJyZWFkQXNCdWZmZXIiLCJyZXMiLCJQcm9taXNlIiwicmVzb2x2ZSIsInJlamVjdCIsImJvZHkiLCJvbiIsImNodW5rIiwicHVzaCIsImUiLCJCdWZmZXIiLCJjb25jYXQiLCJyZWFkQXNTdHJpbmciLCJ0b1N0cmluZyIsImRyYWluUmVzcG9uc2UiXSwic291cmNlcyI6WyJyZXNwb25zZS50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgdHlwZSBodHRwIGZyb20gJ25vZGU6aHR0cCdcbmltcG9ydCB0eXBlIHN0cmVhbSBmcm9tICdub2RlOnN0cmVhbSdcblxuZXhwb3J0IGFzeW5jIGZ1bmN0aW9uIHJlYWRBc0J1ZmZlcihyZXM6IHN0cmVhbS5SZWFkYWJsZSk6IFByb21pc2U8QnVmZmVyPiB7XG4gIHJldHVybiBuZXcgUHJvbWlzZSgocmVzb2x2ZSwgcmVqZWN0KSA9PiB7XG4gICAgY29uc3QgYm9keTogQnVmZmVyW10gPSBbXVxuICAgIHJlc1xuICAgICAgLm9uKCdkYXRhJywgKGNodW5rOiBCdWZmZXIpID0+IGJvZHkucHVzaChjaHVuaykpXG4gICAgICAub24oJ2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1ILE9BQU8sQ0FBQ08sTUFBTSxDQUFDQyxNQUFNLENBQUNOLElBQUksQ0FBQyxDQUFDLENBQUM7RUFDbEQsQ0FBQyxDQUFDO0FBQ0o7QUFFTyxlQUFlTyxZQUFZQSxDQUFDWCxHQUF5QixFQUFtQjtFQUM3RSxNQUFNSSxJQUFJLEdBQUcsTUFBTUwsWUFBWSxDQUFDQyxHQUFHLENBQUM7RUFDcEMsT0FBT0ksSUFBSSxDQUFDUSxRQUFRLENBQUMsQ0FBQztBQUN4QjtBQUVPLGVBQWVDLGFBQWFBLENBQUNiLEdBQW9CLEVBQWlCO0VBQ3ZFLE9BQU8sSUFBSUMsT0FBTyxDQUFDLENBQUNDLE9BQU8sRUFBRUMsTUFBTSxLQUFLO0lBQ3RDSCxHQUFHLENBQ0FLLEVBQUUsQ0FBQyxNQUFNLEVBQUUsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUNwQkEsRUFBRSxDQUFDLE9BQU8sRUFBR0csQ0FBQyxJQUFLTCxNQUFNLENBQUNLLENBQUMsQ0FBQyxDQUFDLENBQzdCSCxFQUFFLENBQUMsS0FBSyxFQUFFLE1BQU1ILE9BQU8sQ0FBQyxDQUFDLENBQUM7RUFDL0IsQ0FBQyxDQUFDO0FBQ0oifQ== \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/s3-endpoints.d.ts b/node_modules/minio/dist/main/internal/s3-endpoints.d.ts new file mode 100644 index 0000000..d26e9e2 --- /dev/null +++ b/node_modules/minio/dist/main/internal/s3-endpoints.d.ts @@ -0,0 +1,38 @@ +declare const awsS3Endpoint: { + 'af-south-1': string; + 'ap-east-1': string; + 'ap-south-1': string; + 'ap-south-2': string; + 'ap-southeast-1': string; + 'ap-southeast-2': string; + 'ap-southeast-3': string; + 'ap-southeast-4': string; + 'ap-southeast-5': string; + 'ap-northeast-1': string; + 'ap-northeast-2': string; + 'ap-northeast-3': string; + 'ca-central-1': string; + 'ca-west-1': string; + 'cn-north-1': string; + 'eu-central-1': string; + 'eu-central-2': string; + 'eu-north-1': string; + 'eu-south-1': string; + 'eu-south-2': string; + 'eu-west-1': string; + 'eu-west-2': string; + 'eu-west-3': string; + 'il-central-1': string; + 'me-central-1': string; + 'me-south-1': string; + 'sa-east-1': string; + 'us-east-1': string; + 'us-east-2': string; + 'us-west-1': string; + 'us-west-2': string; + 'us-gov-east-1': string; + 'us-gov-west-1': string; +}; +export type Region = keyof typeof awsS3Endpoint | string; +export declare function getS3Endpoint(region: Region): string; +export {}; \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/s3-endpoints.js b/node_modules/minio/dist/main/internal/s3-endpoints.js new file mode 100644 index 0000000..e5adcf7 --- /dev/null +++ b/node_modules/minio/dist/main/internal/s3-endpoints.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getS3Endpoint = getS3Endpoint; +var _helper = require("./helper.js"); +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015, 2016 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// List of currently supported endpoints. +const awsS3Endpoint = { + 'af-south-1': 's3.af-south-1.amazonaws.com', + 'ap-east-1': 's3.ap-east-1.amazonaws.com', + 'ap-south-1': 's3.ap-south-1.amazonaws.com', + 'ap-south-2': 's3.ap-south-2.amazonaws.com', + 'ap-southeast-1': 's3.ap-southeast-1.amazonaws.com', + 'ap-southeast-2': 's3.ap-southeast-2.amazonaws.com', + 'ap-southeast-3': 's3.ap-southeast-3.amazonaws.com', + 'ap-southeast-4': 's3.ap-southeast-4.amazonaws.com', + 'ap-southeast-5': 's3.ap-southeast-5.amazonaws.com', + 'ap-northeast-1': 's3.ap-northeast-1.amazonaws.com', + 'ap-northeast-2': 's3.ap-northeast-2.amazonaws.com', + 'ap-northeast-3': 's3.ap-northeast-3.amazonaws.com', + 'ca-central-1': 's3.ca-central-1.amazonaws.com', + 'ca-west-1': 's3.ca-west-1.amazonaws.com', + 'cn-north-1': 's3.cn-north-1.amazonaws.com.cn', + 'eu-central-1': 's3.eu-central-1.amazonaws.com', + 'eu-central-2': 's3.eu-central-2.amazonaws.com', + 'eu-north-1': 's3.eu-north-1.amazonaws.com', + 'eu-south-1': 's3.eu-south-1.amazonaws.com', + 'eu-south-2': 's3.eu-south-2.amazonaws.com', + 'eu-west-1': 's3.eu-west-1.amazonaws.com', + 'eu-west-2': 's3.eu-west-2.amazonaws.com', + 'eu-west-3': 's3.eu-west-3.amazonaws.com', + 'il-central-1': 's3.il-central-1.amazonaws.com', + 'me-central-1': 's3.me-central-1.amazonaws.com', + 'me-south-1': 's3.me-south-1.amazonaws.com', + 'sa-east-1': 's3.sa-east-1.amazonaws.com', + 'us-east-1': 's3.us-east-1.amazonaws.com', + 'us-east-2': 's3.us-east-2.amazonaws.com', + 'us-west-1': 's3.us-west-1.amazonaws.com', + 'us-west-2': 's3.us-west-2.amazonaws.com', + 'us-gov-east-1': 's3.us-gov-east-1.amazonaws.com', + 'us-gov-west-1': 's3.us-gov-west-1.amazonaws.com' + // Add new endpoints here. +}; + +// getS3Endpoint get relevant endpoint for the region. +function getS3Endpoint(region) { + if (!(0, _helper.isString)(region)) { + throw new TypeError(`Invalid region: ${region}`); + } + const endpoint = awsS3Endpoint[region]; + if (endpoint) { + return endpoint; + } + return 's3.amazonaws.com'; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfaGVscGVyIiwicmVxdWlyZSIsImF3c1MzRW5kcG9pbnQiLCJnZXRTM0VuZHBvaW50IiwicmVnaW9uIiwiaXNTdHJpbmciLCJUeXBlRXJyb3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FBQ0QsTUFBTSxDQUFDLEVBQUU7SUFDckIsTUFBTSxJQUFJRSxTQUFTLENBQUUsbUJBQWtCRixNQUFPLEVBQUMsQ0FBQztFQUNsRDtFQUVBLE1BQU1HLFFBQVEsR0FBSUwsYUFBYSxDQUE0QkUsTUFBTSxDQUFDO0VBQ2xFLElBQUlHLFFBQVEsRUFBRTtJQUNaLE9BQU9BLFFBQVE7RUFDakI7RUFDQSxPQUFPLGtCQUFrQjtBQUMzQiJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/type.d.ts b/node_modules/minio/dist/main/internal/type.d.ts new file mode 100644 index 0000000..2206cf5 --- /dev/null +++ b/node_modules/minio/dist/main/internal/type.d.ts @@ -0,0 +1,482 @@ +/// +/// +/// +import type * as http from 'node:http'; +import type { Readable as ReadableStream } from 'node:stream'; +import type { CopyDestinationOptions, CopySourceOptions } from "../helpers.js"; +import type { CopyConditions } from "./copy-conditions.js"; +export type VersionIdentificator = { + versionId?: string; +}; +export type GetObjectOpts = VersionIdentificator & { + SSECustomerAlgorithm?: string; + SSECustomerKey?: string; + SSECustomerKeyMD5?: string; +}; +export type Binary = string | Buffer; +export type ResponseHeader = Record; +export type ObjectMetaData = Record; +export type RequestHeaders = Record; +export type EnabledOrDisabledStatus = 'Enabled' | 'Disabled'; +export declare const ENCRYPTION_TYPES: { + readonly SSEC: "SSE-C"; + readonly KMS: "KMS"; +}; +export type ENCRYPTION_TYPES = (typeof ENCRYPTION_TYPES)[keyof typeof ENCRYPTION_TYPES]; +export type Encryption = { + type: typeof ENCRYPTION_TYPES.SSEC; +} | { + type: typeof ENCRYPTION_TYPES.KMS; + SSEAlgorithm?: string; + KMSMasterKeyID?: string; +}; +export declare const RETENTION_MODES: { + readonly GOVERNANCE: "GOVERNANCE"; + readonly COMPLIANCE: "COMPLIANCE"; +}; +export type RETENTION_MODES = (typeof RETENTION_MODES)[keyof typeof RETENTION_MODES]; +export declare const RETENTION_VALIDITY_UNITS: { + readonly DAYS: "Days"; + readonly YEARS: "Years"; +}; +export type RETENTION_VALIDITY_UNITS = (typeof RETENTION_VALIDITY_UNITS)[keyof typeof RETENTION_VALIDITY_UNITS]; +export declare const LEGAL_HOLD_STATUS: { + readonly ENABLED: "ON"; + readonly DISABLED: "OFF"; +}; +export type LEGAL_HOLD_STATUS = (typeof LEGAL_HOLD_STATUS)[keyof typeof LEGAL_HOLD_STATUS]; +export type Transport = Pick; +export interface IRequest { + protocol: string; + port?: number | string; + method: string; + path: string; + headers: RequestHeaders; +} +export type ICanonicalRequest = string; +export interface IncompleteUploadedBucketItem { + key: string; + uploadId: string; + size: number; +} +export interface MetadataItem { + Key: string; + Value: string; +} +export interface ItemBucketMetadataList { + Items: MetadataItem[]; +} +export interface ItemBucketMetadata { + [key: string]: any; +} +export interface ItemBucketTags { + [key: string]: any; +} +export interface BucketItemFromList { + name: string; + creationDate: Date; +} +export interface BucketItemCopy { + etag: string; + lastModified: Date; +} +export type BucketItem = { + name: string; + size: number; + etag: string; + prefix?: never; + lastModified: Date; +} | { + name?: never; + etag?: never; + lastModified?: never; + prefix: string; + size: 0; +}; +export type BucketItemWithMetadata = BucketItem & { + metadata?: ItemBucketMetadata | ItemBucketMetadataList; + tags?: ItemBucketTags; +}; +export interface BucketStream extends ReadableStream { + on(event: 'data', listener: (item: T) => void): this; + on(event: 'end' | 'pause' | 'readable' | 'resume' | 'close', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; +} +export interface BucketItemStat { + size: number; + etag: string; + lastModified: Date; + metaData: ItemBucketMetadata; + versionId?: string | null; +} +export type StatObjectOpts = { + versionId?: string; +}; +export type ReplicationRuleStatus = { + Status: EnabledOrDisabledStatus; +}; +export type Tag = { + Key: string; + Value: string; +}; +export type Tags = Record; +export type ReplicationRuleDestination = { + Bucket: string; + StorageClass: string; +}; +export type ReplicationRuleAnd = { + Prefix: string; + Tags: Tag[]; +}; +export type ReplicationRuleFilter = { + Prefix: string; + And: ReplicationRuleAnd; + Tag: Tag; +}; +export type ReplicaModifications = { + Status: ReplicationRuleStatus; +}; +export type SourceSelectionCriteria = { + ReplicaModifications: ReplicaModifications; +}; +export type ExistingObjectReplication = { + Status: ReplicationRuleStatus; +}; +export type ReplicationRule = { + ID: string; + Status: ReplicationRuleStatus; + Priority: number; + DeleteMarkerReplication: ReplicationRuleStatus; + DeleteReplication: ReplicationRuleStatus; + Destination: ReplicationRuleDestination; + Filter: ReplicationRuleFilter; + SourceSelectionCriteria: SourceSelectionCriteria; + ExistingObjectReplication: ExistingObjectReplication; +}; +export type ReplicationConfigOpts = { + role: string; + rules: ReplicationRule[]; +}; +export type ReplicationConfig = { + ReplicationConfiguration: ReplicationConfigOpts; +}; +export type ResultCallback = (error: Error | null, result: T) => void; +export type GetObjectLegalHoldOptions = { + versionId: string; +}; +/** + * @deprecated keep for backward compatible, use `LEGAL_HOLD_STATUS` instead + */ +export type LegalHoldStatus = LEGAL_HOLD_STATUS; +export type PutObjectLegalHoldOptions = { + versionId?: string; + status: LEGAL_HOLD_STATUS; +}; +export interface UploadedObjectInfo { + etag: string; + versionId: string | null; +} +export interface RetentionOptions { + versionId: string; + mode?: RETENTION_MODES; + retainUntilDate?: IsoDate; + governanceBypass?: boolean; +} +export type Retention = RetentionOptions | EmptyObject; +export type IsoDate = string; +export type EmptyObject = Record; +export type ObjectLockInfo = { + objectLockEnabled: EnabledOrDisabledStatus; + mode: RETENTION_MODES; + unit: RETENTION_VALIDITY_UNITS; + validity: number; +} | EmptyObject; +export type ObjectLockConfigParam = { + ObjectLockEnabled?: 'Enabled' | undefined; + Rule?: { + DefaultRetention: { + Mode: RETENTION_MODES; + Days: number; + Years: number; + } | EmptyObject; + } | EmptyObject; +}; +export type VersioningEnabled = 'Enabled'; +export type VersioningSuspended = 'Suspended'; +export type TaggingOpts = { + versionId: string; +}; +export type PutTaggingParams = { + bucketName: string; + objectName?: string; + tags: Tags; + putOpts?: TaggingOpts; +}; +export type RemoveTaggingParams = { + bucketName: string; + objectName?: string; + removeOpts?: TaggingOpts; +}; +export type InputSerialization = { + CompressionType?: 'NONE' | 'GZIP' | 'BZIP2'; + CSV?: { + AllowQuotedRecordDelimiter?: boolean; + Comments?: string; + FieldDelimiter?: string; + FileHeaderInfo?: 'NONE' | 'IGNORE' | 'USE'; + QuoteCharacter?: string; + QuoteEscapeCharacter?: string; + RecordDelimiter?: string; + }; + JSON?: { + Type: 'DOCUMENT' | 'LINES'; + }; + Parquet?: EmptyObject; +}; +export type OutputSerialization = { + CSV?: { + FieldDelimiter?: string; + QuoteCharacter?: string; + QuoteEscapeCharacter?: string; + QuoteFields?: string; + RecordDelimiter?: string; + }; + JSON?: { + RecordDelimiter?: string; + }; +}; +export type SelectProgress = { + Enabled: boolean; +}; +export type ScanRange = { + Start: number; + End: number; +}; +export type SelectOptions = { + expression: string; + expressionType?: string; + inputSerialization: InputSerialization; + outputSerialization: OutputSerialization; + requestProgress?: SelectProgress; + scanRange?: ScanRange; +}; +export type Expiration = { + Date?: string; + Days: number; + DeleteMarker?: boolean; + DeleteAll?: boolean; +}; +export type RuleFilterAnd = { + Prefix: string; + Tags: Tag[]; +}; +export type RuleFilter = { + And?: RuleFilterAnd; + Prefix: string; + Tag?: Tag[]; +}; +export type NoncurrentVersionExpiration = { + NoncurrentDays: number; + NewerNoncurrentVersions?: number; +}; +export type NoncurrentVersionTransition = { + StorageClass: string; + NoncurrentDays?: number; + NewerNoncurrentVersions?: number; +}; +export type Transition = { + Date?: string; + StorageClass: string; + Days: number; +}; +export type AbortIncompleteMultipartUpload = { + DaysAfterInitiation: number; +}; +export type LifecycleRule = { + AbortIncompleteMultipartUpload?: AbortIncompleteMultipartUpload; + ID: string; + Prefix?: string; + Status?: string; + Expiration?: Expiration; + Filter?: RuleFilter; + NoncurrentVersionExpiration?: NoncurrentVersionExpiration; + NoncurrentVersionTransition?: NoncurrentVersionTransition; + Transition?: Transition; +}; +export type LifecycleConfig = { + Rule: LifecycleRule[]; +}; +export type LifeCycleConfigParam = LifecycleConfig | null | undefined | ''; +export type ApplySSEByDefault = { + KmsMasterKeyID?: string; + SSEAlgorithm: string; +}; +export type EncryptionRule = { + ApplyServerSideEncryptionByDefault?: ApplySSEByDefault; +}; +export type EncryptionConfig = { + Rule: EncryptionRule[]; +}; +export type GetObjectRetentionOpts = { + versionId: string; +}; +export type ObjectRetentionInfo = { + mode: RETENTION_MODES; + retainUntilDate: string; +}; +export type RemoveObjectsEntry = { + name: string; + versionId?: string; +}; +export type ObjectName = string; +export type RemoveObjectsParam = ObjectName[] | RemoveObjectsEntry[]; +export type RemoveObjectsRequestEntry = { + Key: string; + VersionId?: string; +}; +export type RemoveObjectsResponse = null | undefined | { + Error?: { + Code?: string; + Message?: string; + Key?: string; + VersionId?: string; + }; +}; +export type CopyObjectResultV1 = { + etag: string; + lastModified: string | Date; +}; +export type CopyObjectResultV2 = { + Bucket?: string; + Key?: string; + LastModified: string | Date; + MetaData?: ResponseHeader; + VersionId?: string | null; + SourceVersionId?: string | null; + Etag?: string; + Size?: number; +}; +export type CopyObjectResult = CopyObjectResultV1 | CopyObjectResultV2; +export type CopyObjectParams = [CopySourceOptions, CopyDestinationOptions] | [string, string, string, CopyConditions?]; +export type ExcludedPrefix = { + Prefix: string; +}; +export type BucketVersioningConfiguration = { + Status: VersioningEnabled | VersioningSuspended; + MFADelete?: string; + ExcludedPrefixes?: ExcludedPrefix[]; + ExcludeFolders?: boolean; +}; +export type UploadPartConfig = { + bucketName: string; + objectName: string; + uploadID: string; + partNumber: number; + headers: RequestHeaders; + sourceObj: string; +}; +export type PreSignRequestParams = { + [key: string]: string; +}; +/** List object api types **/ +export type CommonPrefix = { + Prefix: string; +}; +export type Owner = { + ID: string; + DisplayName: string; +}; +export type Metadata = { + Items: MetadataItem[]; +}; +export type ObjectInfo = { + key?: string; + name?: string; + lastModified?: Date; + etag?: string; + owner?: Owner; + storageClass?: string; + userMetadata?: Metadata; + userTags?: string; + prefix?: string; + size?: number; +}; +export type ListObjectQueryRes = { + isTruncated?: boolean; + nextMarker?: string; + objects?: ObjectInfo[]; + keyMarker?: string; + versionIdMarker?: string; +}; +export type ListObjectQueryOpts = { + Delimiter?: string; + MaxKeys?: number; + IncludeVersion?: boolean; + keyMarker?: string; + versionIdMarker?: string; +}; +/** List object api types **/ +export type ObjectVersionEntry = { + IsLatest?: string; + VersionId?: string; +}; +export type ObjectRowEntry = ObjectVersionEntry & { + Key: string; + LastModified?: Date | undefined; + ETag?: string; + Size?: string; + Owner?: Owner; + StorageClass?: string; +}; +export type ListObjectV2Res = { + objects: BucketItem[]; + isTruncated: boolean; + nextContinuationToken: string; +}; +export type NotificationConfigEntry = { + Id: string; + Event: string[]; + Filter: { + Name: string; + Value: string; + }[]; +}; +export type TopicConfigEntry = NotificationConfigEntry & { + Topic: string; +}; +export type QueueConfigEntry = NotificationConfigEntry & { + Queue: string; +}; +export type CloudFunctionConfigEntry = NotificationConfigEntry & { + CloudFunction: string; +}; +export type NotificationConfigResult = { + TopicConfiguration: TopicConfigEntry[]; + QueueConfiguration: QueueConfigEntry[]; + CloudFunctionConfiguration: CloudFunctionConfigEntry[]; +}; +export interface ListBucketResultV1 { + Name?: string; + Prefix?: string; + ContinuationToken?: string; + KeyCount?: string; + Marker?: string; + MaxKeys?: string; + Delimiter?: string; + IsTruncated?: boolean; + Contents?: ObjectRowEntry[]; + NextKeyMarker?: string; + CommonPrefixes?: CommonPrefix[]; + Version?: ObjectRowEntry[]; + DeleteMarker?: ObjectRowEntry[]; + VersionIdMarker?: string; + NextVersionIdMarker?: string; + NextMarker?: string; +} +export interface PostPolicyResult { + postURL: string; + formData: { + [key: string]: any; + }; +} \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/type.js b/node_modules/minio/dist/main/internal/type.js new file mode 100644 index 0000000..a3ffb54 --- /dev/null +++ b/node_modules/minio/dist/main/internal/type.js @@ -0,0 +1,42 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// nodejs IncomingHttpHeaders is Record, but it's actually this: + +const ENCRYPTION_TYPES = { + SSEC: 'SSE-C', + KMS: 'KMS' +}; +exports.ENCRYPTION_TYPES = ENCRYPTION_TYPES; +const RETENTION_MODES = { + GOVERNANCE: 'GOVERNANCE', + COMPLIANCE: 'COMPLIANCE' +}; +exports.RETENTION_MODES = RETENTION_MODES; +const RETENTION_VALIDITY_UNITS = { + DAYS: 'Days', + YEARS: 'Years' +}; +exports.RETENTION_VALIDITY_UNITS = RETENTION_VALIDITY_UNITS; +const LEGAL_HOLD_STATUS = { + ENABLED: 'ON', + DISABLED: 'OFF' +}; + +/* Replication Config types */ + +/* Replication Config types */ + +/** + * @deprecated keep for backward compatible, use `LEGAL_HOLD_STATUS` instead + */ + +/** List object api types **/ + +// Common types + +/** List object api types **/ +exports.LEGAL_HOLD_STATUS = LEGAL_HOLD_STATUS; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJFTkNSWVBUSU9OX1RZUEVTIiwiU1NFQyIsIktNUyIsImV4cG9ydHMiLCJSRVRFTlRJT05fTU9ERVMiLCJHT1ZFUk5BTkNFIiwiQ09NUExJQU5DRSIsIlJFVEVOVElPTl9WQUxJRElUWV9VTklUUyIsIkRBWVMiLCJZRUFSUyIsIkxFR0FMX0hPTERfU1RBVFVTIiwiRU5BQkxFRCIsIkRJU0FCTEVEIl0sInNvdXJjZXMiOlsidHlwZS50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgdHlwZSAqIGFzIGh0dHAgZnJvbSAnbm9kZTpodHRwJ1xuaW1wb3J0IHR5cGUgeyBSZWFkYWJsZSBhcyBSZWFkYWJsZVN0cmVhbSB9IGZyb20gJ25vZGU6c3RyZWFtJ1xuXG5pbXBvcnQgdHlwZSB7IENvcHlEZXN0aW5hdGlvbk9wdGlvbnMsIENvcHlTb3VyY2VPcHRpb25zIH0gZnJvbSAnLi4vaGVscGVycy50cydcbmltcG9ydCB0eXBlIHsg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ml-parser.d.ts b/node_modules/minio/dist/main/internal/xml-parser.d.ts new file mode 100644 index 0000000..6fb25c8 --- /dev/null +++ b/node_modules/minio/dist/main/internal/xml-parser.d.ts @@ -0,0 +1,93 @@ +/// +/// +import type * as http from 'node:http'; +import { SelectResults } from "../helpers.js"; +import type { BucketItemFromList, BucketItemWithMetadata, CopyObjectResultV1, ListObjectV2Res, NotificationConfigResult, ObjectInfo, ObjectLockInfo, ReplicationConfig, Tag } from "./type.js"; +export declare function parseBucketRegion(xml: string): string; +export declare function parseError(xml: string, headerInfo: Record): Record; +export declare function parseResponseError(response: http.IncomingMessage): Promise>; +/** + * parse XML response for list objects v2 with metadata in a bucket + */ +export declare function parseListObjectsV2WithMetadata(xml: string): { + objects: Array; + isTruncated: boolean; + nextContinuationToken: string; +}; +export declare function parseListObjectsV2(xml: string): ListObjectV2Res; +export declare function parseBucketNotification(xml: string): NotificationConfigResult; +export type UploadedPart = { + part: number; + lastModified?: Date; + etag: string; + size: number; +}; +export declare function parseListParts(xml: string): { + isTruncated: boolean; + marker: number; + parts: UploadedPart[]; +}; +export declare function parseListBucket(xml: string): BucketItemFromList[]; +export declare function parseInitiateMultipart(xml: string): string; +export declare function parseReplicationConfig(xml: string): ReplicationConfig; +export declare function parseObjectLegalHoldConfig(xml: string): any; +export declare function parseTagging(xml: string): Tag[]; +export declare function parseCompleteMultipart(xml: string): { + location: any; + bucket: any; + key: any; + etag: any; + errCode?: undefined; + errMessage?: undefined; +} | { + errCode: any; + errMessage: any; + location?: undefined; + bucket?: undefined; + key?: undefined; + etag?: undefined; +} | undefined; +type UploadID = string; +export type ListMultipartResult = { + uploads: { + key: string; + uploadId: UploadID; + initiator?: { + id: string; + displayName: string; + }; + owner?: { + id: string; + displayName: string; + }; + storageClass: unknown; + initiated: Date; + }[]; + prefixes: { + prefix: string; + }[]; + isTruncated: boolean; + nextKeyMarker: string; + nextUploadIdMarker: string; +}; +export declare function parseListMultipart(xml: string): ListMultipartResult; +export declare function parseObjectLockConfig(xml: string): ObjectLockInfo; +export declare function parseBucketVersioningConfig(xml: string): any; +export declare function parseSelectObjectContentResponse(res: Buffer): SelectResults | undefined; +export declare function parseLifecycleConfig(xml: string): any; +export declare function parseBucketEncryptionConfig(xml: string): any; +export declare function parseObjectRetentionConfig(xml: string): { + mode: any; + retainUntilDate: any; +}; +export declare function removeObjectsParser(xml: string): any[]; +export declare function parseCopyObject(xml: string): CopyObjectResultV1; +export declare function parseListObjects(xml: string): { + objects: ObjectInfo[]; + isTruncated?: boolean | undefined; + nextMarker?: string | undefined; + versionIdMarker?: string | undefined; + keyMarker?: string | undefined; +}; +export declare function uploadPartParser(xml: string): any; +export {}; \ No newline at end of file diff --git a/node_modules/minio/dist/main/internal/xml-parser.js b/node_modules/minio/dist/main/internal/xml-parser.js new file mode 100644 index 0000000..21e7431 --- /dev/null +++ b/node_modules/minio/dist/main/internal/xml-parser.js @@ -0,0 +1,847 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parseBucketEncryptionConfig = parseBucketEncryptionConfig; +exports.parseBucketNotification = parseBucketNotification; +exports.parseBucketRegion = parseBucketRegion; +exports.parseBucketVersioningConfig = parseBucketVersioningConfig; +exports.parseCompleteMultipart = parseCompleteMultipart; +exports.parseCopyObject = parseCopyObject; +exports.parseError = parseError; +exports.parseInitiateMultipart = parseInitiateMultipart; +exports.parseLifecycleConfig = parseLifecycleConfig; +exports.parseListBucket = parseListBucket; +exports.parseListMultipart = parseListMultipart; +exports.parseListObjects = parseListObjects; +exports.parseListObjectsV2 = parseListObjectsV2; +exports.parseListObjectsV2WithMetadata = parseListObjectsV2WithMetadata; +exports.parseListParts = parseListParts; +exports.parseObjectLegalHoldConfig = parseObjectLegalHoldConfig; +exports.parseObjectLockConfig = parseObjectLockConfig; +exports.parseObjectRetentionConfig = parseObjectRetentionConfig; +exports.parseReplicationConfig = parseReplicationConfig; +exports.parseResponseError = parseResponseError; +exports.parseSelectObjectContentResponse = parseSelectObjectContentResponse; +exports.parseTagging = parseTagging; +exports.removeObjectsParser = removeObjectsParser; +exports.uploadPartParser = uploadPartParser; +var _bufferCrc = require("buffer-crc32"); +var _fastXmlParser = require("fast-xml-parser"); +var errors = _interopRequireWildcard(require("../errors.js"), true); +var _helpers = require("../helpers.js"); +var _helper = require("./helper.js"); +var _response = require("./response.js"); +var _type = require("./type.js"); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +// parse XML response for bucket region +function parseBucketRegion(xml) { + // return region information + return (0, _helper.parseXml)(xml).LocationConstraint; +} +const fxp = new _fastXmlParser.XMLParser(); +const fxpWithoutNumParser = new _fastXmlParser.XMLParser({ + // @ts-ignore + numberParseOptions: { + skipLike: /./ + } +}); + +// Parse XML and return information as Javascript types +// parse error XML response +function parseError(xml, headerInfo) { + let xmlErr = {}; + const xmlObj = fxp.parse(xml); + if (xmlObj.Error) { + xmlErr = xmlObj.Error; + } + const e = new errors.S3Error(); + Object.entries(xmlErr).forEach(([key, value]) => { + e[key.toLowerCase()] = value; + }); + Object.entries(headerInfo).forEach(([key, value]) => { + e[key] = value; + }); + return e; +} + +// Generates an Error object depending on http statusCode and XML body +async function parseResponseError(response) { + const statusCode = response.statusCode; + let code = '', + message = ''; + if (statusCode === 301) { + code = 'MovedPermanently'; + message = 'Moved Permanently'; + } else if (statusCode === 307) { + code = 'TemporaryRedirect'; + message = 'Are you using the correct endpoint URL?'; + } else if (statusCode === 403) { + code = 'AccessDenied'; + message = 'Valid and authorized credentials required'; + } else if (statusCode === 404) { + code = 'NotFound'; + message = 'Not Found'; + } else if (statusCode === 405) { + code = 'MethodNotAllowed'; + message = 'Method Not Allowed'; + } else if (statusCode === 501) { + code = 'MethodNotAllowed'; + message = 'Method Not Allowed'; + } else if (statusCode === 503) { + code = 'SlowDown'; + message = 'Please reduce your request rate.'; + } else { + const hErrCode = response.headers['x-minio-error-code']; + const hErrDesc = response.headers['x-minio-error-desc']; + if (hErrCode && hErrDesc) { + code = hErrCode; + message = hErrDesc; + } + } + const headerInfo = {}; + // A value created by S3 compatible server that uniquely identifies the request. + headerInfo.amzRequestid = response.headers['x-amz-request-id']; + // A special token that helps troubleshoot API replies and issues. + headerInfo.amzId2 = response.headers['x-amz-id-2']; + + // Region where the bucket is located. This header is returned only + // in HEAD bucket and ListObjects response. + headerInfo.amzBucketRegion = response.headers['x-amz-bucket-region']; + const xmlString = await (0, _response.readAsString)(response); + if (xmlString) { + throw parseError(xmlString, headerInfo); + } + + // Message should be instantiated for each S3Errors. + const e = new errors.S3Error(message, { + cause: headerInfo + }); + // S3 Error code. + e.code = code; + Object.entries(headerInfo).forEach(([key, value]) => { + // @ts-expect-error force set error properties + e[key] = value; + }); + throw e; +} + +/** + * parse XML response for list objects v2 with metadata in a bucket + */ +function parseListObjectsV2WithMetadata(xml) { + const result = { + objects: [], + isTruncated: false, + nextContinuationToken: '' + }; + let xmlobj = (0, _helper.parseXml)(xml); + if (!xmlobj.ListBucketResult) { + throw new errors.InvalidXMLError('Missing tag: "ListBucketResult"'); + } + xmlobj = xmlobj.ListBucketResult; + if (xmlobj.IsTruncated) { + result.isTruncated = xmlobj.IsTruncated; + } + if (xmlobj.NextContinuationToken) { + result.nextContinuationToken = xmlobj.NextContinuationToken; + } + if (xmlobj.Contents) { + (0, _helper.toArray)(xmlobj.Contents).forEach(content => { + const name = (0, _helper.sanitizeObjectKey)(content.Key); + const lastModified = new Date(content.LastModified); + const etag = (0, _helper.sanitizeETag)(content.ETag); + const size = content.Size; + let tags = {}; + if (content.UserTags != null) { + (0, _helper.toArray)(content.UserTags.split('&')).forEach(tag => { + const [key, value] = tag.split('='); + tags[key] = value; + }); + } else { + tags = {}; + } + let metadata; + if (content.UserMetadata != null) { + metadata = (0, _helper.toArray)(content.UserMetadata)[0]; + } else { + metadata = null; + } + result.objects.push({ + name, + lastModified, + etag, + size, + metadata, + tags + }); + }); + } + if (xmlobj.CommonPrefixes) { + (0, _helper.toArray)(xmlobj.CommonPrefixes).forEach(commonPrefix => { + result.objects.push({ + prefix: (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(commonPrefix.Prefix)[0]), + size: 0 + }); + }); + } + return result; +} +function parseListObjectsV2(xml) { + const result = { + objects: [], + isTruncated: false, + nextContinuationToken: '' + }; + let xmlobj = (0, _helper.parseXml)(xml); + if (!xmlobj.ListBucketResult) { + throw new errors.InvalidXMLError('Missing tag: "ListBucketResult"'); + } + xmlobj = xmlobj.ListBucketResult; + if (xmlobj.IsTruncated) { + result.isTruncated = xmlobj.IsTruncated; + } + if (xmlobj.NextContinuationToken) { + result.nextContinuationToken = xmlobj.NextContinuationToken; + } + if (xmlobj.Contents) { + (0, _helper.toArray)(xmlobj.Contents).forEach(content => { + const name = (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(content.Key)[0]); + const lastModified = new Date(content.LastModified); + const etag = (0, _helper.sanitizeETag)(content.ETag); + const size = content.Size; + result.objects.push({ + name, + lastModified, + etag, + size + }); + }); + } + if (xmlobj.CommonPrefixes) { + (0, _helper.toArray)(xmlobj.CommonPrefixes).forEach(commonPrefix => { + result.objects.push({ + prefix: (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(commonPrefix.Prefix)[0]), + size: 0 + }); + }); + } + return result; +} +function parseBucketNotification(xml) { + const result = { + TopicConfiguration: [], + QueueConfiguration: [], + CloudFunctionConfiguration: [] + }; + const genEvents = events => { + if (!events) { + return []; + } + return (0, _helper.toArray)(events); + }; + const genFilterRules = filters => { + var _filterArr$; + const rules = []; + if (!filters) { + return rules; + } + const filterArr = (0, _helper.toArray)(filters); + if ((_filterArr$ = filterArr[0]) !== null && _filterArr$ !== void 0 && _filterArr$.S3Key) { + var _s3KeyArr$; + const s3KeyArr = (0, _helper.toArray)(filterArr[0].S3Key); + if ((_s3KeyArr$ = s3KeyArr[0]) !== null && _s3KeyArr$ !== void 0 && _s3KeyArr$.FilterRule) { + (0, _helper.toArray)(s3KeyArr[0].FilterRule).forEach(rule => { + const r = rule; + const Name = (0, _helper.toArray)(r.Name)[0]; + const Value = (0, _helper.toArray)(r.Value)[0]; + rules.push({ + Name, + Value + }); + }); + } + } + return rules; + }; + let xmlobj = (0, _helper.parseXml)(xml); + xmlobj = xmlobj.NotificationConfiguration; + if (xmlobj.TopicConfiguration) { + (0, _helper.toArray)(xmlobj.TopicConfiguration).forEach(config => { + const Id = (0, _helper.toArray)(config.Id)[0]; + const Topic = (0, _helper.toArray)(config.Topic)[0]; + const Event = genEvents(config.Event); + const Filter = genFilterRules(config.Filter); + result.TopicConfiguration.push({ + Id, + Topic, + Event, + Filter + }); + }); + } + if (xmlobj.QueueConfiguration) { + (0, _helper.toArray)(xmlobj.QueueConfiguration).forEach(config => { + const Id = (0, _helper.toArray)(config.Id)[0]; + const Queue = (0, _helper.toArray)(config.Queue)[0]; + const Event = genEvents(config.Event); + const Filter = genFilterRules(config.Filter); + result.QueueConfiguration.push({ + Id, + Queue, + Event, + Filter + }); + }); + } + if (xmlobj.CloudFunctionConfiguration) { + (0, _helper.toArray)(xmlobj.CloudFunctionConfiguration).forEach(config => { + const Id = (0, _helper.toArray)(config.Id)[0]; + const CloudFunction = (0, _helper.toArray)(config.CloudFunction)[0]; + const Event = genEvents(config.Event); + const Filter = genFilterRules(config.Filter); + result.CloudFunctionConfiguration.push({ + Id, + CloudFunction, + Event, + Filter + }); + }); + } + return result; +} +// parse XML response for list parts of an in progress multipart upload +function parseListParts(xml) { + let xmlobj = (0, _helper.parseXml)(xml); + const result = { + isTruncated: false, + parts: [], + marker: 0 + }; + if (!xmlobj.ListPartsResult) { + throw new errors.InvalidXMLError('Missing tag: "ListPartsResult"'); + } + xmlobj = xmlobj.ListPartsResult; + if (xmlobj.IsTruncated) { + result.isTruncated = xmlobj.IsTruncated; + } + if (xmlobj.NextPartNumberMarker) { + result.marker = (0, _helper.toArray)(xmlobj.NextPartNumberMarker)[0] || ''; + } + if (xmlobj.Part) { + (0, _helper.toArray)(xmlobj.Part).forEach(p => { + const part = parseInt((0, _helper.toArray)(p.PartNumber)[0], 10); + const lastModified = new Date(p.LastModified); + const etag = p.ETag.replace(/^"/g, '').replace(/"$/g, '').replace(/^"/g, '').replace(/"$/g, '').replace(/^"/g, '').replace(/"$/g, ''); + result.parts.push({ + part, + lastModified, + etag, + size: parseInt(p.Size, 10) + }); + }); + } + return result; +} +function parseListBucket(xml) { + let result = []; + const listBucketResultParser = new _fastXmlParser.XMLParser({ + parseTagValue: true, + // Enable parsing of values + numberParseOptions: { + leadingZeros: false, + // Disable number parsing for values with leading zeros + hex: false, + // Disable hex number parsing - Invalid bucket name + skipLike: /^[0-9]+$/ // Skip number parsing if the value consists entirely of digits + }, + + tagValueProcessor: (tagName, tagValue = '') => { + // Ensure that the Name tag is always treated as a string + if (tagName === 'Name') { + return tagValue.toString(); + } + return tagValue; + }, + ignoreAttributes: false // Ensure that all attributes are parsed + }); + + const parsedXmlRes = listBucketResultParser.parse(xml); + if (!parsedXmlRes.ListAllMyBucketsResult) { + throw new errors.InvalidXMLError('Missing tag: "ListAllMyBucketsResult"'); + } + const { + ListAllMyBucketsResult: { + Buckets = {} + } = {} + } = parsedXmlRes; + if (Buckets.Bucket) { + result = (0, _helper.toArray)(Buckets.Bucket).map((bucket = {}) => { + const { + Name: bucketName, + CreationDate + } = bucket; + const creationDate = new Date(CreationDate); + return { + name: bucketName, + creationDate + }; + }); + } + return result; +} +function parseInitiateMultipart(xml) { + let xmlobj = (0, _helper.parseXml)(xml); + if (!xmlobj.InitiateMultipartUploadResult) { + throw new errors.InvalidXMLError('Missing tag: "InitiateMultipartUploadResult"'); + } + xmlobj = xmlobj.InitiateMultipartUploadResult; + if (xmlobj.UploadId) { + return xmlobj.UploadId; + } + throw new errors.InvalidXMLError('Missing tag: "UploadId"'); +} +function parseReplicationConfig(xml) { + const xmlObj = (0, _helper.parseXml)(xml); + const { + Role, + Rule + } = xmlObj.ReplicationConfiguration; + return { + ReplicationConfiguration: { + role: Role, + rules: (0, _helper.toArray)(Rule) + } + }; +} +function parseObjectLegalHoldConfig(xml) { + const xmlObj = (0, _helper.parseXml)(xml); + return xmlObj.LegalHold; +} +function parseTagging(xml) { + const xmlObj = (0, _helper.parseXml)(xml); + let result = []; + if (xmlObj.Tagging && xmlObj.Tagging.TagSet && xmlObj.Tagging.TagSet.Tag) { + const tagResult = xmlObj.Tagging.TagSet.Tag; + // if it is a single tag convert into an array so that the return value is always an array. + if (Array.isArray(tagResult)) { + result = [...tagResult]; + } else { + result.push(tagResult); + } + } + return result; +} + +// parse XML response when a multipart upload is completed +function parseCompleteMultipart(xml) { + const xmlobj = (0, _helper.parseXml)(xml).CompleteMultipartUploadResult; + if (xmlobj.Location) { + const location = (0, _helper.toArray)(xmlobj.Location)[0]; + const bucket = (0, _helper.toArray)(xmlobj.Bucket)[0]; + const key = xmlobj.Key; + const etag = xmlobj.ETag.replace(/^"/g, '').replace(/"$/g, '').replace(/^"/g, '').replace(/"$/g, '').replace(/^"/g, '').replace(/"$/g, ''); + return { + location, + bucket, + key, + etag + }; + } + // Complete Multipart can return XML Error after a 200 OK response + if (xmlobj.Code && xmlobj.Message) { + const errCode = (0, _helper.toArray)(xmlobj.Code)[0]; + const errMessage = (0, _helper.toArray)(xmlobj.Message)[0]; + return { + errCode, + errMessage + }; + } +} +// parse XML response for listing in-progress multipart uploads +function parseListMultipart(xml) { + const result = { + prefixes: [], + uploads: [], + isTruncated: false, + nextKeyMarker: '', + nextUploadIdMarker: '' + }; + let xmlobj = (0, _helper.parseXml)(xml); + if (!xmlobj.ListMultipartUploadsResult) { + throw new errors.InvalidXMLError('Missing tag: "ListMultipartUploadsResult"'); + } + xmlobj = xmlobj.ListMultipartUploadsResult; + if (xmlobj.IsTruncated) { + result.isTruncated = xmlobj.IsTruncated; + } + if (xmlobj.NextKeyMarker) { + result.nextKeyMarker = xmlobj.NextKeyMarker; + } + if (xmlobj.NextUploadIdMarker) { + result.nextUploadIdMarker = xmlobj.nextUploadIdMarker || ''; + } + if (xmlobj.CommonPrefixes) { + (0, _helper.toArray)(xmlobj.CommonPrefixes).forEach(prefix => { + // @ts-expect-error index check + result.prefixes.push({ + prefix: (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(prefix.Prefix)[0]) + }); + }); + } + if (xmlobj.Upload) { + (0, _helper.toArray)(xmlobj.Upload).forEach(upload => { + const uploadItem = { + key: upload.Key, + uploadId: upload.UploadId, + storageClass: upload.StorageClass, + initiated: new Date(upload.Initiated) + }; + if (upload.Initiator) { + uploadItem.initiator = { + id: upload.Initiator.ID, + displayName: upload.Initiator.DisplayName + }; + } + if (upload.Owner) { + uploadItem.owner = { + id: upload.Owner.ID, + displayName: upload.Owner.DisplayName + }; + } + result.uploads.push(uploadItem); + }); + } + return result; +} +function parseObjectLockConfig(xml) { + const xmlObj = (0, _helper.parseXml)(xml); + let lockConfigResult = {}; + if (xmlObj.ObjectLockConfiguration) { + lockConfigResult = { + objectLockEnabled: xmlObj.ObjectLockConfiguration.ObjectLockEnabled + }; + let retentionResp; + if (xmlObj.ObjectLockConfiguration && xmlObj.ObjectLockConfiguration.Rule && xmlObj.ObjectLockConfiguration.Rule.DefaultRetention) { + retentionResp = xmlObj.ObjectLockConfiguration.Rule.DefaultRetention || {}; + lockConfigResult.mode = retentionResp.Mode; + } + if (retentionResp) { + const isUnitYears = retentionResp.Years; + if (isUnitYears) { + lockConfigResult.validity = isUnitYears; + lockConfigResult.unit = _type.RETENTION_VALIDITY_UNITS.YEARS; + } else { + lockConfigResult.validity = retentionResp.Days; + lockConfigResult.unit = _type.RETENTION_VALIDITY_UNITS.DAYS; + } + } + } + return lockConfigResult; +} +function parseBucketVersioningConfig(xml) { + const xmlObj = (0, _helper.parseXml)(xml); + return xmlObj.VersioningConfiguration; +} + +// Used only in selectObjectContent API. +// extractHeaderType extracts the first half of the header message, the header type. +function extractHeaderType(stream) { + const headerNameLen = Buffer.from(stream.read(1)).readUInt8(); + const headerNameWithSeparator = Buffer.from(stream.read(headerNameLen)).toString(); + const splitBySeparator = (headerNameWithSeparator || '').split(':'); + return splitBySeparator.length >= 1 ? splitBySeparator[1] : ''; +} +function extractHeaderValue(stream) { + const bodyLen = Buffer.from(stream.read(2)).readUInt16BE(); + return Buffer.from(stream.read(bodyLen)).toString(); +} +function parseSelectObjectContentResponse(res) { + const selectResults = new _helpers.SelectResults({}); // will be returned + + const responseStream = (0, _helper.readableStream)(res); // convert byte array to a readable responseStream + // @ts-ignore + while (responseStream._readableState.length) { + // Top level responseStream read tracker. + let msgCrcAccumulator; // accumulate from start of the message till the message crc start. + + const totalByteLengthBuffer = Buffer.from(responseStream.read(4)); + msgCrcAccumulator = _bufferCrc(totalByteLengthBuffer); + const headerBytesBuffer = Buffer.from(responseStream.read(4)); + msgCrcAccumulator = _bufferCrc(headerBytesBuffer, msgCrcAccumulator); + const calculatedPreludeCrc = msgCrcAccumulator.readInt32BE(); // use it to check if any CRC mismatch in header itself. + + const preludeCrcBuffer = Buffer.from(responseStream.read(4)); // read 4 bytes i.e 4+4 =8 + 4 = 12 ( prelude + prelude crc) + msgCrcAccumulator = _bufferCrc(preludeCrcBuffer, msgCrcAccumulator); + const totalMsgLength = totalByteLengthBuffer.readInt32BE(); + const headerLength = headerBytesBuffer.readInt32BE(); + const preludeCrcByteValue = preludeCrcBuffer.readInt32BE(); + if (preludeCrcByteValue !== calculatedPreludeCrc) { + // Handle Header CRC mismatch Error + throw new Error(`Header Checksum Mismatch, Prelude CRC of ${preludeCrcByteValue} does not equal expected CRC of ${calculatedPreludeCrc}`); + } + const headers = {}; + if (headerLength > 0) { + const headerBytes = Buffer.from(responseStream.read(headerLength)); + msgCrcAccumulator = _bufferCrc(headerBytes, msgCrcAccumulator); + const headerReaderStream = (0, _helper.readableStream)(headerBytes); + // @ts-ignore + while (headerReaderStream._readableState.length) { + const headerTypeName = extractHeaderType(headerReaderStream); + headerReaderStream.read(1); // just read and ignore it. + if (headerTypeName) { + headers[headerTypeName] = extractHeaderValue(headerReaderStream); + } + } + } + let payloadStream; + const payLoadLength = totalMsgLength - headerLength - 16; + if (payLoadLength > 0) { + const payLoadBuffer = Buffer.from(responseStream.read(payLoadLength)); + msgCrcAccumulator = _bufferCrc(payLoadBuffer, msgCrcAccumulator); + // read the checksum early and detect any mismatch so we can avoid unnecessary further processing. + const messageCrcByteValue = Buffer.from(responseStream.read(4)).readInt32BE(); + const calculatedCrc = msgCrcAccumulator.readInt32BE(); + // Handle message CRC Error + if (messageCrcByteValue !== calculatedCrc) { + throw new Error(`Message Checksum Mismatch, Message CRC of ${messageCrcByteValue} does not equal expected CRC of ${calculatedCrc}`); + } + payloadStream = (0, _helper.readableStream)(payLoadBuffer); + } + const messageType = headers['message-type']; + switch (messageType) { + case 'error': + { + const errorMessage = headers['error-code'] + ':"' + headers['error-message'] + '"'; + throw new Error(errorMessage); + } + case 'event': + { + const contentType = headers['content-type']; + const eventType = headers['event-type']; + switch (eventType) { + case 'End': + { + selectResults.setResponse(res); + return selectResults; + } + case 'Records': + { + var _payloadStream; + const readData = (_payloadStream = payloadStream) === null || _payloadStream === void 0 ? void 0 : _payloadStream.read(payLoadLength); + selectResults.setRecords(readData); + break; + } + case 'Progress': + { + switch (contentType) { + case 'text/xml': + { + var _payloadStream2; + const progressData = (_payloadStream2 = payloadStream) === null || _payloadStream2 === void 0 ? void 0 : _payloadStream2.read(payLoadLength); + selectResults.setProgress(progressData.toString()); + break; + } + default: + { + const errorMessage = `Unexpected content-type ${contentType} sent for event-type Progress`; + throw new Error(errorMessage); + } + } + } + break; + case 'Stats': + { + switch (contentType) { + case 'text/xml': + { + var _payloadStream3; + const statsData = (_payloadStream3 = payloadStream) === null || _payloadStream3 === void 0 ? void 0 : _payloadStream3.read(payLoadLength); + selectResults.setStats(statsData.toString()); + break; + } + default: + { + const errorMessage = `Unexpected content-type ${contentType} sent for event-type Stats`; + throw new Error(errorMessage); + } + } + } + break; + default: + { + // Continuation message: Not sure if it is supported. did not find a reference or any message in response. + // It does not have a payload. + const warningMessage = `Un implemented event detected ${messageType}.`; + // eslint-disable-next-line no-console + console.warn(warningMessage); + } + } + } + } + } +} +function parseLifecycleConfig(xml) { + const xmlObj = (0, _helper.parseXml)(xml); + return xmlObj.LifecycleConfiguration; +} +function parseBucketEncryptionConfig(xml) { + return (0, _helper.parseXml)(xml); +} +function parseObjectRetentionConfig(xml) { + const xmlObj = (0, _helper.parseXml)(xml); + const retentionConfig = xmlObj.Retention; + return { + mode: retentionConfig.Mode, + retainUntilDate: retentionConfig.RetainUntilDate + }; +} +function removeObjectsParser(xml) { + const xmlObj = (0, _helper.parseXml)(xml); + if (xmlObj.DeleteResult && xmlObj.DeleteResult.Error) { + // return errors as array always. as the response is object in case of single object passed in removeObjects + return (0, _helper.toArray)(xmlObj.DeleteResult.Error); + } + return []; +} + +// parse XML response for copy object +function parseCopyObject(xml) { + const result = { + etag: '', + lastModified: '' + }; + let xmlobj = (0, _helper.parseXml)(xml); + if (!xmlobj.CopyObjectResult) { + throw new errors.InvalidXMLError('Missing tag: "CopyObjectResult"'); + } + xmlobj = xmlobj.CopyObjectResult; + if (xmlobj.ETag) { + result.etag = xmlobj.ETag.replace(/^"/g, '').replace(/"$/g, '').replace(/^"/g, '').replace(/"$/g, '').replace(/^"/g, '').replace(/"$/g, ''); + } + if (xmlobj.LastModified) { + result.lastModified = new Date(xmlobj.LastModified); + } + return result; +} +const formatObjInfo = (content, opts = {}) => { + const { + Key, + LastModified, + ETag, + Size, + VersionId, + IsLatest + } = content; + if (!(0, _helper.isObject)(opts)) { + opts = {}; + } + const name = (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(Key)[0] || ''); + const lastModified = LastModified ? new Date((0, _helper.toArray)(LastModified)[0] || '') : undefined; + const etag = (0, _helper.sanitizeETag)((0, _helper.toArray)(ETag)[0] || ''); + const size = (0, _helper.sanitizeSize)(Size || ''); + return { + name, + lastModified, + etag, + size, + versionId: VersionId, + isLatest: IsLatest, + isDeleteMarker: opts.IsDeleteMarker ? opts.IsDeleteMarker : false + }; +}; + +// parse XML response for list objects in a bucket +function parseListObjects(xml) { + const result = { + objects: [], + isTruncated: false, + nextMarker: undefined, + versionIdMarker: undefined, + keyMarker: undefined + }; + let isTruncated = false; + let nextMarker; + const xmlobj = fxpWithoutNumParser.parse(xml); + const parseCommonPrefixesEntity = commonPrefixEntry => { + if (commonPrefixEntry) { + (0, _helper.toArray)(commonPrefixEntry).forEach(commonPrefix => { + result.objects.push({ + prefix: (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(commonPrefix.Prefix)[0] || ''), + size: 0 + }); + }); + } + }; + const listBucketResult = xmlobj.ListBucketResult; + const listVersionsResult = xmlobj.ListVersionsResult; + if (listBucketResult) { + if (listBucketResult.IsTruncated) { + isTruncated = listBucketResult.IsTruncated; + } + if (listBucketResult.Contents) { + (0, _helper.toArray)(listBucketResult.Contents).forEach(content => { + const name = (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(content.Key)[0] || ''); + const lastModified = new Date((0, _helper.toArray)(content.LastModified)[0] || ''); + const etag = (0, _helper.sanitizeETag)((0, _helper.toArray)(content.ETag)[0] || ''); + const size = (0, _helper.sanitizeSize)(content.Size || ''); + result.objects.push({ + name, + lastModified, + etag, + size + }); + }); + } + if (listBucketResult.Marker) { + nextMarker = listBucketResult.Marker; + } + if (listBucketResult.NextMarker) { + nextMarker = listBucketResult.NextMarker; + } else if (isTruncated && result.objects.length > 0) { + var _result$objects; + nextMarker = (_result$objects = result.objects[result.objects.length - 1]) === null || _result$objects === void 0 ? void 0 : _result$objects.name; + } + if (listBucketResult.CommonPrefixes) { + parseCommonPrefixesEntity(listBucketResult.CommonPrefixes); + } + } + if (listVersionsResult) { + if (listVersionsResult.IsTruncated) { + isTruncated = listVersionsResult.IsTruncated; + } + if (listVersionsResult.Version) { + (0, _helper.toArray)(listVersionsResult.Version).forEach(content => { + result.objects.push(formatObjInfo(content)); + }); + } + if (listVersionsResult.DeleteMarker) { + (0, _helper.toArray)(listVersionsResult.DeleteMarker).forEach(content => { + result.objects.push(formatObjInfo(content, { + IsDeleteMarker: true + })); + }); + } + if (listVersionsResult.NextKeyMarker) { + result.keyMarker = listVersionsResult.NextKeyMarker; + } + if (listVersionsResult.NextVersionIdMarker) { + result.versionIdMarker = listVersionsResult.NextVersionIdMarker; + } + if (listVersionsResult.CommonPrefixes) { + parseCommonPrefixesEntity(listVersionsResult.CommonPrefixes); + } + } + result.isTruncated = isTruncated; + if (isTruncated) { + result.nextMarker = nextMarker; + } + return result; +} +function uploadPartParser(xml) { + const xmlObj = (0, _helper.parseXml)(xml); + const respEl = xmlObj.CopyPartResult; + return respEl; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfYnVmZmVyQ3JjIiwicmVxdWlyZSIsIl9mYXN0WG1sUGFyc2VyIiwiZXJyb3JzIiwiX2ludGVyb3BSZXF1aXJlV2lsZGNhcmQiLCJfaGVscGVycyIsIl9oZWxwZXIiLCJfcmVzcG9uc2UiLCJfdHlwZSIsImUiLCJ0IiwiV2Vha01hcCIsInIiLCJuIiwiX19lc01vZHVsZSIsIm8iLCJpIiwiZiIsIl9fcHJvdG9fXyIsImRlZmF1bHQiLCJoYXMiLCJnZXQiLCJzZXQiLCJoYXNPd25Qcm9wZXJ0eSIsImNhbGwiLCJPYmplY3QiLCJkZWZpbmVQcm9wZXJ0eSIsImdldE93blByb3BlcnR5RGVzY3JpcHRvciIsInBhcnNlQnVja2V0UmVnaW9uIiwieG1sIiwicGFyc2VYbWwiLCJMb2NhdGlvbkNvbnN0cmFpbnQiLCJmeHAiLC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H1cblxuICBpZiAoeG1sb2JqLkNvbnRlbnRzKSB7XG4gICAgdG9BcnJheSh4bWxvYmouQ29udGVudHMpLmZvckVhY2goKGNvbnRlbnQpID0+IHtcbiAgICAgIGNvbnN0IG5hbWUgPSBzYW5pdGl6ZU9iamVjdEtleShjb250ZW50LktleSlcbiAgICAgIGNvbnN0IGxhc3RNb2RpZmllZCA9IG5ldyBEYXRlKGNvbnRlbnQuTGFzdE1vZGlmaWVkKVxuICAgICAgY29uc3QgZXRhZyA9IHNhbml0aXplRVRhZyhjb250ZW50LkVUYWcpXG4gICAgICBjb25zdCBzaXplID0gY29udGVudC5TaXplXG5cbiAgICAgIGxldCB0YWdzOiBUYWdzID0ge31cbiAgICAgIGlmIChjb250ZW50LlVzZXJUYWdzICE9IG51bGwpIHtcbiAgICAgICAgdG9BcnJheShjb250ZW50LlVzZXJUYWdzLnNwbGl0KCcmJykpLmZvckVhY2goKHRhZykgPT4ge1xuICAgICAgICAgIGNvbnN0IFtrZXksIHZhbHVlXSA9IHRhZy5zcGxpdCgnPScpXG4gICAgICAgICAgdGFnc1trZXldID0gdmFsdWVcbiAgICAgICAgfSlcbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIHRhZ3MgPSB7fVxuICAgICAgfVxuXG4gICAgICBsZXQgbWV0YWRhdGFcbiAgICAgIGlmIChjb250ZW50LlVzZXJNZXRhZGF0YSAhPSBudWxsKSB7XG4gICAgICAgIG1ldGFkYXRhID0gdG9BcnJheShjb250ZW50LlVzZXJNZXRhZGF0YSlbMF1cbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIG1ldGFkYXRhID0gbnVsbFxuICAgICAgfVxuICAgICAgcmVzdWx0Lm9iamVjdHMucHVzaCh7IG5hbWUsIGxhc3RNb2RpZmllZCwgZXRhZywgc2l6ZSwgbWV0YWRhdGEsIHRhZ3MgfSlcbiAgICB9KVxuICB9XG5cbiAgaWYgKHhtbG9iai5Db21tb25QcmVmaXhlcykge1xuICAgIHRvQXJyYXko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ZVZhbHVlfSBkb2VzIG5vdCBlcXVhbCBleHBlY3RlZCBDUkMgb2YgJHtjYWxjdWxhdGVkQ3JjfWAsXG4gICAgICAgIClcbiAgICAgIH1cbiAgICAgIHBheWxvYWRTdHJlYW0gPSByZWFkYWJsZVN0cmVhbShwYXlMb2FkQnVmZmVyKVxuICAgIH1cbiAgICBjb25zdCBtZXNzYWdlVHlwZSA9IGhlYWRlcnNbJ21lc3NhZ2UtdHlwZSddXG5cbiAgICBzd2l0Y2ggKG1lc3NhZ2VUeXBlKSB7XG4gICAgICBjYXNlICdlcnJvcic6IHtcbiAgICAgICAgY29uc3QgZXJyb3JNZXNzYWdlID0gaGVhZGVyc1snZXJyb3ItY29kZSddICsgJzpcIicgKyBoZWFkZXJzWydlcnJvci1tZXNzYWdlJ10gKyAnXCInXG4gICAgICAgIHRocm93IG5ldyBFcnJvcihlcnJvck1lc3NhZ2UpXG4gICAgICB9XG4gICAgICBjYXNlICdldmVudCc6IHtcbiAgICAgICAgY29uc3QgY29udGVudFR5cGUgPSBoZWFkZXJzWydjb250ZW50LXR5cGUnXVxuICAgICAgICBjb25zdCBldmVudFR5cGUgPSBoZWFkZXJzWydldmVudC10eXBlJ11cblxuICAgICAgICBzd2l0Y2ggKGV2ZW50VHlwZSkge1xuICAgICAgICAgIGNhc2UgJ0VuZCc6IHtcbiAgICAgICAgICAgIHNlbGVjdFJlc3VsdHMuc2V0UmVzcG9uc2UocmVzKVxuICAgICAgICAgICAgcmV0dXJuIHNlbGVjdFJlc3VsdHNcbiAgICAgICAgICB9XG5cbiAgICAgICAgICBjYXNlICdSZWNvcmRzJzoge1xuICAgICAgICAgICAgY29uc3QgcmVhZERhdGEgPSBwYXlsb2FkU3RyZWFtPy5yZWFkKHBheUxvYWRMZW5ndGgpXG4gICAgICAgICAgICBzZWxlY3RSZXN1bHRzLnNldFJlY29yZHMocmVhZERhdGEpXG4gICAgICAgICAgICBicmVha1xuICAgICAgICAgIH1cblxuICAgICAgICAgIGNhc2UgJ1Byb2dyZXNzJzpcbiAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgc3dpdGNoIChjb250ZW50VHlwZSkge1xuICAgICAgICAgICAgICAgIGNhc2UgJ3RleHQveG1sJzoge1xuICAgICAgICAgICAgICAgICAgY29uc3QgcHJvZ3Jlc3NEYXRhID0gcGF5bG9hZFN0cmVhbT8ucmVhZChwYXlMb2FkTGVuZ3RoKVxuICAgICAgICAgICAgICAgICAgc2VsZWN0UmVzdWx0cy5zZXRQcm9ncmVzcyhwcm9ncmVzc0RhdGEudG9TdHJpbmcoKSlcbiAgICAgICAgICAgICAgICAgIGJyZWFrXG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIGRlZmF1bHQ6IHtcbiAgICAgICAgICAgICAgICAgIGNvbnN0IGVycm9yTWVzc2FnZSA9IGBVbmV4cGVjdGVkIGNvbnRlbnQtdHlwZSAke2NvbnRlbnRUeXBlfSBzZW50IGZvciBldmVudC10eXBlIFByb2dyZXNzYFxuICAgICAgICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKGVycm9yTWVzc2FnZSlcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGJyZWFrXG4gICAgICAgICAgY2FzZSAnU3RhdHMnOlxuICAgICAgICAgICAge1xuICAgICAgICAgICAgICBzd2l0Y2ggKGNvbnRlbnRUeXBlKSB7XG4gICAgICAgICAgICAgICAgY2FzZSAndGV4dC94bWwnOiB7XG4gICAgICAgICAgICAgICAgICBjb25zdCBzdGF0c0RhdGEgPSBwYXlsb2FkU3RyZWFtPy5yZWFkKHBheUxvYWRMZW5ndGgpXG4gICAgICAgICAgICAgICAgICBzZWxlY3RSZXN1bHRzLnNldFN0YXRzKHN0YXRzRGF0YS50b1N0cmluZygpKVxuICAgICAgICAgICAgICAgICAgYnJlYWtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgZGVmYXVsdDo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ix5QkFBeUIsQ0FBQ0csa0JBQWtCLENBQUN0TixjQUFjLENBQUM7SUFDOUQ7RUFDRjtFQUVBOUIsTUFBTSxDQUFDRSxXQUFXLEdBQUdBLFdBQVc7RUFDaEMsSUFBSUEsV0FBVyxFQUFFO0lBQ2ZGLE1BQU0sQ0FBQzhPLFVBQVUsR0FBR0EsVUFBVTtFQUNoQztFQUNBLE9BQU85TyxNQUFNO0FBQ2Y7QUFFTyxTQUFTNFAsZ0JBQWdCQSxDQUFDL1IsR0FBVyxFQUFFO0VBQzVDLE1BQU1XLE1BQU0sR0FBRyxJQUFBVixnQkFBUSxFQUFDRCxHQUFHLENBQUM7RUFDNUIsTUFBTWdTLE1BQU0sR0FBR3JSLE1BQU0sQ0FBQ3NSLGNBQWM7RUFDcEMsT0FBT0QsTUFBTTtBQUNmIn0= \ No newline at end of file diff --git a/node_modules/minio/dist/main/minio.d.ts b/node_modules/minio/dist/main/minio.d.ts new file mode 100644 index 0000000..11a5c4b --- /dev/null +++ b/node_modules/minio/dist/main/minio.d.ts @@ -0,0 +1,40 @@ +import type { LEGAL_HOLD_STATUS, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from "./helpers.js"; +import { TypedClient } from "./internal/client.js"; +import { CopyConditions } from "./internal/copy-conditions.js"; +import { PostPolicy } from "./internal/post-policy.js"; +export * from "./errors.js"; +export * from "./helpers.js"; +export * from "./notification.js"; +export { CopyConditions, PostPolicy }; +export { IamAwsProvider } from "./IamAwsProvider.js"; +export type { MakeBucketOpt } from "./internal/client.js"; +export type { ClientOptions, NoResultCallback, RemoveOptions } from "./internal/client.js"; +export type { Region } from "./internal/s3-endpoints.js"; +export type { BucketItem, BucketItemCopy, BucketItemFromList, BucketItemStat, BucketItemWithMetadata, BucketStream, EmptyObject, ExistingObjectReplication, GetObjectLegalHoldOptions, IncompleteUploadedBucketItem, InputSerialization, IsoDate, ItemBucketMetadata, ItemBucketMetadataList, LegalHoldStatus, LifecycleConfig, LifecycleRule, MetadataItem, ObjectLockInfo, OutputSerialization, PostPolicyResult, PutObjectLegalHoldOptions, ReplicaModifications, ReplicationConfig, ReplicationConfigOpts, ReplicationRule, ReplicationRuleAnd, ReplicationRuleDestination, ReplicationRuleFilter, ReplicationRuleStatus, Retention, RetentionOptions, ScanRange, SelectOptions, SelectProgress, SourceSelectionCriteria, Tag } from "./internal/type.js"; +/** + * @deprecated keep for backward compatible, use `RETENTION_MODES` instead + */ +export type Mode = RETENTION_MODES; +/** + * @deprecated keep for backward compatible + */ +export type LockUnit = RETENTION_VALIDITY_UNITS; +export type VersioningConfig = Record; +export type TagList = Record; +export interface LockConfig { + mode: RETENTION_MODES; + unit: RETENTION_VALIDITY_UNITS; + validity: number; +} +export interface LegalHoldOptions { + versionId: string; + status: LEGAL_HOLD_STATUS; +} +export interface SourceObjectStats { + size: number; + metaData: string; + lastModicied: Date; + versionId: string; + etag: string; +} +export declare class Client extends TypedClient {} \ No newline at end of file diff --git a/node_modules/minio/dist/main/minio.js b/node_modules/minio/dist/main/minio.js new file mode 100644 index 0000000..3138e1c --- /dev/null +++ b/node_modules/minio/dist/main/minio.js @@ -0,0 +1,117 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + IamAwsProvider: true, + Client: true, + CopyConditions: true, + PostPolicy: true +}; +var _callbackify = require("./internal/callbackify.js"); +var _client = require("./internal/client.js"); +var _copyConditions = require("./internal/copy-conditions.js"); +exports.CopyConditions = _copyConditions.CopyConditions; +var _postPolicy = require("./internal/post-policy.js"); +exports.PostPolicy = _postPolicy.PostPolicy; +var _errors = require("./errors.js"); +Object.keys(_errors).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _errors[key]) return; + exports[key] = _errors[key]; +}); +var _helpers = require("./helpers.js"); +Object.keys(_helpers).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _helpers[key]) return; + exports[key] = _helpers[key]; +}); +var _notification = require("./notification.js"); +Object.keys(_notification).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _notification[key]) return; + exports[key] = _notification[key]; +}); +var _IamAwsProvider = require("./IamAwsProvider.js"); +exports.IamAwsProvider = _IamAwsProvider.IamAwsProvider; +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @deprecated keep for backward compatible, use `RETENTION_MODES` instead + */ + +/** + * @deprecated keep for backward compatible + */ + +class Client extends _client.TypedClient {} + +// refactored API use promise internally +exports.Client = Client; +Client.prototype.makeBucket = (0, _callbackify.callbackify)(Client.prototype.makeBucket); +Client.prototype.bucketExists = (0, _callbackify.callbackify)(Client.prototype.bucketExists); +Client.prototype.removeBucket = (0, _callbackify.callbackify)(Client.prototype.removeBucket); +Client.prototype.listBuckets = (0, _callbackify.callbackify)(Client.prototype.listBuckets); +Client.prototype.getObject = (0, _callbackify.callbackify)(Client.prototype.getObject); +Client.prototype.fGetObject = (0, _callbackify.callbackify)(Client.prototype.fGetObject); +Client.prototype.getPartialObject = (0, _callbackify.callbackify)(Client.prototype.getPartialObject); +Client.prototype.statObject = (0, _callbackify.callbackify)(Client.prototype.statObject); +Client.prototype.putObjectRetention = (0, _callbackify.callbackify)(Client.prototype.putObjectRetention); +Client.prototype.putObject = (0, _callbackify.callbackify)(Client.prototype.putObject); +Client.prototype.fPutObject = (0, _callbackify.callbackify)(Client.prototype.fPutObject); +Client.prototype.removeObject = (0, _callbackify.callbackify)(Client.prototype.removeObject); +Client.prototype.removeBucketReplication = (0, _callbackify.callbackify)(Client.prototype.removeBucketReplication); +Client.prototype.setBucketReplication = (0, _callbackify.callbackify)(Client.prototype.setBucketReplication); +Client.prototype.getBucketReplication = (0, _callbackify.callbackify)(Client.prototype.getBucketReplication); +Client.prototype.getObjectLegalHold = (0, _callbackify.callbackify)(Client.prototype.getObjectLegalHold); +Client.prototype.setObjectLegalHold = (0, _callbackify.callbackify)(Client.prototype.setObjectLegalHold); +Client.prototype.setObjectLockConfig = (0, _callbackify.callbackify)(Client.prototype.setObjectLockConfig); +Client.prototype.getObjectLockConfig = (0, _callbackify.callbackify)(Client.prototype.getObjectLockConfig); +Client.prototype.getBucketPolicy = (0, _callbackify.callbackify)(Client.prototype.getBucketPolicy); +Client.prototype.setBucketPolicy = (0, _callbackify.callbackify)(Client.prototype.setBucketPolicy); +Client.prototype.getBucketTagging = (0, _callbackify.callbackify)(Client.prototype.getBucketTagging); +Client.prototype.getObjectTagging = (0, _callbackify.callbackify)(Client.prototype.getObjectTagging); +Client.prototype.setBucketTagging = (0, _callbackify.callbackify)(Client.prototype.setBucketTagging); +Client.prototype.removeBucketTagging = (0, _callbackify.callbackify)(Client.prototype.removeBucketTagging); +Client.prototype.setObjectTagging = (0, _callbackify.callbackify)(Client.prototype.setObjectTagging); +Client.prototype.removeObjectTagging = (0, _callbackify.callbackify)(Client.prototype.removeObjectTagging); +Client.prototype.getBucketVersioning = (0, _callbackify.callbackify)(Client.prototype.getBucketVersioning); +Client.prototype.setBucketVersioning = (0, _callbackify.callbackify)(Client.prototype.setBucketVersioning); +Client.prototype.selectObjectContent = (0, _callbackify.callbackify)(Client.prototype.selectObjectContent); +Client.prototype.setBucketLifecycle = (0, _callbackify.callbackify)(Client.prototype.setBucketLifecycle); +Client.prototype.getBucketLifecycle = (0, _callbackify.callbackify)(Client.prototype.getBucketLifecycle); +Client.prototype.removeBucketLifecycle = (0, _callbackify.callbackify)(Client.prototype.removeBucketLifecycle); +Client.prototype.setBucketEncryption = (0, _callbackify.callbackify)(Client.prototype.setBucketEncryption); +Client.prototype.getBucketEncryption = (0, _callbackify.callbackify)(Client.prototype.getBucketEncryption); +Client.prototype.removeBucketEncryption = (0, _callbackify.callbackify)(Client.prototype.removeBucketEncryption); +Client.prototype.getObjectRetention = (0, _callbackify.callbackify)(Client.prototype.getObjectRetention); +Client.prototype.removeObjects = (0, _callbackify.callbackify)(Client.prototype.removeObjects); +Client.prototype.removeIncompleteUpload = (0, _callbackify.callbackify)(Client.prototype.removeIncompleteUpload); +Client.prototype.copyObject = (0, _callbackify.callbackify)(Client.prototype.copyObject); +Client.prototype.composeObject = (0, _callbackify.callbackify)(Client.prototype.composeObject); +Client.prototype.presignedUrl = (0, _callbackify.callbackify)(Client.prototype.presignedUrl); +Client.prototype.presignedGetObject = (0, _callbackify.callbackify)(Client.prototype.presignedGetObject); +Client.prototype.presignedPutObject = (0, _callbackify.callbackify)(Client.prototype.presignedPutObject); +Client.prototype.presignedPostPolicy = (0, _callbackify.callbackify)(Client.prototype.presignedPostPolicy); +Client.prototype.setBucketNotification = (0, _callbackify.callbackify)(Client.prototype.setBucketNotification); +Client.prototype.getBucketNotification = (0, _callbackify.callbackify)(Client.prototype.getBucketNotification); +Client.prototype.removeAllBucketNotification = (0, _callbackify.callbackify)(Client.prototype.removeAllBucketNotification); +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfY2FsbGJhY2tpZnkiLCJyZXF1aXJlIiwiX2NsaWVudCIsIl9jb3B5Q29uZGl0aW9ucyIsImV4cG9ydHMiLCJDb3B5Q29uZGl0aW9ucyIsIl9wb3N0UG9saWN5IiwiUG9zdFBvbGljeSIsIl9lcnJvcnMiLCJPYmplY3QiLCJrZXlzIiwiZm9yRWFjaCIsImtleSIsInByb3RvdHlwZSIsImhhc093blByb3BlcnR5IiwiY2FsbCIsIl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FHLElBQUF6Qyx3QkFBVyxFQUFDSCxNQUFNLENBQUNSLFNBQVMsQ0FBQ29ELFlBQVksQ0FBQztBQUMxRTVDLE1BQU0sQ0FBQ1IsU0FBUyxDQUFDcUQsa0JBQWtCLEdBQUcsSUFBQTFDLHdCQUFXLEVBQUNILE1BQU0sQ0FBQ1IsU0FBUyxDQUFDcUQsa0JBQWtCLENBQUM7QUFDdEY3QyxNQUFNLENBQUNSLFNBQVMsQ0FBQ3NELGtCQUFrQixHQUFHLElBQUEzQyx3QkFBVyxFQUFDSCxNQUFNLENBQUNSLFNBQVMsQ0FBQ3NELGtCQUFrQixDQUFDO0FBQ3RGOUMsTUFBTSxDQUFDUixTQUFTLENBQUN1RCxtQkFBbUIsR0FBRyxJQUFBNUMsd0JBQVcsRUFBQ0gsTUFBTSxDQUFDUixTQUFTLENBQUN1RCxtQkFBbUIsQ0FBQztBQUN4Ri9DLE1BQU0sQ0FBQ1IsU0FBUyxDQUFDd0QscUJBQXFCLEdBQUcsSUFBQTdDLHdCQUFXLEVBQUNILE1BQU0sQ0FBQ1IsU0FBUyxDQUFDd0QscUJBQXFCLENBQUM7QUFDNUZoRCxNQUFNLENBQUNSLFNBQVMsQ0FBQ3lELHFCQUFxQixHQUFHLElBQUE5Qyx3QkFBVyxFQUFDSCxNQUFNLENBQUNSLFNBQVMsQ0FBQ3lELHFCQUFxQixDQUFDO0FBQzVGakQsTUFBTSxDQUFDUixTQUFTLENBQUMwRCwyQkFBMkIsR0FBRyxJQUFBL0Msd0JBQVcsRUFBQ0gsTUFBTSxDQUFDUixTQUFTLENBQUMwRCwyQkFBMkIsQ0FBQyJ9 \ No newline at end of file diff --git a/node_modules/minio/dist/main/notification.d.ts b/node_modules/minio/dist/main/notification.d.ts new file mode 100644 index 0000000..e31d2e2 --- /dev/null +++ b/node_modules/minio/dist/main/notification.d.ts @@ -0,0 +1,58 @@ +import { EventEmitter } from 'eventemitter3'; +import type { TypedClient } from "./internal/client.js"; +type Event = unknown; +export declare class TargetConfig { + private Filter?; + private Event?; + private Id; + setId(id: unknown): void; + addEvent(newevent: Event): void; + addFilterSuffix(suffix: string): void; + addFilterPrefix(prefix: string): void; +} +export declare class TopicConfig extends TargetConfig { + private Topic; + constructor(arn: string); +} +export declare class QueueConfig extends TargetConfig { + private Queue; + constructor(arn: string); +} +export declare class CloudFunctionConfig extends TargetConfig { + private CloudFunction; + constructor(arn: string); +} +export declare class NotificationConfig { + private TopicConfiguration?; + private CloudFunctionConfiguration?; + private QueueConfiguration?; + add(target: TargetConfig): void; +} +export declare const buildARN: (partition: string, service: string, region: string, accountId: string, resource: string) => string; +export declare const ObjectCreatedAll = "s3:ObjectCreated:*"; +export declare const ObjectCreatedPut = "s3:ObjectCreated:Put"; +export declare const ObjectCreatedPost = "s3:ObjectCreated:Post"; +export declare const ObjectCreatedCopy = "s3:ObjectCreated:Copy"; +export declare const ObjectCreatedCompleteMultipartUpload = "s3:ObjectCreated:CompleteMultipartUpload"; +export declare const ObjectRemovedAll = "s3:ObjectRemoved:*"; +export declare const ObjectRemovedDelete = "s3:ObjectRemoved:Delete"; +export declare const ObjectRemovedDeleteMarkerCreated = "s3:ObjectRemoved:DeleteMarkerCreated"; +export declare const ObjectReducedRedundancyLostObject = "s3:ReducedRedundancyLostObject"; +export type NotificationEvent = 's3:ObjectCreated:*' | 's3:ObjectCreated:Put' | 's3:ObjectCreated:Post' | 's3:ObjectCreated:Copy' | 's3:ObjectCreated:CompleteMultipartUpload' | 's3:ObjectRemoved:*' | 's3:ObjectRemoved:Delete' | 's3:ObjectRemoved:DeleteMarkerCreated' | 's3:ReducedRedundancyLostObject' | 's3:TestEvent' | 's3:ObjectRestore:Post' | 's3:ObjectRestore:Completed' | 's3:Replication:OperationFailedReplication' | 's3:Replication:OperationMissedThreshold' | 's3:Replication:OperationReplicatedAfterThreshold' | 's3:Replication:OperationNotTracked' | string; +export type NotificationRecord = unknown; +export declare class NotificationPoller extends EventEmitter<{ + notification: (event: NotificationRecord) => void; + error: (error: unknown) => void; +}> { + private client; + private bucketName; + private prefix; + private suffix; + private events; + private ending; + constructor(client: TypedClient, bucketName: string, prefix: string, suffix: string, events: NotificationEvent[]); + start(): void; + stop(): void; + checkForChanges(): void; +} +export {}; \ No newline at end of file diff --git a/node_modules/minio/dist/main/notification.js b/node_modules/minio/dist/main/notification.js new file mode 100644 index 0000000..8d8e8b3 --- /dev/null +++ b/node_modules/minio/dist/main/notification.js @@ -0,0 +1,230 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _eventemitter = require("eventemitter3"); +var _Parser = require("stream-json/jsonl/Parser.js"); +var _helpers = require("./helpers.js"); +var _helper = require("./internal/helper.js"); +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2016 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// TODO: type this + +// Base class for three supported configs. +class TargetConfig { + setId(id) { + this.Id = id; + } + addEvent(newevent) { + if (!this.Event) { + this.Event = []; + } + this.Event.push(newevent); + } + addFilterSuffix(suffix) { + if (!this.Filter) { + this.Filter = { + S3Key: { + FilterRule: [] + } + }; + } + this.Filter.S3Key.FilterRule.push({ + Name: 'suffix', + Value: suffix + }); + } + addFilterPrefix(prefix) { + if (!this.Filter) { + this.Filter = { + S3Key: { + FilterRule: [] + } + }; + } + this.Filter.S3Key.FilterRule.push({ + Name: 'prefix', + Value: prefix + }); + } +} + +// 1. Topic (simple notification service) +exports.TargetConfig = TargetConfig; +class TopicConfig extends TargetConfig { + constructor(arn) { + super(); + this.Topic = arn; + } +} + +// 2. Queue (simple queue service) +exports.TopicConfig = TopicConfig; +class QueueConfig extends TargetConfig { + constructor(arn) { + super(); + this.Queue = arn; + } +} + +// 3. CloudFront (lambda function) +exports.QueueConfig = QueueConfig; +class CloudFunctionConfig extends TargetConfig { + constructor(arn) { + super(); + this.CloudFunction = arn; + } +} + +// Notification config - array of target configs. +// Target configs can be +// 1. Topic (simple notification service) +// 2. Queue (simple queue service) +// 3. CloudFront (lambda function) +exports.CloudFunctionConfig = CloudFunctionConfig; +class NotificationConfig { + add(target) { + let instance; + if (target instanceof TopicConfig) { + instance = this.TopicConfiguration ?? (this.TopicConfiguration = []); + } + if (target instanceof QueueConfig) { + instance = this.QueueConfiguration ?? (this.QueueConfiguration = []); + } + if (target instanceof CloudFunctionConfig) { + instance = this.CloudFunctionConfiguration ?? (this.CloudFunctionConfiguration = []); + } + if (instance) { + instance.push(target); + } + } +} +exports.NotificationConfig = NotificationConfig; +const buildARN = (partition, service, region, accountId, resource) => { + return 'arn:' + partition + ':' + service + ':' + region + ':' + accountId + ':' + resource; +}; +exports.buildARN = buildARN; +const ObjectCreatedAll = 's3:ObjectCreated:*'; +exports.ObjectCreatedAll = ObjectCreatedAll; +const ObjectCreatedPut = 's3:ObjectCreated:Put'; +exports.ObjectCreatedPut = ObjectCreatedPut; +const ObjectCreatedPost = 's3:ObjectCreated:Post'; +exports.ObjectCreatedPost = ObjectCreatedPost; +const ObjectCreatedCopy = 's3:ObjectCreated:Copy'; +exports.ObjectCreatedCopy = ObjectCreatedCopy; +const ObjectCreatedCompleteMultipartUpload = 's3:ObjectCreated:CompleteMultipartUpload'; +exports.ObjectCreatedCompleteMultipartUpload = ObjectCreatedCompleteMultipartUpload; +const ObjectRemovedAll = 's3:ObjectRemoved:*'; +exports.ObjectRemovedAll = ObjectRemovedAll; +const ObjectRemovedDelete = 's3:ObjectRemoved:Delete'; +exports.ObjectRemovedDelete = ObjectRemovedDelete; +const ObjectRemovedDeleteMarkerCreated = 's3:ObjectRemoved:DeleteMarkerCreated'; +exports.ObjectRemovedDeleteMarkerCreated = ObjectRemovedDeleteMarkerCreated; +const ObjectReducedRedundancyLostObject = 's3:ReducedRedundancyLostObject'; + +// put string at least so auto-complete could work + +// TODO: type this +exports.ObjectReducedRedundancyLostObject = ObjectReducedRedundancyLostObject; +// Poll for notifications, used in #listenBucketNotification. +// Listening constitutes repeatedly requesting s3 whether or not any +// changes have occurred. +class NotificationPoller extends _eventemitter.EventEmitter { + constructor(client, bucketName, prefix, suffix, events) { + super(); + this.client = client; + this.bucketName = bucketName; + this.prefix = prefix; + this.suffix = suffix; + this.events = events; + this.ending = false; + } + + // Starts the polling. + start() { + this.ending = false; + process.nextTick(() => { + this.checkForChanges(); + }); + } + + // Stops the polling. + stop() { + this.ending = true; + } + checkForChanges() { + // Don't continue if we're looping again but are cancelled. + if (this.ending) { + return; + } + const method = 'GET'; + const queries = []; + if (this.prefix) { + const prefix = (0, _helper.uriEscape)(this.prefix); + queries.push(`prefix=${prefix}`); + } + if (this.suffix) { + const suffix = (0, _helper.uriEscape)(this.suffix); + queries.push(`suffix=${suffix}`); + } + if (this.events) { + this.events.forEach(s3event => queries.push('events=' + (0, _helper.uriEscape)(s3event))); + } + queries.sort(); + let query = ''; + if (queries.length > 0) { + query = `${queries.join('&')}`; + } + const region = this.client.region || _helpers.DEFAULT_REGION; + this.client.makeRequestAsync({ + method, + bucketName: this.bucketName, + query + }, '', [200], region).then(response => { + const asm = _Parser.make(); + (0, _helper.pipesetup)(response, asm).on('data', data => { + // Data is flushed periodically (every 5 seconds), so we should + // handle it after flushing from the JSON parser. + let records = data.value.Records; + // If null (= no records), change to an empty array. + if (!records) { + records = []; + } + + // Iterate over the notifications and emit them individually. + records.forEach(record => { + this.emit('notification', record); + }); + + // If we're done, stop. + if (this.ending) { + response === null || response === void 0 ? void 0 : response.destroy(); + } + }).on('error', e => this.emit('error', e)).on('end', () => { + // Do it again, if we haven't cancelled yet. + process.nextTick(() => { + this.checkForChanges(); + }); + }); + }, e => { + return this.emit('error', e); + }); + } +} +exports.NotificationPoller = NotificationPoller; +//#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IHRoZSBKU09OIHBhcnNlci5cbiAgICAgICAgICAgIGxldCByZWNvcmRzID0gZGF0YS52YWx1ZS5SZWNvcmRzXG4gICAgICAgICAgICAvLyBJZiBudWxsICg9IG5vIHJlY29yZHMpLCBjaGFuZ2UgdG8gYW4gZW1wdHkgYXJyYXkuXG4gICAgICAgICAgICBpZiAoIXJlY29yZHMpIHtcbiAgICAgICAgICAgICAgcmVjb3JkcyA9IFtdXG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIC8vIEl0ZXJhdGUgb3ZlciB0aGUgbm90aWZpY2F0aW9ucyBhbmQgZW1pdCB0aGVtIGluZGl2aWR1YWxseS5cbiAgICAgICAgICAgIHJlY29yZHMuZm9yRWFjaCgocmVjb3JkOiBOb3RpZmljYXRpb25SZWNvcmQpID0+IHtcbiAgICAgICAgICAgICAgdGhpcy5lbWl0KCdub3RpZmljYXRpb24nLCByZWNvcmQpXG4gICAgICAgICAgICB9KVxuXG4gICAgICAgICAgICAvLyBJZiB3ZSdyZSBkb25lLCBzdG9wLlxuICAgICAgICAgICAgaWYgKHRoaXMuZW5kaW5nKSB7XG4gICAgICAgICAgICAgIHJlc3BvbnNlPy5kZXN0cm95KClcbiAgICAgICAgICAgIH1cbiAgICAgICAgICB9KVxuICAgICAgICAgIC5vbignZXJyb3InLCAoZSkgPT4gdGhpcy5lbWl0KCdlcnJvcicsIGUpKVxuICAgICAgICAgIC5vbignZW5kJywgKCkgPT4ge1xuICAgICAgICAgICAgLy8gRG8gaXQgYWdhaW4sIGlmIHdlIGhhdmVuJ3QgY2FuY2VsbGVkIHlldC5cbiAgICAgICAgICAgIHByb2Nlc3MubmV4dFRpY2soKCkgPT4ge1xuICAgICAgICAgICAgICB0aGlzLmNoZWNrRm9yQ2hhbmdlcygpXG4gICAgICAgICAgICB9KVxuICAgICAgICAgIH0pXG4gICAgICB9LFxuICAgICAgKGUpID0+IHtcbiAgICAgICAgcmV0dXJuIHRoaXMuZW1pdCgnZXJyb3InLCBlKV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0EsSUFBSUMsT0FBTyxHQUFHRCxJQUFJLENBQUNFLEtBQUssQ0FBQ0MsT0FBTztRQUNoQztRQUNBLElBQUksQ0FBQ0YsT0FBTyxFQUFFO1VBQ1pBLE9BQU8sR0FBRyxFQUFFO1FBQ2Q7O1FBRUE7UUFDQUEsT0FBTyxDQUFDaEIsT0FBTyxDQUFFbUIsTUFBMEIsSUFBSztVQUM5QyxJQUFJLENBQUNDLElBQUksQ0FBQyxjQUFjLEVBQUVELE1BQU0sQ0FBQztRQUNuQyxDQUFDLENBQUM7O1FBRUY7UUFDQSxJQUFJLElBQUksQ0FBQzVCLE1BQU0sRUFBRTtVQUNma0IsUUFBUSxhQUFSQSxRQUFRLHVCQUFSQSxRQUFRLENBQUVZLE9BQU8sQ0FBQyxDQUFDO1FBQ3JCO01BQ0YsQ0FBQyxDQUFDLENBQ0RQLEVBQUUsQ0FBQyxPQUFPLEVBQUdRLENBQUMsSUFBSyxJQUFJLENBQUNGLElBQUksQ0FBQyxPQUFPLEVBQUVFLENBQUMsQ0FBQyxDQUFDLENBQ3pDUixFQUFFLENBQUMsS0FBSyxFQUFFLE1BQU07UUFDZjtRQUNBckIsT0FBTyxDQUFDQyxRQUFRLENBQUMsTUFBTTtVQUNyQixJQUFJLENBQUNDLGVBQWUsQ0FBQyxDQUFDO1FBQ3hCLENBQUMsQ0FBQztNQUNKLENBQUMsQ0FBQztJQUNOLENBQUMsRUFDQTJCLENBQUMsSUFBSztNQUNMLE9BQU8sSUFBSSxDQUFDRixJQUFJLENBQUMsT0FBTyxFQUFFRSxDQUFDLENBQUM7SUFDOUIsQ0FDRixDQUFDO0VBQ0g7QUFDRjtBQUFDbkUsT0FBQSxDQUFBK0Isa0JBQUEsR0FBQUEsa0JBQUEifQ== \ No newline at end of file diff --git a/node_modules/minio/dist/main/signing.d.ts b/node_modules/minio/dist/main/signing.d.ts new file mode 100644 index 0000000..0cbfd70 --- /dev/null +++ b/node_modules/minio/dist/main/signing.d.ts @@ -0,0 +1,5 @@ +import type { IRequest } from "./internal/type.js"; +export declare function postPresignSignatureV4(region: string, date: Date, secretKey: string, policyBase64: string): string; +export declare function signV4(request: IRequest, accessKey: string, secretKey: string, region: string, requestDate: Date, sha256sum: string, serviceName?: string): string; +export declare function signV4ByServiceName(request: IRequest, accessKey: string, secretKey: string, region: string, requestDate: Date, contentSha256: string, serviceName?: string): string; +export declare function presignSignatureV4(request: IRequest, accessKey: string, secretKey: string, sessionToken: string | undefined, region: string, requestDate: Date, expires: number | undefined): string; \ No newline at end of file diff --git a/node_modules/minio/dist/main/signing.js b/node_modules/minio/dist/main/signing.js new file mode 100644 index 0000000..9203adb --- /dev/null +++ b/node_modules/minio/dist/main/signing.js @@ -0,0 +1,268 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.postPresignSignatureV4 = postPresignSignatureV4; +exports.presignSignatureV4 = presignSignatureV4; +exports.signV4 = signV4; +exports.signV4ByServiceName = signV4ByServiceName; +var crypto = _interopRequireWildcard(require("crypto"), true); +var errors = _interopRequireWildcard(require("./errors.js"), true); +var _helpers = require("./helpers.js"); +var _helper = require("./internal/helper.js"); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2016 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const signV4Algorithm = 'AWS4-HMAC-SHA256'; + +// getCanonicalRequest generate a canonical request of style. +// +// canonicalRequest = +// \n +// \n +// \n +// \n +// \n +// +// +function getCanonicalRequest(method, path, headers, signedHeaders, hashedPayload) { + if (!(0, _helper.isString)(method)) { + throw new TypeError('method should be of type "string"'); + } + if (!(0, _helper.isString)(path)) { + throw new TypeError('path should be of type "string"'); + } + if (!(0, _helper.isObject)(headers)) { + throw new TypeError('headers should be of type "object"'); + } + if (!Array.isArray(signedHeaders)) { + throw new TypeError('signedHeaders should be of type "array"'); + } + if (!(0, _helper.isString)(hashedPayload)) { + throw new TypeError('hashedPayload should be of type "string"'); + } + const headersArray = signedHeaders.reduce((acc, i) => { + // Trim spaces from the value (required by V4 spec) + const val = `${headers[i]}`.replace(/ +/g, ' '); + acc.push(`${i.toLowerCase()}:${val}`); + return acc; + }, []); + const requestResource = path.split('?')[0]; + let requestQuery = path.split('?')[1]; + if (!requestQuery) { + requestQuery = ''; + } + if (requestQuery) { + requestQuery = requestQuery.split('&').sort().map(element => !element.includes('=') ? element + '=' : element).join('&'); + } + return [method.toUpperCase(), requestResource, requestQuery, headersArray.join('\n') + '\n', signedHeaders.join(';').toLowerCase(), hashedPayload].join('\n'); +} + +// generate a credential string +function getCredential(accessKey, region, requestDate, serviceName = 's3') { + if (!(0, _helper.isString)(accessKey)) { + throw new TypeError('accessKey should be of type "string"'); + } + if (!(0, _helper.isString)(region)) { + throw new TypeError('region should be of type "string"'); + } + if (!(0, _helper.isObject)(requestDate)) { + throw new TypeError('requestDate should be of type "object"'); + } + return `${accessKey}/${(0, _helper.getScope)(region, requestDate, serviceName)}`; +} + +// Returns signed headers array - alphabetically sorted +function getSignedHeaders(headers) { + if (!(0, _helper.isObject)(headers)) { + throw new TypeError('request should be of type "object"'); + } + // Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258 + // + // User-Agent: + // + // This is ignored from signing because signing this causes problems with generating pre-signed URLs + // (that are executed by other agents) or when customers pass requests through proxies, which may + // modify the user-agent. + // + // Content-Length: + // + // This is ignored from signing because generating a pre-signed URL should not provide a content-length + // constraint, specifically when vending a S3 pre-signed PUT URL. The corollary to this is that when + // sending regular requests (non-pre-signed), the signature contains a checksum of the body, which + // implicitly validates the payload length (since changing the number of bytes would change the checksum) + // and therefore this header is not valuable in the signature. + // + // Content-Type: + // + // Signing this header causes quite a number of problems in browser environments, where browsers + // like to modify and normalize the content-type header in different ways. There is more information + // on this in https://github.com/aws/aws-sdk-js/issues/244. Avoiding this field simplifies logic + // and reduces the possibility of future bugs + // + // Authorization: + // + // Is skipped for obvious reasons + + const ignoredHeaders = ['authorization', 'content-length', 'content-type', 'user-agent']; + return Object.keys(headers).filter(header => !ignoredHeaders.includes(header)).sort(); +} + +// returns the key used for calculating signature +function getSigningKey(date, region, secretKey, serviceName = 's3') { + if (!(0, _helper.isObject)(date)) { + throw new TypeError('date should be of type "object"'); + } + if (!(0, _helper.isString)(region)) { + throw new TypeError('region should be of type "string"'); + } + if (!(0, _helper.isString)(secretKey)) { + throw new TypeError('secretKey should be of type "string"'); + } + const dateLine = (0, _helper.makeDateShort)(date); + const hmac1 = crypto.createHmac('sha256', 'AWS4' + secretKey).update(dateLine).digest(), + hmac2 = crypto.createHmac('sha256', hmac1).update(region).digest(), + hmac3 = crypto.createHmac('sha256', hmac2).update(serviceName).digest(); + return crypto.createHmac('sha256', hmac3).update('aws4_request').digest(); +} + +// returns the string that needs to be signed +function getStringToSign(canonicalRequest, requestDate, region, serviceName = 's3') { + if (!(0, _helper.isString)(canonicalRequest)) { + throw new TypeError('canonicalRequest should be of type "string"'); + } + if (!(0, _helper.isObject)(requestDate)) { + throw new TypeError('requestDate should be of type "object"'); + } + if (!(0, _helper.isString)(region)) { + throw new TypeError('region should be of type "string"'); + } + const hash = crypto.createHash('sha256').update(canonicalRequest).digest('hex'); + const scope = (0, _helper.getScope)(region, requestDate, serviceName); + const stringToSign = [signV4Algorithm, (0, _helper.makeDateLong)(requestDate), scope, hash]; + return stringToSign.join('\n'); +} + +// calculate the signature of the POST policy +function postPresignSignatureV4(region, date, secretKey, policyBase64) { + if (!(0, _helper.isString)(region)) { + throw new TypeError('region should be of type "string"'); + } + if (!(0, _helper.isObject)(date)) { + throw new TypeError('date should be of type "object"'); + } + if (!(0, _helper.isString)(secretKey)) { + throw new TypeError('secretKey should be of type "string"'); + } + if (!(0, _helper.isString)(policyBase64)) { + throw new TypeError('policyBase64 should be of type "string"'); + } + const signingKey = getSigningKey(date, region, secretKey); + return crypto.createHmac('sha256', signingKey).update(policyBase64).digest('hex').toLowerCase(); +} + +// Returns the authorization header +function signV4(request, accessKey, secretKey, region, requestDate, sha256sum, serviceName = 's3') { + if (!(0, _helper.isObject)(request)) { + throw new TypeError('request should be of type "object"'); + } + if (!(0, _helper.isString)(accessKey)) { + throw new TypeError('accessKey should be of type "string"'); + } + if (!(0, _helper.isString)(secretKey)) { + throw new TypeError('secretKey should be of type "string"'); + } + if (!(0, _helper.isString)(region)) { + throw new TypeError('region should be of type "string"'); + } + if (!accessKey) { + throw new errors.AccessKeyRequiredError('accessKey is required for signing'); + } + if (!secretKey) { + throw new errors.SecretKeyRequiredError('secretKey is required for signing'); + } + const signedHeaders = getSignedHeaders(request.headers); + const canonicalRequest = getCanonicalRequest(request.method, request.path, request.headers, signedHeaders, sha256sum); + const serviceIdentifier = serviceName || 's3'; + const stringToSign = getStringToSign(canonicalRequest, requestDate, region, serviceIdentifier); + const signingKey = getSigningKey(requestDate, region, secretKey, serviceIdentifier); + const credential = getCredential(accessKey, region, requestDate, serviceIdentifier); + const signature = crypto.createHmac('sha256', signingKey).update(stringToSign).digest('hex').toLowerCase(); + return `${signV4Algorithm} Credential=${credential}, SignedHeaders=${signedHeaders.join(';').toLowerCase()}, Signature=${signature}`; +} +function signV4ByServiceName(request, accessKey, secretKey, region, requestDate, contentSha256, serviceName = 's3') { + return signV4(request, accessKey, secretKey, region, requestDate, contentSha256, serviceName); +} + +// returns a presigned URL string +function presignSignatureV4(request, accessKey, secretKey, sessionToken, region, requestDate, expires) { + if (!(0, _helper.isObject)(request)) { + throw new TypeError('request should be of type "object"'); + } + if (!(0, _helper.isString)(accessKey)) { + throw new TypeError('accessKey should be of type "string"'); + } + if (!(0, _helper.isString)(secretKey)) { + throw new TypeError('secretKey should be of type "string"'); + } + if (!(0, _helper.isString)(region)) { + throw new TypeError('region should be of type "string"'); + } + if (!accessKey) { + throw new errors.AccessKeyRequiredError('accessKey is required for presigning'); + } + if (!secretKey) { + throw new errors.SecretKeyRequiredError('secretKey is required for presigning'); + } + if (expires && !(0, _helper.isNumber)(expires)) { + throw new TypeError('expires should be of type "number"'); + } + if (expires && expires < 1) { + throw new errors.ExpiresParamError('expires param cannot be less than 1 seconds'); + } + if (expires && expires > _helpers.PRESIGN_EXPIRY_DAYS_MAX) { + throw new errors.ExpiresParamError('expires param cannot be greater than 7 days'); + } + const iso8601Date = (0, _helper.makeDateLong)(requestDate); + const signedHeaders = getSignedHeaders(request.headers); + const credential = getCredential(accessKey, region, requestDate); + const hashedPayload = 'UNSIGNED-PAYLOAD'; + const requestQuery = []; + requestQuery.push(`X-Amz-Algorithm=${signV4Algorithm}`); + requestQuery.push(`X-Amz-Credential=${(0, _helper.uriEscape)(credential)}`); + requestQuery.push(`X-Amz-Date=${iso8601Date}`); + requestQuery.push(`X-Amz-Expires=${expires}`); + requestQuery.push(`X-Amz-SignedHeaders=${(0, _helper.uriEscape)(signedHeaders.join(';').toLowerCase())}`); + if (sessionToken) { + requestQuery.push(`X-Amz-Security-Token=${(0, _helper.uriEscape)(sessionToken)}`); + } + const resource = request.path.split('?')[0]; + let query = request.path.split('?')[1]; + if (query) { + query = query + '&' + requestQuery.join('&'); + } else { + query = requestQuery.join('&'); + } + const path = resource + '?' + query; + const canonicalRequest = getCanonicalRequest(request.method, path, request.headers, signedHeaders, hashedPayload); + const stringToSign = getStringToSign(canonicalRequest, requestDate, region); + const signingKey = getSigningKey(requestDate, region, secretKey); + const signature = crypto.createHmac('sha256', signingKey).update(stringToSign).digest('hex').toLowerCase(); + return request.protocol + '//' + request.headers.host + path + `&X-Amz-Signature=${signature}`; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjcnlwdG8iLCJfaW50ZXJvcFJlcXVpcmVXaWxkY2FyZCIsInJlcXVpcmUiLCJlcnJvcnMiLCJfaGVscGVycyIsIl9oZWxwZXIiLCJlIiwidCIsIldlYWtNYXAiLCJyIiwibiIsIl9fZXNNb2R1bGUiLCJvIiwiaSIsImYiLCJfX3Byb3RvX18iLCJkZWZhdWx0IiwiaGFzIiwiZ2V0Iiwic2V0IiwiaGFzT3duUHJvcGVydHkiLCJjYWxsIiwiT2JqZWN0IiwiZGVmaW5lUHJvcGVydHkiLCJnZXRPd25Qcm9wZXJ0eURlc2NyaXB0b3IiLCJzaWduVjRBbGdvcml0aG0iLCJnZXRDYW5vbmljYWxSZXF1ZXN0IiwibWV0aG9kIiwicGF0aCIsImhlYWRlcnMiLCJzaWduZWRIZWFkZXJzIiwiaGFzaGVkUGF5bG9hZCIsImlzU3RyaW5nIiwiVHlwZUVycm9yIiwiaXNPYmplY3QiLCJBcnJheSIsImlzQXJyYXkiLCJoZWFkZXJzQXJyYXkiLCJyZWR1Y2UiLCJhY2MiLCJ2YWwiLCJyZXBsYWNlIiwicHVzaCIsInRvTG93ZXJDYXNlIiwicmVxdWVzdFJlc291cmNlIiwic3BsaXQiLCJyZXF1ZXN0UXVlcnkiLCJzb3J0IiwibWFwIiwiZWxlbWVudCIsImluY2x1ZGVzIiwiam9pbiIsInRvVXBwZXJDYXNlIiwiZ2V0Q3JlZGVudGlhbCIsImFjY2Vzc0tleSIsInJlZ2lvbiIsInJlcXVlc3REYXRlIiwic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zlDLENBQUMsTUFBTTtJQUNMcUQsS0FBSyxHQUFHMUQsWUFBWSxDQUFDSyxJQUFJLENBQUMsR0FBRyxDQUFDO0VBQ2hDO0VBRUEsTUFBTXZCLElBQUksR0FBRzJFLFFBQVEsR0FBRyxHQUFHLEdBQUdDLEtBQUs7RUFFbkMsTUFBTTVCLGdCQUFnQixHQUFHbEQsbUJBQW1CLENBQUM0RCxPQUFPLENBQUMzRCxNQUFNLEVBQUVDLElBQUksRUFBRTBELE9BQU8sQ0FBQ3pELE9BQU8sRUFBRUMsYUFBYSxFQUFFQyxhQUFhLENBQUM7RUFFakgsTUFBTWlELFlBQVksR0FBR0wsZUFBZSxDQUFDQyxnQkFBZ0IsRUFBRXBCLFdBQVcsRUFBRUQsTUFBTSxDQUFDO0VBQzNFLE1BQU02QixVQUFVLEdBQUdwQixhQUFhLENBQUNSLFdBQVcsRUFBRUQsTUFBTSxFQUFFVyxTQUFTLENBQUM7RUFDaEUsTUFBTTBCLFNBQVMsR0FBRzVGLE1BQU0sQ0FBQ3NFLFVBQVUsQ0FBQyxRQUFRLEVBQUVjLFVBQVUsQ0FBQyxDQUFDYixNQUFNLENBQUNTLFlBQVksQ0FBQyxDQUFDUixNQUFNLENBQUMsS0FBSyxDQUFDLENBQUM3QixXQUFXLENBQUMsQ0FBQztFQUMxRyxPQUFPMkMsT0FBTyxDQUFDbUIsUUFBUSxHQUFHLElBQUksR0FBR25CLE9BQU8sQ0FBQ3pELE9BQU8sQ0FBQzZFLElBQUksR0FBRzlFLElBQUksR0FBSSxvQkFBbUJnRSxTQUFVLEVBQUM7QUFDaEcifQ== \ No newline at end of file diff --git a/node_modules/minio/package.json b/node_modules/minio/package.json new file mode 100644 index 0000000..89d589e --- /dev/null +++ b/node_modules/minio/package.json @@ -0,0 +1,152 @@ +{ + "name": "minio", + "version": "8.0.7", + "description": "S3 Compatible Cloud Storage client", + "main": "./dist/main/minio.js", + "module": "./dist/esm/minio.mjs", + "scripts": { + "prepare": "husky install", + "tsc": "tsc", + "type-check": "tsc --noEmit --emitDeclarationOnly false", + "build": "node build.mjs", + "test": "mocha", + "lint": "eslint --ext js,mjs,cjs,ts ./", + "lint-fix": "eslint --ext js,mjs,cjs,ts ./ --fix", + "prepublishOnly": "npm run build", + "functional": "mocha tests/functional/functional-tests.js", + "format": "prettier -w .", + "format-check": "prettier --list-different .", + "lint-staged": "lint-staged" + }, + "exports": { + ".": { + "require": "./dist/main/minio.js", + "types": "./dist/main/minio.d.ts", + "default": "./dist/esm/minio.mjs" + }, + "./dist/main/internal/*": null, + "./dist/main/*": { + "require": "./dist/main/*", + "default": null + }, + "./dist/esm/internal/*": null, + "./dist/esm/*": { + "import": "./dist/esm/*", + "default": null + }, + "./package.json": "./package.json" + }, + "files": [ + "package.json", + "./dist/", + "./src/", + "./types/", + "LICENSE", + "README.md", + "README_zh_CN.md", + "MAINTAINERS.md" + ], + "prettier": { + "printWidth": 120, + "singleQuote": true, + "endOfLine": "lf", + "trailingComma": "all", + "semi": false + }, + "lint-staged": { + "*.json": [ + "prettier --write" + ], + "*.{js,cjs,mjs,ts}": [ + "eslint --fix", + "prettier --write" + ], + "*.md": [ + "prettier --write" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/minio/minio-js.git" + }, + "author": { + "name": "MinIO, Inc.", + "url": "https://min.io" + }, + "engines": { + "node": "^16 || ^18 || >=20" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/minio/minio-js/issues", + "mail": "" + }, + "homepage": "https://github.com/minio/minio-js#readme", + "dependencies": { + "async": "^3.2.4", + "block-stream2": "^2.1.0", + "browser-or-node": "^2.1.1", + "buffer-crc32": "^1.0.0", + "eventemitter3": "^5.0.1", + "fast-xml-parser": "^5.3.4", + "ipaddr.js": "^2.0.1", + "lodash": "^4.17.21", + "mime-types": "^2.1.35", + "query-string": "^7.1.3", + "stream-json": "^1.8.0", + "through2": "^4.0.2", + "xml2js": "^0.5.0 || ^0.6.2" + }, + "devDependencies": { + "@babel/core": "^7.21.8", + "@babel/plugin-transform-modules-commonjs": "^7.21.5", + "@babel/preset-env": "^7.21.5", + "@babel/preset-typescript": "^7.21.5", + "@babel/register": "^7.21.0", + "@nodelib/fs.walk": "^1.2.8", + "@types/async": "^3.2.20", + "@types/block-stream2": "^2.1.2", + "@types/chai": "^4.3.11", + "@types/chai-as-promised": "^7.1.8", + "@types/lodash": "^4.14.194", + "@types/mime-types": "^2.1.1", + "@types/node": "^20.1.0", + "@types/stream-json": "^1.7.5", + "@types/through2": "^2.0.38", + "@types/xml2js": "^0.4.11", + "@typescript-eslint/eslint-plugin": "^5.59.2", + "@typescript-eslint/parser": "^5.59.2", + "@upleveled/babel-plugin-remove-node-prefix": "^1.0.5", + "babel-plugin-replace-import-extension": "^1.1.3", + "babel-plugin-transform-replace-expressions": "^0.2.0", + "chai": "^4.3.7", + "chai-as-promised": "^7.1.1", + "dotenv": "^16.0.3", + "eslint": "^8.40.0", + "eslint-config-prettier": "^8.8.0", + "eslint-import-resolver-typescript": "^3.5.5", + "eslint-plugin-import": "^2.27.5", + "eslint-plugin-simple-import-sort": "^10.0.0", + "eslint-plugin-unicorn": "^47.0.0", + "eslint-plugin-unused-imports": "^2.0.0", + "husky": "^8.0.3", + "lint-staged": "^13.2.2", + "mocha": "^10.2.0", + "mocha-steps": "^1.3.0", + "nock": "^13.3.1", + "prettier": "^2.8.8", + "source-map-support": "^0.5.21", + "split-file": "^2.3.0", + "superagent": "^8.0.1", + "typescript": "^5.0.4", + "uuid": "^9.0.0" + }, + "keywords": [ + "api", + "amazon", + "minio", + "cloud", + "s3", + "storage" + ] +} diff --git a/node_modules/minio/src/AssumeRoleProvider.ts b/node_modules/minio/src/AssumeRoleProvider.ts new file mode 100644 index 0000000..71a5952 --- /dev/null +++ b/node_modules/minio/src/AssumeRoleProvider.ts @@ -0,0 +1,262 @@ +import * as http from 'node:http' +import * as https from 'node:https' +import { URL, URLSearchParams } from 'node:url' + +import { CredentialProvider } from './CredentialProvider.ts' +import { Credentials } from './Credentials.ts' +import { makeDateLong, parseXml, toSha256 } from './internal/helper.ts' +import { request } from './internal/request.ts' +import { readAsString } from './internal/response.ts' +import type { Transport } from './internal/type.ts' +import { signV4ByServiceName } from './signing.ts' + +/** + * @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html + */ +type CredentialResponse = { + ErrorResponse?: { + Error?: { + Code?: string + Message?: string + } + } + + AssumeRoleResponse: { + AssumeRoleResult: { + Credentials: { + AccessKeyId: string + SecretAccessKey: string + SessionToken: string + Expiration: string + } + } + } +} + +export interface AssumeRoleProviderOptions { + stsEndpoint: string + accessKey: string + secretKey: string + durationSeconds?: number + sessionToken?: string + policy?: string + region?: string + roleArn?: string + roleSessionName?: string + externalId?: string + token?: string + webIdentityToken?: string + action?: string + transportAgent?: http.Agent +} + +const defaultExpirySeconds = 900 + +export class AssumeRoleProvider extends CredentialProvider { + private readonly stsEndpoint: URL + private readonly accessKey: string + private readonly secretKey: string + private readonly durationSeconds: number + private readonly policy?: string + private readonly region: string + private readonly roleArn?: string + private readonly roleSessionName?: string + private readonly externalId?: string + private readonly token?: string + private readonly webIdentityToken?: string + private readonly action: string + + private _credentials: Credentials | null + private readonly expirySeconds: number + private accessExpiresAt = '' + private readonly transportAgent?: http.Agent + + private readonly transport: Transport + + constructor({ + stsEndpoint, + accessKey, + secretKey, + durationSeconds = defaultExpirySeconds, + sessionToken, + policy, + region = '', + roleArn, + roleSessionName, + externalId, + token, + webIdentityToken, + action = 'AssumeRole', + transportAgent = undefined, + }: AssumeRoleProviderOptions) { + super({ accessKey, secretKey, sessionToken }) + + this.stsEndpoint = new URL(stsEndpoint) + this.accessKey = accessKey + this.secretKey = secretKey + this.policy = policy + this.region = region + this.roleArn = roleArn + this.roleSessionName = roleSessionName + this.externalId = externalId + this.token = token + this.webIdentityToken = webIdentityToken + this.action = action + + this.durationSeconds = parseInt(durationSeconds as unknown as string) + + let expirySeconds = this.durationSeconds + if (this.durationSeconds < defaultExpirySeconds) { + expirySeconds = defaultExpirySeconds + } + this.expirySeconds = expirySeconds // for calculating refresh of credentials. + + // By default, nodejs uses a global agent if the 'agent' property + // is set to undefined. Otherwise, it's okay to assume the users + // know what they're doing if they specify a custom transport agent. + this.transportAgent = transportAgent + const isHttp: boolean = this.stsEndpoint.protocol === 'http:' + this.transport = isHttp ? http : https + + /** + * Internal Tracking variables + */ + this._credentials = null + } + + getRequestConfig(): { + requestOptions: http.RequestOptions + requestData: string + } { + const hostValue = this.stsEndpoint.hostname + const portValue = this.stsEndpoint.port + const qryParams = new URLSearchParams({ Action: this.action, Version: '2011-06-15' }) + + qryParams.set('DurationSeconds', this.expirySeconds.toString()) + + if (this.policy) { + qryParams.set('Policy', this.policy) + } + if (this.roleArn) { + qryParams.set('RoleArn', this.roleArn) + } + + if (this.roleSessionName != null) { + qryParams.set('RoleSessionName', this.roleSessionName) + } + if (this.token != null) { + qryParams.set('Token', this.token) + } + + if (this.webIdentityToken) { + qryParams.set('WebIdentityToken', this.webIdentityToken) + } + + if (this.externalId) { + qryParams.set('ExternalId', this.externalId) + } + + const urlParams = qryParams.toString() + const contentSha256 = toSha256(urlParams) + + const date = new Date() + + const requestOptions = { + hostname: hostValue, + port: portValue, + path: '/', + protocol: this.stsEndpoint.protocol, + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'content-length': urlParams.length.toString(), + host: hostValue, + 'x-amz-date': makeDateLong(date), + 'x-amz-content-sha256': contentSha256, + } as Record, + agent: this.transportAgent, + } satisfies http.RequestOptions + + requestOptions.headers.authorization = signV4ByServiceName( + requestOptions, + this.accessKey, + this.secretKey, + this.region, + date, + contentSha256, + 'sts', + ) + + return { + requestOptions, + requestData: urlParams, + } + } + + async performRequest(): Promise { + const { requestOptions, requestData } = this.getRequestConfig() + + const res = await request(this.transport, requestOptions, requestData) + + const body = await readAsString(res) + + return parseXml(body) + } + + parseCredentials(respObj: CredentialResponse): Credentials { + if (respObj.ErrorResponse) { + throw new Error( + `Unable to obtain credentials: ${respObj.ErrorResponse?.Error?.Code} ${respObj.ErrorResponse?.Error?.Message}`, + { cause: respObj }, + ) + } + + const { + AssumeRoleResponse: { + AssumeRoleResult: { + Credentials: { + AccessKeyId: accessKey, + SecretAccessKey: secretKey, + SessionToken: sessionToken, + Expiration: expiresAt, + }, + }, + }, + } = respObj + + this.accessExpiresAt = expiresAt + + return new Credentials({ accessKey, secretKey, sessionToken }) + } + + async refreshCredentials(): Promise { + try { + const assumeRoleCredentials = await this.performRequest() + this._credentials = this.parseCredentials(assumeRoleCredentials) + } catch (err) { + throw new Error(`Failed to get Credentials: ${err}`, { cause: err }) + } + + return this._credentials + } + + async getCredentials(): Promise { + if (this._credentials && !this.isAboutToExpire()) { + return this._credentials + } + + this._credentials = await this.refreshCredentials() + return this._credentials + } + + isAboutToExpire() { + const expiresAt = new Date(this.accessExpiresAt) + const provisionalExpiry = new Date(Date.now() + 1000 * 10) // check before 10 seconds. + return provisionalExpiry > expiresAt + } +} + +// deprecated default export, please use named exports. +// keep for backward compatibility. +// eslint-disable-next-line import/no-default-export +export default AssumeRoleProvider diff --git a/node_modules/minio/src/CredentialProvider.ts b/node_modules/minio/src/CredentialProvider.ts new file mode 100644 index 0000000..ba224b3 --- /dev/null +++ b/node_modules/minio/src/CredentialProvider.ts @@ -0,0 +1,54 @@ +import { Credentials } from './Credentials.ts' + +export class CredentialProvider { + private credentials: Credentials + + constructor({ accessKey, secretKey, sessionToken }: { accessKey: string; secretKey: string; sessionToken?: string }) { + this.credentials = new Credentials({ + accessKey, + secretKey, + sessionToken, + }) + } + + async getCredentials(): Promise { + return this.credentials.get() + } + + setCredentials(credentials: Credentials) { + if (credentials instanceof Credentials) { + this.credentials = credentials + } else { + throw new Error('Unable to set Credentials. it should be an instance of Credentials class') + } + } + + setAccessKey(accessKey: string) { + this.credentials.setAccessKey(accessKey) + } + + getAccessKey() { + return this.credentials.getAccessKey() + } + + setSecretKey(secretKey: string) { + this.credentials.setSecretKey(secretKey) + } + + getSecretKey() { + return this.credentials.getSecretKey() + } + + setSessionToken(sessionToken: string) { + this.credentials.setSessionToken(sessionToken) + } + + getSessionToken() { + return this.credentials.getSessionToken() + } +} + +// deprecated default export, please use named exports. +// keep for backward compatibility. +// eslint-disable-next-line import/no-default-export +export default CredentialProvider diff --git a/node_modules/minio/src/Credentials.ts b/node_modules/minio/src/Credentials.ts new file mode 100644 index 0000000..b92fe27 --- /dev/null +++ b/node_modules/minio/src/Credentials.ts @@ -0,0 +1,44 @@ +export class Credentials { + public accessKey: string + public secretKey: string + public sessionToken?: string + + constructor({ accessKey, secretKey, sessionToken }: { accessKey: string; secretKey: string; sessionToken?: string }) { + this.accessKey = accessKey + this.secretKey = secretKey + this.sessionToken = sessionToken + } + + setAccessKey(accessKey: string) { + this.accessKey = accessKey + } + + getAccessKey() { + return this.accessKey + } + + setSecretKey(secretKey: string) { + this.secretKey = secretKey + } + + getSecretKey() { + return this.secretKey + } + + setSessionToken(sessionToken: string) { + this.sessionToken = sessionToken + } + + getSessionToken() { + return this.sessionToken + } + + get(): Credentials { + return this + } +} + +// deprecated default export, please use named exports. +// keep for backward compatibility. +// eslint-disable-next-line import/no-default-export +export default Credentials diff --git a/node_modules/minio/src/IamAwsProvider.ts b/node_modules/minio/src/IamAwsProvider.ts new file mode 100644 index 0000000..6324da0 --- /dev/null +++ b/node_modules/minio/src/IamAwsProvider.ts @@ -0,0 +1,234 @@ +import * as fs from 'node:fs/promises' +import * as http from 'node:http' +import * as https from 'node:https' +import { URL, URLSearchParams } from 'node:url' + +import { CredentialProvider } from './CredentialProvider.ts' +import { Credentials } from './Credentials.ts' +import { parseXml } from './internal/helper.ts' +import { request } from './internal/request.ts' +import { readAsString } from './internal/response.ts' + +interface AssumeRoleResponse { + AssumeRoleWithWebIdentityResponse: { + AssumeRoleWithWebIdentityResult: { + Credentials: { + AccessKeyId: string + SecretAccessKey: string + SessionToken: string + Expiration: string + } + } + } +} + +interface EcsCredentials { + AccessKeyID: string + SecretAccessKey: string + Token: string + Expiration: string + Code: string + Message: string +} + +export interface IamAwsProviderOptions { + customEndpoint?: string + transportAgent?: http.Agent +} + +export class IamAwsProvider extends CredentialProvider { + private readonly customEndpoint?: string + + private _credentials: Credentials | null + private readonly transportAgent?: http.Agent + private accessExpiresAt = '' + + constructor({ customEndpoint = undefined, transportAgent = undefined }: IamAwsProviderOptions) { + super({ accessKey: '', secretKey: '' }) + + this.customEndpoint = customEndpoint + this.transportAgent = transportAgent + + /** + * Internal Tracking variables + */ + this._credentials = null + } + + async getCredentials(): Promise { + if (!this._credentials || this.isAboutToExpire()) { + this._credentials = await this.fetchCredentials() + } + return this._credentials + } + + private async fetchCredentials(): Promise { + try { + // check for IRSA (https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) + const tokenFile = process.env.AWS_WEB_IDENTITY_TOKEN_FILE + if (tokenFile) { + return await this.fetchCredentialsUsingTokenFile(tokenFile) + } + + // try with IAM role for EC2 instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) + let tokenHeader = 'Authorization' + let token = process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN + const relativeUri = process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI + const fullUri = process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI + let url: URL + if (relativeUri) { + url = new URL(relativeUri, 'http://169.254.170.2') + } else if (fullUri) { + url = new URL(fullUri) + } else { + token = await this.fetchImdsToken() + tokenHeader = 'X-aws-ec2-metadata-token' + url = await this.getIamRoleNamedUrl(token) + } + + return this.requestCredentials(url, tokenHeader, token) + } catch (err) { + throw new Error(`Failed to get Credentials: ${err}`, { cause: err }) + } + } + + private async fetchCredentialsUsingTokenFile(tokenFile: string): Promise { + const token = await fs.readFile(tokenFile, { encoding: 'utf8' }) + const region = process.env.AWS_REGION + const stsEndpoint = new URL(region ? `https://sts.${region}.amazonaws.com` : 'https://sts.amazonaws.com') + + const hostValue = stsEndpoint.hostname + const portValue = stsEndpoint.port + const qryParams = new URLSearchParams({ + Action: 'AssumeRoleWithWebIdentity', + Version: '2011-06-15', + }) + + const roleArn = process.env.AWS_ROLE_ARN + if (roleArn) { + qryParams.set('RoleArn', roleArn) + const roleSessionName = process.env.AWS_ROLE_SESSION_NAME + qryParams.set('RoleSessionName', roleSessionName ? roleSessionName : Date.now().toString()) + } + + qryParams.set('WebIdentityToken', token) + qryParams.sort() + + const requestOptions = { + hostname: hostValue, + port: portValue, + path: `${stsEndpoint.pathname}?${qryParams.toString()}`, + protocol: stsEndpoint.protocol, + method: 'POST', + headers: {}, + agent: this.transportAgent, + } satisfies http.RequestOptions + + const transport = stsEndpoint.protocol === 'http:' ? http : https + const res = await request(transport, requestOptions, null) + const body = await readAsString(res) + + const assumeRoleResponse: AssumeRoleResponse = parseXml(body) + const creds = assumeRoleResponse.AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult.Credentials + this.accessExpiresAt = creds.Expiration + return new Credentials({ + accessKey: creds.AccessKeyId, + secretKey: creds.SecretAccessKey, + sessionToken: creds.SessionToken, + }) + } + + private async fetchImdsToken() { + const endpoint = this.customEndpoint ? this.customEndpoint : 'http://169.254.169.254' + const url = new URL('/latest/api/token', endpoint) + + const requestOptions = { + hostname: url.hostname, + port: url.port, + path: `${url.pathname}${url.search}`, + protocol: url.protocol, + method: 'PUT', + headers: { + 'X-aws-ec2-metadata-token-ttl-seconds': '21600', + }, + agent: this.transportAgent, + } satisfies http.RequestOptions + + const transport = url.protocol === 'http:' ? http : https + const res = await request(transport, requestOptions, null) + return await readAsString(res) + } + + private async getIamRoleNamedUrl(token: string) { + const endpoint = this.customEndpoint ? this.customEndpoint : 'http://169.254.169.254' + const url = new URL('latest/meta-data/iam/security-credentials/', endpoint) + + const roleName = await this.getIamRoleName(url, token) + return new URL(`${url.pathname}/${encodeURIComponent(roleName)}`, url.origin) + } + + private async getIamRoleName(url: URL, token: string): Promise { + const requestOptions = { + hostname: url.hostname, + port: url.port, + path: `${url.pathname}${url.search}`, + protocol: url.protocol, + method: 'GET', + headers: { + 'X-aws-ec2-metadata-token': token, + }, + agent: this.transportAgent, + } satisfies http.RequestOptions + + const transport = url.protocol === 'http:' ? http : https + const res = await request(transport, requestOptions, null) + const body = await readAsString(res) + const roleNames = body.split(/\r\n|[\n\r\u2028\u2029]/) + if (roleNames.length === 0) { + throw new Error(`No IAM roles attached to EC2 service ${url}`) + } + return roleNames[0] as string + } + + private async requestCredentials(url: URL, tokenHeader: string, token: string | undefined): Promise { + const headers: Record = {} + if (token) { + headers[tokenHeader] = token + } + const requestOptions = { + hostname: url.hostname, + port: url.port, + path: `${url.pathname}${url.search}`, + protocol: url.protocol, + method: 'GET', + headers: headers, + agent: this.transportAgent, + } satisfies http.RequestOptions + + const transport = url.protocol === 'http:' ? http : https + const res = await request(transport, requestOptions, null) + const body = await readAsString(res) + const ecsCredentials = JSON.parse(body) as EcsCredentials + if (!ecsCredentials.Code || ecsCredentials.Code != 'Success') { + throw new Error(`${url} failed with code ${ecsCredentials.Code} and message ${ecsCredentials.Message}`) + } + + this.accessExpiresAt = ecsCredentials.Expiration + return new Credentials({ + accessKey: ecsCredentials.AccessKeyID, + secretKey: ecsCredentials.SecretAccessKey, + sessionToken: ecsCredentials.Token, + }) + } + + private isAboutToExpire() { + const expiresAt = new Date(this.accessExpiresAt) + const provisionalExpiry = new Date(Date.now() + 1000 * 10) // 10 seconds leeway + return provisionalExpiry > expiresAt + } +} + +// deprecated default export, please use named exports. +// keep for backward compatibility. +// eslint-disable-next-line import/no-default-export +export default IamAwsProvider diff --git a/node_modules/minio/src/errors.ts b/node_modules/minio/src/errors.ts new file mode 100644 index 0000000..9aca3e3 --- /dev/null +++ b/node_modules/minio/src/errors.ts @@ -0,0 +1,120 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// + +class ExtendableError extends Error { + constructor(message?: string, opt?: ErrorOptions) { + // error Option {cause?: unknown} is a 'nice to have', + // don't use it internally + super(message, opt) + // set error name, otherwise it's always 'Error' + this.name = this.constructor.name + } +} + +/** + * AnonymousRequestError is generated for anonymous keys on specific + * APIs. NOTE: PresignedURL generation always requires access keys. + */ +export class AnonymousRequestError extends ExtendableError {} + +/** + * InvalidArgumentError is generated for all invalid arguments. + */ +export class InvalidArgumentError extends ExtendableError {} + +/** + * InvalidPortError is generated when a non integer value is provided + * for ports. + */ +export class InvalidPortError extends ExtendableError {} + +/** + * InvalidEndpointError is generated when an invalid end point value is + * provided which does not follow domain standards. + */ +export class InvalidEndpointError extends ExtendableError {} + +/** + * InvalidBucketNameError is generated when an invalid bucket name is + * provided which does not follow AWS S3 specifications. + * http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html + */ +export class InvalidBucketNameError extends ExtendableError {} + +/** + * InvalidObjectNameError is generated when an invalid object name is + * provided which does not follow AWS S3 specifications. + * http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html + */ +export class InvalidObjectNameError extends ExtendableError {} + +/** + * AccessKeyRequiredError generated by signature methods when access + * key is not found. + */ +export class AccessKeyRequiredError extends ExtendableError {} + +/** + * SecretKeyRequiredError generated by signature methods when secret + * key is not found. + */ +export class SecretKeyRequiredError extends ExtendableError {} + +/** + * ExpiresParamError generated when expires parameter value is not + * well within stipulated limits. + */ +export class ExpiresParamError extends ExtendableError {} + +/** + * InvalidDateError generated when invalid date is found. + */ +export class InvalidDateError extends ExtendableError {} + +/** + * InvalidPrefixError generated when object prefix provided is invalid + * or does not conform to AWS S3 object key restrictions. + */ +export class InvalidPrefixError extends ExtendableError {} + +/** + * InvalidBucketPolicyError generated when the given bucket policy is invalid. + */ +export class InvalidBucketPolicyError extends ExtendableError {} + +/** + * IncorrectSizeError generated when total data read mismatches with + * the input size. + */ +export class IncorrectSizeError extends ExtendableError {} + +/** + * InvalidXMLError generated when an unknown XML is found. + */ +export class InvalidXMLError extends ExtendableError {} + +/** + * S3Error is generated for errors returned from S3 server. + * see getErrorTransformer for details + */ +export class S3Error extends ExtendableError { + code?: string + region?: string +} + +export class IsValidBucketNameError extends ExtendableError {} diff --git a/node_modules/minio/src/helpers.ts b/node_modules/minio/src/helpers.ts new file mode 100644 index 0000000..40bec96 --- /dev/null +++ b/node_modules/minio/src/helpers.ts @@ -0,0 +1,354 @@ +import * as fs from 'node:fs' +import * as path from 'node:path' + +import * as querystring from 'query-string' + +import * as errors from './errors.ts' +import { + getEncryptionHeaders, + isEmpty, + isEmptyObject, + isNumber, + isObject, + isString, + isValidBucketName, + isValidObjectName, +} from './internal/helper.ts' +import type { Encryption, ObjectMetaData, RequestHeaders } from './internal/type.ts' +import { RETENTION_MODES } from './internal/type.ts' + +export { ENCRYPTION_TYPES, LEGAL_HOLD_STATUS, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from './internal/type.ts' + +export const DEFAULT_REGION = 'us-east-1' + +export const PRESIGN_EXPIRY_DAYS_MAX = 24 * 60 * 60 * 7 // 7 days in seconds + +export interface ICopySourceOptions { + Bucket: string + Object: string + /** + * Valid versionId + */ + VersionID?: string + /** + * Etag to match + */ + MatchETag?: string + /** + * Etag to exclude + */ + NoMatchETag?: string + /** + * Modified Date of the object/part. UTC Date in string format + */ + MatchModifiedSince?: string | null + /** + * Modified Date of the object/part to exclude UTC Date in string format + */ + MatchUnmodifiedSince?: string | null + /** + * true or false Object range to match + */ + MatchRange?: boolean + Start?: number + End?: number + Encryption?: Encryption +} + +export class CopySourceOptions { + public readonly Bucket: string + public readonly Object: string + public readonly VersionID: string + public MatchETag: string + private readonly NoMatchETag: string + private readonly MatchModifiedSince: string | null + private readonly MatchUnmodifiedSince: string | null + public readonly MatchRange: boolean + public readonly Start: number + public readonly End: number + private readonly Encryption?: Encryption + + constructor({ + Bucket, + Object, + VersionID = '', + MatchETag = '', + NoMatchETag = '', + MatchModifiedSince = null, + MatchUnmodifiedSince = null, + MatchRange = false, + Start = 0, + End = 0, + Encryption = undefined, + }: ICopySourceOptions) { + this.Bucket = Bucket + this.Object = Object + this.VersionID = VersionID + this.MatchETag = MatchETag + this.NoMatchETag = NoMatchETag + this.MatchModifiedSince = MatchModifiedSince + this.MatchUnmodifiedSince = MatchUnmodifiedSince + this.MatchRange = MatchRange + this.Start = Start + this.End = End + this.Encryption = Encryption + } + + validate() { + if (!isValidBucketName(this.Bucket)) { + throw new errors.InvalidBucketNameError('Invalid Source bucket name: ' + this.Bucket) + } + if (!isValidObjectName(this.Object)) { + throw new errors.InvalidObjectNameError(`Invalid Source object name: ${this.Object}`) + } + if ((this.MatchRange && this.Start !== -1 && this.End !== -1 && this.Start > this.End) || this.Start < 0) { + throw new errors.InvalidObjectNameError('Source start must be non-negative, and start must be at most end.') + } else if ((this.MatchRange && !isNumber(this.Start)) || !isNumber(this.End)) { + throw new errors.InvalidObjectNameError( + 'MatchRange is specified. But Invalid Start and End values are specified.', + ) + } + + return true + } + + getHeaders(): RequestHeaders { + const headerOptions: RequestHeaders = {} + headerOptions['x-amz-copy-source'] = encodeURI(this.Bucket + '/' + this.Object) + + if (!isEmpty(this.VersionID)) { + headerOptions['x-amz-copy-source'] = `${encodeURI(this.Bucket + '/' + this.Object)}?versionId=${this.VersionID}` + } + + if (!isEmpty(this.MatchETag)) { + headerOptions['x-amz-copy-source-if-match'] = this.MatchETag + } + if (!isEmpty(this.NoMatchETag)) { + headerOptions['x-amz-copy-source-if-none-match'] = this.NoMatchETag + } + + if (!isEmpty(this.MatchModifiedSince)) { + headerOptions['x-amz-copy-source-if-modified-since'] = this.MatchModifiedSince + } + if (!isEmpty(this.MatchUnmodifiedSince)) { + headerOptions['x-amz-copy-source-if-unmodified-since'] = this.MatchUnmodifiedSince + } + + return headerOptions + } +} + +/** + * @deprecated use nodejs fs module + */ +export function removeDirAndFiles(dirPath: string, removeSelf = true) { + if (removeSelf) { + return fs.rmSync(dirPath, { recursive: true, force: true }) + } + + fs.readdirSync(dirPath).forEach((item) => { + fs.rmSync(path.join(dirPath, item), { recursive: true, force: true }) + }) +} + +export interface ICopyDestinationOptions { + /** + * Bucket name + */ + Bucket: string + /** + * Object Name for the destination (composed/copied) object defaults + */ + Object: string + /** + * Encryption configuration defaults to {} + * @default {} + */ + Encryption?: Encryption + UserMetadata?: ObjectMetaData + /** + * query-string encoded string or Record Object + */ + UserTags?: Record | string + LegalHold?: 'on' | 'off' + /** + * UTC Date String + */ + RetainUntilDate?: string + Mode?: RETENTION_MODES + MetadataDirective?: 'COPY' | 'REPLACE' + /** + * Extra headers for the target object + */ + Headers?: Record +} + +export class CopyDestinationOptions { + public readonly Bucket: string + public readonly Object: string + private readonly Encryption?: Encryption + private readonly UserMetadata?: ObjectMetaData + private readonly UserTags?: Record | string + private readonly LegalHold?: 'on' | 'off' + private readonly RetainUntilDate?: string + private readonly Mode?: RETENTION_MODES + private readonly MetadataDirective?: string + private readonly Headers?: Record + + constructor({ + Bucket, + Object, + Encryption, + UserMetadata, + UserTags, + LegalHold, + RetainUntilDate, + Mode, + MetadataDirective, + Headers, + }: ICopyDestinationOptions) { + this.Bucket = Bucket + this.Object = Object + this.Encryption = Encryption ?? undefined // null input will become undefined, easy for runtime assert + this.UserMetadata = UserMetadata + this.UserTags = UserTags + this.LegalHold = LegalHold + this.Mode = Mode // retention mode + this.RetainUntilDate = RetainUntilDate + this.MetadataDirective = MetadataDirective + this.Headers = Headers + } + + getHeaders(): RequestHeaders { + const replaceDirective = 'REPLACE' + const headerOptions: RequestHeaders = {} + + const userTags = this.UserTags + if (!isEmpty(userTags)) { + headerOptions['X-Amz-Tagging-Directive'] = replaceDirective + headerOptions['X-Amz-Tagging'] = isObject(userTags) + ? querystring.stringify(userTags) + : isString(userTags) + ? userTags + : '' + } + + if (this.Mode) { + headerOptions['X-Amz-Object-Lock-Mode'] = this.Mode // GOVERNANCE or COMPLIANCE + } + + if (this.RetainUntilDate) { + headerOptions['X-Amz-Object-Lock-Retain-Until-Date'] = this.RetainUntilDate // needs to be UTC. + } + + if (this.LegalHold) { + headerOptions['X-Amz-Object-Lock-Legal-Hold'] = this.LegalHold // ON or OFF + } + + if (this.UserMetadata) { + for (const [key, value] of Object.entries(this.UserMetadata)) { + headerOptions[`X-Amz-Meta-${key}`] = value.toString() + } + } + + if (this.MetadataDirective) { + headerOptions[`X-Amz-Metadata-Directive`] = this.MetadataDirective + } + + if (this.Encryption) { + const encryptionHeaders = getEncryptionHeaders(this.Encryption) + for (const [key, value] of Object.entries(encryptionHeaders)) { + headerOptions[key] = value + } + } + if (this.Headers) { + for (const [key, value] of Object.entries(this.Headers)) { + headerOptions[key] = value + } + } + + return headerOptions + } + + validate() { + if (!isValidBucketName(this.Bucket)) { + throw new errors.InvalidBucketNameError('Invalid Destination bucket name: ' + this.Bucket) + } + if (!isValidObjectName(this.Object)) { + throw new errors.InvalidObjectNameError(`Invalid Destination object name: ${this.Object}`) + } + if (!isEmpty(this.UserMetadata) && !isObject(this.UserMetadata)) { + throw new errors.InvalidObjectNameError(`Destination UserMetadata should be an object with key value pairs`) + } + + if (!isEmpty(this.Mode) && ![RETENTION_MODES.GOVERNANCE, RETENTION_MODES.COMPLIANCE].includes(this.Mode)) { + throw new errors.InvalidObjectNameError( + `Invalid Mode specified for destination object it should be one of [GOVERNANCE,COMPLIANCE]`, + ) + } + + if (this.Encryption !== undefined && isEmptyObject(this.Encryption)) { + throw new errors.InvalidObjectNameError(`Invalid Encryption configuration for destination object `) + } + return true + } +} + +/** + * maybe this should be a generic type for Records, leave it for later refactor + */ +export class SelectResults { + private records?: unknown + private response?: unknown + private stats?: string + private progress?: unknown + + constructor({ + records, // parsed data as stream + response, // original response stream + stats, // stats as xml + progress, // stats as xml + }: { + records?: unknown + response?: unknown + stats?: string + progress?: unknown + }) { + this.records = records + this.response = response + this.stats = stats + this.progress = progress + } + + setStats(stats: string) { + this.stats = stats + } + + getStats() { + return this.stats + } + + setProgress(progress: unknown) { + this.progress = progress + } + + getProgress() { + return this.progress + } + + setResponse(response: unknown) { + this.response = response + } + + getResponse() { + return this.response + } + + setRecords(records: unknown) { + this.records = records + } + + getRecords(): unknown { + return this.records + } +} diff --git a/node_modules/minio/src/internal/async.ts b/node_modules/minio/src/internal/async.ts new file mode 100644 index 0000000..2532dd5 --- /dev/null +++ b/node_modules/minio/src/internal/async.ts @@ -0,0 +1,14 @@ +// promise helper for stdlib + +import * as fs from 'node:fs' +import * as stream from 'node:stream' +import { promisify } from 'node:util' + +// TODO: use "node:fs/promise" directly after we stop testing on nodejs 12 +export { promises as fsp } from 'node:fs' +export const streamPromise = { + // node:stream/promises Added in: v15.0.0 + pipeline: promisify(stream.pipeline), +} + +export const fstat = promisify(fs.fstat) diff --git a/node_modules/minio/src/internal/callbackify.ts b/node_modules/minio/src/internal/callbackify.ts new file mode 100644 index 0000000..013b7d4 --- /dev/null +++ b/node_modules/minio/src/internal/callbackify.ts @@ -0,0 +1,19 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ + +// Wrapper for an async function that supports callback style API. +// It will preserve 'this'. +export function callbackify(fn: (...args: any[]) => any) { + return function (this: any, ...args: any[]) { + const lastArg = args[args.length - 1] + + if (typeof lastArg === 'function') { + const callback = args.pop() + return fn.apply(this, args).then( + (result: any) => callback(null, result), + (err: any) => callback(err), + ) + } + + return fn.apply(this, args) + } +} diff --git a/node_modules/minio/src/internal/client.ts b/node_modules/minio/src/internal/client.ts new file mode 100644 index 0000000..6785c6b --- /dev/null +++ b/node_modules/minio/src/internal/client.ts @@ -0,0 +1,3412 @@ +import * as crypto from 'node:crypto' +import * as fs from 'node:fs' +import type { IncomingHttpHeaders } from 'node:http' +import * as http from 'node:http' +import * as https from 'node:https' +import * as path from 'node:path' +import * as stream from 'node:stream' + +import * as async from 'async' +import BlockStream2 from 'block-stream2' +import { isBrowser } from 'browser-or-node' +import _ from 'lodash' +import * as qs from 'query-string' +import xml2js from 'xml2js' + +import { CredentialProvider } from '../CredentialProvider.ts' +import * as errors from '../errors.ts' +import type { SelectResults } from '../helpers.ts' +import { + CopyDestinationOptions, + CopySourceOptions, + DEFAULT_REGION, + LEGAL_HOLD_STATUS, + PRESIGN_EXPIRY_DAYS_MAX, + RETENTION_MODES, + RETENTION_VALIDITY_UNITS, +} from '../helpers.ts' +import type { NotificationEvent } from '../notification.ts' +import { NotificationConfig, NotificationPoller } from '../notification.ts' +import { postPresignSignatureV4, presignSignatureV4, signV4 } from '../signing.ts' +import { fsp, streamPromise } from './async.ts' +import { CopyConditions } from './copy-conditions.ts' +import { Extensions } from './extensions.ts' +import { + calculateEvenSplits, + extractMetadata, + getContentLength, + getScope, + getSourceVersionId, + getVersionId, + hashBinary, + insertContentType, + isAmazonEndpoint, + isBoolean, + isDefined, + isEmpty, + isNumber, + isObject, + isPlainObject, + isReadableStream, + isString, + isValidBucketName, + isValidEndpoint, + isValidObjectName, + isValidPort, + isValidPrefix, + isVirtualHostStyle, + makeDateLong, + PART_CONSTRAINTS, + partsRequired, + prependXAMZMeta, + readableStream, + sanitizeETag, + toMd5, + toSha256, + uriEscape, + uriResourceEscape, +} from './helper.ts' +import { joinHostPort } from './join-host-port.ts' +import { PostPolicy } from './post-policy.ts' +import { requestWithRetry } from './request.ts' +import { drainResponse, readAsBuffer, readAsString } from './response.ts' +import type { Region } from './s3-endpoints.ts' +import { getS3Endpoint } from './s3-endpoints.ts' +import type { + Binary, + BucketItem, + BucketItemFromList, + BucketItemStat, + BucketStream, + BucketVersioningConfiguration, + CopyObjectParams, + CopyObjectResult, + CopyObjectResultV2, + EncryptionConfig, + GetObjectLegalHoldOptions, + GetObjectOpts, + GetObjectRetentionOpts, + IncompleteUploadedBucketItem, + IRequest, + ItemBucketMetadata, + LifecycleConfig, + LifeCycleConfigParam, + ListObjectQueryOpts, + ListObjectQueryRes, + ListObjectV2Res, + NotificationConfigResult, + ObjectInfo, + ObjectLockConfigParam, + ObjectLockInfo, + ObjectMetaData, + ObjectRetentionInfo, + PostPolicyResult, + PreSignRequestParams, + PutObjectLegalHoldOptions, + PutTaggingParams, + RemoveObjectsParam, + RemoveObjectsRequestEntry, + RemoveObjectsResponse, + RemoveTaggingParams, + ReplicationConfig, + ReplicationConfigOpts, + RequestHeaders, + ResponseHeader, + ResultCallback, + Retention, + SelectOptions, + StatObjectOpts, + Tag, + TaggingOpts, + Tags, + Transport, + UploadedObjectInfo, + UploadPartConfig, +} from './type.ts' +import type { ListMultipartResult, UploadedPart } from './xml-parser.ts' +import { + parseBucketNotification, + parseCompleteMultipart, + parseInitiateMultipart, + parseListObjects, + parseListObjectsV2, + parseObjectLegalHoldConfig, + parseSelectObjectContentResponse, + uploadPartParser, +} from './xml-parser.ts' +import * as xmlParsers from './xml-parser.ts' + +const xml = new xml2js.Builder({ renderOpts: { pretty: false }, headless: true }) + +// will be replaced by bundler. +const Package = { version: process.env.MINIO_JS_PACKAGE_VERSION || 'development' } + +const requestOptionProperties = [ + 'agent', + 'ca', + 'cert', + 'ciphers', + 'clientCertEngine', + 'crl', + 'dhparam', + 'ecdhCurve', + 'family', + 'honorCipherOrder', + 'key', + 'passphrase', + 'pfx', + 'rejectUnauthorized', + 'secureOptions', + 'secureProtocol', + 'servername', + 'sessionIdContext', +] as const + +export interface RetryOptions { + /** + * If this set to true, it will take precedence over all other retry options. + * @default false + */ + disableRetry?: boolean + /** + * The maximum amount of retries for a request. + * @default 1 + */ + maximumRetryCount?: number + /** + * The minimum duration (in milliseconds) for the exponential backoff algorithm. + * @default 100 + */ + baseDelayMs?: number + /** + * The maximum duration (in milliseconds) for the exponential backoff algorithm. + * @default 60000 + */ + maximumDelayMs?: number +} + +export interface ClientOptions { + endPoint: string + accessKey?: string + secretKey?: string + useSSL?: boolean + port?: number + region?: Region + transport?: Transport + sessionToken?: string + partSize?: number + pathStyle?: boolean + credentialsProvider?: CredentialProvider + s3AccelerateEndpoint?: string + transportAgent?: http.Agent + retryOptions?: RetryOptions +} + +export type RequestOption = Partial & { + method: string + bucketName?: string + objectName?: string + query?: string + pathStyle?: boolean +} + +export type NoResultCallback = (error: unknown) => void + +export interface MakeBucketOpt { + ObjectLocking?: boolean +} + +export interface RemoveOptions { + versionId?: string + governanceBypass?: boolean + forceDelete?: boolean +} + +type Part = { + part: number + etag: string +} + +export class TypedClient { + protected transport: Transport + protected host: string + protected port: number + protected protocol: string + protected accessKey: string + protected secretKey: string + protected sessionToken?: string + protected userAgent: string + protected anonymous: boolean + protected pathStyle: boolean + protected regionMap: Record + public region?: string + protected credentialsProvider?: CredentialProvider + partSize: number = 64 * 1024 * 1024 + protected overRidePartSize?: boolean + protected retryOptions: RetryOptions + + protected maximumPartSize = 5 * 1024 * 1024 * 1024 + protected maxObjectSize = 5 * 1024 * 1024 * 1024 * 1024 + public enableSHA256: boolean + protected s3AccelerateEndpoint?: string + protected reqOptions: Record + + protected transportAgent: http.Agent + private readonly clientExtensions: Extensions + + constructor(params: ClientOptions) { + // @ts-expect-error deprecated property + if (params.secure !== undefined) { + throw new Error('"secure" option deprecated, "useSSL" should be used instead') + } + // Default values if not specified. + if (params.useSSL === undefined) { + params.useSSL = true + } + if (!params.port) { + params.port = 0 + } + // Validate input params. + if (!isValidEndpoint(params.endPoint)) { + throw new errors.InvalidEndpointError(`Invalid endPoint : ${params.endPoint}`) + } + if (!isValidPort(params.port)) { + throw new errors.InvalidArgumentError(`Invalid port : ${params.port}`) + } + if (!isBoolean(params.useSSL)) { + throw new errors.InvalidArgumentError( + `Invalid useSSL flag type : ${params.useSSL}, expected to be of type "boolean"`, + ) + } + + // Validate region only if its set. + if (params.region) { + if (!isString(params.region)) { + throw new errors.InvalidArgumentError(`Invalid region : ${params.region}`) + } + } + + const host = params.endPoint.toLowerCase() + let port = params.port + let protocol: string + let transport + let transportAgent: http.Agent + // Validate if configuration is not using SSL + // for constructing relevant endpoints. + if (params.useSSL) { + // Defaults to secure. + transport = https + protocol = 'https:' + port = port || 443 + transportAgent = https.globalAgent + } else { + transport = http + protocol = 'http:' + port = port || 80 + transportAgent = http.globalAgent + } + + // if custom transport is set, use it. + if (params.transport) { + if (!isObject(params.transport)) { + throw new errors.InvalidArgumentError( + `Invalid transport type : ${params.transport}, expected to be type "object"`, + ) + } + transport = params.transport + } + + // if custom transport agent is set, use it. + if (params.transportAgent) { + if (!isObject(params.transportAgent)) { + throw new errors.InvalidArgumentError( + `Invalid transportAgent type: ${params.transportAgent}, expected to be type "object"`, + ) + } + + transportAgent = params.transportAgent + } + + // User Agent should always following the below style. + // Please open an issue to discuss any new changes here. + // + // MinIO (OS; ARCH) LIB/VER APP/VER + // + const libraryComments = `(${process.platform}; ${process.arch})` + const libraryAgent = `MinIO ${libraryComments} minio-js/${Package.version}` + // User agent block ends. + + this.transport = transport + this.transportAgent = transportAgent + this.host = host + this.port = port + this.protocol = protocol + this.userAgent = `${libraryAgent}` + + // Default path style is true + if (params.pathStyle === undefined) { + this.pathStyle = true + } else { + this.pathStyle = params.pathStyle + } + + this.accessKey = params.accessKey ?? '' + this.secretKey = params.secretKey ?? '' + this.sessionToken = params.sessionToken + this.anonymous = !this.accessKey || !this.secretKey + + if (params.credentialsProvider) { + this.anonymous = false + this.credentialsProvider = params.credentialsProvider + } + + this.regionMap = {} + if (params.region) { + this.region = params.region + } + + if (params.partSize) { + this.partSize = params.partSize + this.overRidePartSize = true + } + if (this.partSize < 5 * 1024 * 1024) { + throw new errors.InvalidArgumentError(`Part size should be greater than 5MB`) + } + if (this.partSize > 5 * 1024 * 1024 * 1024) { + throw new errors.InvalidArgumentError(`Part size should be less than 5GB`) + } + + // SHA256 is enabled only for authenticated http requests. If the request is authenticated + // and the connection is https we use x-amz-content-sha256=UNSIGNED-PAYLOAD + // header for signature calculation. + this.enableSHA256 = !this.anonymous && !params.useSSL + + this.s3AccelerateEndpoint = params.s3AccelerateEndpoint || undefined + this.reqOptions = {} + this.clientExtensions = new Extensions(this) + + if (params.retryOptions) { + if (!isObject(params.retryOptions)) { + throw new errors.InvalidArgumentError( + `Invalid retryOptions type: ${params.retryOptions}, expected to be type "object"`, + ) + } + + this.retryOptions = params.retryOptions + } else { + this.retryOptions = { + disableRetry: false, + } + } + } + /** + * Minio extensions that aren't necessary present for Amazon S3 compatible storage servers + */ + get extensions() { + return this.clientExtensions + } + + /** + * @param endPoint - valid S3 acceleration end point + */ + setS3TransferAccelerate(endPoint: string) { + this.s3AccelerateEndpoint = endPoint + } + + /** + * Sets the supported request options. + */ + public setRequestOptions(options: Pick) { + if (!isObject(options)) { + throw new TypeError('request options should be of type "object"') + } + this.reqOptions = _.pick(options, requestOptionProperties) + } + + /** + * This is s3 Specific and does not hold validity in any other Object storage. + */ + private getAccelerateEndPointIfSet(bucketName?: string, objectName?: string) { + if (!isEmpty(this.s3AccelerateEndpoint) && !isEmpty(bucketName) && !isEmpty(objectName)) { + // http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html + // Disable transfer acceleration for non-compliant bucket names. + if (bucketName.includes('.')) { + throw new Error(`Transfer Acceleration is not supported for non compliant bucket:${bucketName}`) + } + // If transfer acceleration is requested set new host. + // For more details about enabling transfer acceleration read here. + // http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html + return this.s3AccelerateEndpoint + } + return false + } + + /** + * Set application specific information. + * Generates User-Agent in the following style. + * MinIO (OS; ARCH) LIB/VER APP/VER + */ + setAppInfo(appName: string, appVersion: string) { + if (!isString(appName)) { + throw new TypeError(`Invalid appName: ${appName}`) + } + if (appName.trim() === '') { + throw new errors.InvalidArgumentError('Input appName cannot be empty.') + } + if (!isString(appVersion)) { + throw new TypeError(`Invalid appVersion: ${appVersion}`) + } + if (appVersion.trim() === '') { + throw new errors.InvalidArgumentError('Input appVersion cannot be empty.') + } + this.userAgent = `${this.userAgent} ${appName}/${appVersion}` + } + + /** + * returns options object that can be used with http.request() + * Takes care of constructing virtual-host-style or path-style hostname + */ + protected getRequestOptions( + opts: RequestOption & { + region: string + }, + ): IRequest & { + host: string + headers: Record + } { + const method = opts.method + const region = opts.region + const bucketName = opts.bucketName + let objectName = opts.objectName + const headers = opts.headers + const query = opts.query + + let reqOptions = { + method, + headers: {} as RequestHeaders, + protocol: this.protocol, + // If custom transportAgent was supplied earlier, we'll inject it here + agent: this.transportAgent, + } + + // Verify if virtual host supported. + let virtualHostStyle + if (bucketName) { + virtualHostStyle = isVirtualHostStyle(this.host, this.protocol, bucketName, this.pathStyle) + } + + let path = '/' + let host = this.host + + let port: undefined | number + if (this.port) { + port = this.port + } + + if (objectName) { + objectName = uriResourceEscape(objectName) + } + + // For Amazon S3 endpoint, get endpoint based on region. + if (isAmazonEndpoint(host)) { + const accelerateEndPoint = this.getAccelerateEndPointIfSet(bucketName, objectName) + if (accelerateEndPoint) { + host = `${accelerateEndPoint}` + } else { + host = getS3Endpoint(region) + } + } + + if (virtualHostStyle && !opts.pathStyle) { + // For all hosts which support virtual host style, `bucketName` + // is part of the hostname in the following format: + // + // var host = 'bucketName.example.com' + // + if (bucketName) { + host = `${bucketName}.${host}` + } + if (objectName) { + path = `/${objectName}` + } + } else { + // For all S3 compatible storage services we will fallback to + // path style requests, where `bucketName` is part of the URI + // path. + if (bucketName) { + path = `/${bucketName}` + } + if (objectName) { + path = `/${bucketName}/${objectName}` + } + } + + if (query) { + path += `?${query}` + } + reqOptions.headers.host = host + if ((reqOptions.protocol === 'http:' && port !== 80) || (reqOptions.protocol === 'https:' && port !== 443)) { + reqOptions.headers.host = joinHostPort(host, port) + } + + reqOptions.headers['user-agent'] = this.userAgent + if (headers) { + // have all header keys in lower case - to make signing easy + for (const [k, v] of Object.entries(headers)) { + reqOptions.headers[k.toLowerCase()] = v + } + } + + // Use any request option specified in minioClient.setRequestOptions() + reqOptions = Object.assign({}, this.reqOptions, reqOptions) + + return { + ...reqOptions, + headers: _.mapValues(_.pickBy(reqOptions.headers, isDefined), (v) => v.toString()), + host, + port, + path, + } satisfies https.RequestOptions + } + + public async setCredentialsProvider(credentialsProvider: CredentialProvider) { + if (!(credentialsProvider instanceof CredentialProvider)) { + throw new Error('Unable to get credentials. Expected instance of CredentialProvider') + } + this.credentialsProvider = credentialsProvider + await this.checkAndRefreshCreds() + } + + private async checkAndRefreshCreds() { + if (this.credentialsProvider) { + try { + const credentialsConf = await this.credentialsProvider.getCredentials() + this.accessKey = credentialsConf.getAccessKey() + this.secretKey = credentialsConf.getSecretKey() + this.sessionToken = credentialsConf.getSessionToken() + } catch (e) { + throw new Error(`Unable to get credentials: ${e}`, { cause: e }) + } + } + } + + private logStream?: stream.Writable + + /** + * log the request, response, error + */ + private logHTTP(reqOptions: IRequest, response: http.IncomingMessage | null, err?: unknown) { + // if no logStream available return. + if (!this.logStream) { + return + } + if (!isObject(reqOptions)) { + throw new TypeError('reqOptions should be of type "object"') + } + if (response && !isReadableStream(response)) { + throw new TypeError('response should be of type "Stream"') + } + if (err && !(err instanceof Error)) { + throw new TypeError('err should be of type "Error"') + } + const logStream = this.logStream + const logHeaders = (headers: RequestHeaders) => { + Object.entries(headers).forEach(([k, v]) => { + if (k == 'authorization') { + if (isString(v)) { + const redactor = new RegExp('Signature=([0-9a-f]+)') + v = v.replace(redactor, 'Signature=**REDACTED**') + } + } + logStream.write(`${k}: ${v}\n`) + }) + logStream.write('\n') + } + logStream.write(`REQUEST: ${reqOptions.method} ${reqOptions.path}\n`) + logHeaders(reqOptions.headers) + if (response) { + this.logStream.write(`RESPONSE: ${response.statusCode}\n`) + logHeaders(response.headers as RequestHeaders) + } + if (err) { + logStream.write('ERROR BODY:\n') + const errJSON = JSON.stringify(err, null, '\t') + logStream.write(`${errJSON}\n`) + } + } + + /** + * Enable tracing + */ + public traceOn(stream?: stream.Writable) { + if (!stream) { + stream = process.stdout + } + this.logStream = stream + } + + /** + * Disable tracing + */ + public traceOff() { + this.logStream = undefined + } + + /** + * makeRequest is the primitive used by the apis for making S3 requests. + * payload can be empty string in case of no payload. + * statusCode is the expected statusCode. If response.statusCode does not match + * we parse the XML error and call the callback with the error message. + * + * A valid region is passed by the calls - listBuckets, makeBucket and getBucketRegion. + * + * @internal + */ + async makeRequestAsync( + options: RequestOption, + payload: Binary = '', + expectedCodes: number[] = [200], + region = '', + ): Promise { + if (!isObject(options)) { + throw new TypeError('options should be of type "object"') + } + if (!isString(payload) && !isObject(payload)) { + // Buffer is of type 'object' + throw new TypeError('payload should be of type "string" or "Buffer"') + } + expectedCodes.forEach((statusCode) => { + if (!isNumber(statusCode)) { + throw new TypeError('statusCode should be of type "number"') + } + }) + if (!isString(region)) { + throw new TypeError('region should be of type "string"') + } + if (!options.headers) { + options.headers = {} + } + if (options.method === 'POST' || options.method === 'PUT' || options.method === 'DELETE') { + options.headers['content-length'] = payload.length.toString() + } + const sha256sum = this.enableSHA256 ? toSha256(payload) : '' + return this.makeRequestStreamAsync(options, payload, sha256sum, expectedCodes, region) + } + + /** + * new request with promise + * + * No need to drain response, response body is not valid + */ + async makeRequestAsyncOmit( + options: RequestOption, + payload: Binary = '', + statusCodes: number[] = [200], + region = '', + ): Promise> { + const res = await this.makeRequestAsync(options, payload, statusCodes, region) + await drainResponse(res) + return res + } + + /** + * makeRequestStream will be used directly instead of makeRequest in case the payload + * is available as a stream. for ex. putObject + * + * @internal + */ + async makeRequestStreamAsync( + options: RequestOption, + body: stream.Readable | Binary, + sha256sum: string, + statusCodes: number[], + region: string, + ): Promise { + if (!isObject(options)) { + throw new TypeError('options should be of type "object"') + } + if (!(Buffer.isBuffer(body) || typeof body === 'string' || isReadableStream(body))) { + throw new errors.InvalidArgumentError( + `stream should be a Buffer, string or readable Stream, got ${typeof body} instead`, + ) + } + if (!isString(sha256sum)) { + throw new TypeError('sha256sum should be of type "string"') + } + statusCodes.forEach((statusCode) => { + if (!isNumber(statusCode)) { + throw new TypeError('statusCode should be of type "number"') + } + }) + if (!isString(region)) { + throw new TypeError('region should be of type "string"') + } + // sha256sum will be empty for anonymous or https requests + if (!this.enableSHA256 && sha256sum.length !== 0) { + throw new errors.InvalidArgumentError(`sha256sum expected to be empty for anonymous or https requests`) + } + // sha256sum should be valid for non-anonymous http requests. + if (this.enableSHA256 && sha256sum.length !== 64) { + throw new errors.InvalidArgumentError(`Invalid sha256sum : ${sha256sum}`) + } + + await this.checkAndRefreshCreds() + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + region = region || (await this.getBucketRegionAsync(options.bucketName!)) + + const reqOptions = this.getRequestOptions({ ...options, region }) + if (!this.anonymous) { + // For non-anonymous https requests sha256sum is 'UNSIGNED-PAYLOAD' for signature calculation. + if (!this.enableSHA256) { + sha256sum = 'UNSIGNED-PAYLOAD' + } + const date = new Date() + reqOptions.headers['x-amz-date'] = makeDateLong(date) + reqOptions.headers['x-amz-content-sha256'] = sha256sum + if (this.sessionToken) { + reqOptions.headers['x-amz-security-token'] = this.sessionToken + } + reqOptions.headers.authorization = signV4(reqOptions, this.accessKey, this.secretKey, region, date, sha256sum) + } + + const response = await requestWithRetry( + this.transport, + reqOptions, + body, + this.retryOptions.disableRetry === true ? 0 : this.retryOptions.maximumRetryCount, + this.retryOptions.baseDelayMs, + this.retryOptions.maximumDelayMs, + ) + if (!response.statusCode) { + throw new Error("BUG: response doesn't have a statusCode") + } + + if (!statusCodes.includes(response.statusCode)) { + // For an incorrect region, S3 server always sends back 400. + // But we will do cache invalidation for all errors so that, + // in future, if AWS S3 decides to send a different status code or + // XML error code we will still work fine. + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + delete this.regionMap[options.bucketName!] + + const err = await xmlParsers.parseResponseError(response) + this.logHTTP(reqOptions, response, err) + throw err + } + + this.logHTTP(reqOptions, response) + + return response + } + + /** + * gets the region of the bucket + * + * @param bucketName + * + */ + async getBucketRegionAsync(bucketName: string): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name : ${bucketName}`) + } + + // Region is set with constructor, return the region right here. + if (this.region) { + return this.region + } + + const cached = this.regionMap[bucketName] + if (cached) { + return cached + } + + const extractRegionAsync = async (response: http.IncomingMessage) => { + const body = await readAsString(response) + const region = xmlParsers.parseBucketRegion(body) || DEFAULT_REGION + this.regionMap[bucketName] = region + return region + } + + const method = 'GET' + const query = 'location' + // `getBucketLocation` behaves differently in following ways for + // different environments. + // + // - For nodejs env we default to path style requests. + // - For browser env path style requests on buckets yields CORS + // error. To circumvent this problem we make a virtual host + // style request signed with 'us-east-1'. This request fails + // with an error 'AuthorizationHeaderMalformed', additionally + // the error XML also provides Region of the bucket. To validate + // this region is proper we retry the same request with the newly + // obtained region. + const pathStyle = this.pathStyle && !isBrowser + let region: string + try { + const res = await this.makeRequestAsync({ method, bucketName, query, pathStyle }, '', [200], DEFAULT_REGION) + return extractRegionAsync(res) + } catch (e) { + // make alignment with mc cli + if (e instanceof errors.S3Error) { + const errCode = e.code + const errRegion = e.region + if (errCode === 'AccessDenied' && !errRegion) { + return DEFAULT_REGION + } + } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + if (!(e.name === 'AuthorizationHeaderMalformed')) { + throw e + } + // @ts-expect-error we set extra properties on error object + region = e.Region as string + if (!region) { + throw e + } + } + + const res = await this.makeRequestAsync({ method, bucketName, query, pathStyle }, '', [200], region) + return await extractRegionAsync(res) + } + + /** + * makeRequest is the primitive used by the apis for making S3 requests. + * payload can be empty string in case of no payload. + * statusCode is the expected statusCode. If response.statusCode does not match + * we parse the XML error and call the callback with the error message. + * A valid region is passed by the calls - listBuckets, makeBucket and + * getBucketRegion. + * + * @deprecated use `makeRequestAsync` instead + */ + makeRequest( + options: RequestOption, + payload: Binary = '', + expectedCodes: number[] = [200], + region = '', + returnResponse: boolean, + cb: (cb: unknown, result: http.IncomingMessage) => void, + ) { + let prom: Promise + if (returnResponse) { + prom = this.makeRequestAsync(options, payload, expectedCodes, region) + } else { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error compatible for old behaviour + prom = this.makeRequestAsyncOmit(options, payload, expectedCodes, region) + } + + prom.then( + (result) => cb(null, result), + (err) => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + cb(err) + }, + ) + } + + /** + * makeRequestStream will be used directly instead of makeRequest in case the payload + * is available as a stream. for ex. putObject + * + * @deprecated use `makeRequestStreamAsync` instead + */ + makeRequestStream( + options: RequestOption, + stream: stream.Readable | Buffer, + sha256sum: string, + statusCodes: number[], + region: string, + returnResponse: boolean, + cb: (cb: unknown, result: http.IncomingMessage) => void, + ) { + const executor = async () => { + const res = await this.makeRequestStreamAsync(options, stream, sha256sum, statusCodes, region) + if (!returnResponse) { + await drainResponse(res) + } + + return res + } + + executor().then( + (result) => cb(null, result), + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + (err) => cb(err), + ) + } + + /** + * @deprecated use `getBucketRegionAsync` instead + */ + getBucketRegion(bucketName: string, cb: (err: unknown, region: string) => void) { + return this.getBucketRegionAsync(bucketName).then( + (result) => cb(null, result), + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + (err) => cb(err), + ) + } + + // Bucket operations + + /** + * Creates the bucket `bucketName`. + * + */ + async makeBucket(bucketName: string, region: Region = '', makeOpts?: MakeBucketOpt): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + // Backward Compatibility + if (isObject(region)) { + makeOpts = region + region = '' + } + + if (!isString(region)) { + throw new TypeError('region should be of type "string"') + } + if (makeOpts && !isObject(makeOpts)) { + throw new TypeError('makeOpts should be of type "object"') + } + + let payload = '' + + // Region already set in constructor, validate if + // caller requested bucket location is same. + if (region && this.region) { + if (region !== this.region) { + throw new errors.InvalidArgumentError(`Configured region ${this.region}, requested ${region}`) + } + } + // sending makeBucket request with XML containing 'us-east-1' fails. For + // default region server expects the request without body + if (region && region !== DEFAULT_REGION) { + payload = xml.buildObject({ + CreateBucketConfiguration: { + $: { xmlns: 'http://s3.amazonaws.com/doc/2006-03-01/' }, + LocationConstraint: region, + }, + }) + } + const method = 'PUT' + const headers: RequestHeaders = {} + + if (makeOpts && makeOpts.ObjectLocking) { + headers['x-amz-bucket-object-lock-enabled'] = true + } + + // For custom region clients default to custom region specified in client constructor + const finalRegion = this.region || region || DEFAULT_REGION + + const requestOpt: RequestOption = { method, bucketName, headers } + + try { + await this.makeRequestAsyncOmit(requestOpt, payload, [200], finalRegion) + } catch (err: unknown) { + if (region === '' || region === DEFAULT_REGION) { + if (err instanceof errors.S3Error) { + const errCode = err.code + const errRegion = err.region + if (errCode === 'AuthorizationHeaderMalformed' && errRegion !== '') { + // Retry with region returned as part of error + await this.makeRequestAsyncOmit(requestOpt, payload, [200], errCode) + } + } + } + throw err + } + } + + /** + * To check if a bucket already exists. + */ + async bucketExists(bucketName: string): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + const method = 'HEAD' + try { + await this.makeRequestAsyncOmit({ method, bucketName }) + } catch (err) { + // @ts-ignore + if (err.code === 'NoSuchBucket' || err.code === 'NotFound') { + return false + } + throw err + } + + return true + } + + async removeBucket(bucketName: string): Promise + + /** + * @deprecated use promise style API + */ + removeBucket(bucketName: string, callback: NoResultCallback): void + + async removeBucket(bucketName: string): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + const method = 'DELETE' + await this.makeRequestAsyncOmit({ method, bucketName }, '', [204]) + delete this.regionMap[bucketName] + } + + /** + * Callback is called with readable stream of the object content. + */ + async getObject(bucketName: string, objectName: string, getOpts?: GetObjectOpts): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + return this.getPartialObject(bucketName, objectName, 0, 0, getOpts) + } + + /** + * Callback is called with readable stream of the partial object content. + * @param bucketName + * @param objectName + * @param offset + * @param length - length of the object that will be read in the stream (optional, if not specified we read the rest of the file from the offset) + * @param getOpts + */ + async getPartialObject( + bucketName: string, + objectName: string, + offset: number, + length = 0, + getOpts?: GetObjectOpts, + ): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + if (!isNumber(offset)) { + throw new TypeError('offset should be of type "number"') + } + if (!isNumber(length)) { + throw new TypeError('length should be of type "number"') + } + + let range = '' + if (offset || length) { + if (offset) { + range = `bytes=${+offset}-` + } else { + range = 'bytes=0-' + offset = 0 + } + if (length) { + range += `${+length + offset - 1}` + } + } + + let query = '' + let headers: RequestHeaders = { + ...(range !== '' && { range }), + } + + if (getOpts) { + const sseHeaders: Record = { + ...(getOpts.SSECustomerAlgorithm && { + 'X-Amz-Server-Side-Encryption-Customer-Algorithm': getOpts.SSECustomerAlgorithm, + }), + ...(getOpts.SSECustomerKey && { 'X-Amz-Server-Side-Encryption-Customer-Key': getOpts.SSECustomerKey }), + ...(getOpts.SSECustomerKeyMD5 && { + 'X-Amz-Server-Side-Encryption-Customer-Key-MD5': getOpts.SSECustomerKeyMD5, + }), + } + query = qs.stringify(getOpts) + headers = { + ...prependXAMZMeta(sseHeaders), + ...headers, + } + } + + const expectedStatusCodes = [200] + if (range) { + expectedStatusCodes.push(206) + } + const method = 'GET' + + return await this.makeRequestAsync({ method, bucketName, objectName, headers, query }, '', expectedStatusCodes) + } + + /** + * download object content to a file. + * This method will create a temp file named `${filename}.${base64(etag)}.part.minio` when downloading. + * + * @param bucketName - name of the bucket + * @param objectName - name of the object + * @param filePath - path to which the object data will be written to + * @param getOpts - Optional object get option + */ + async fGetObject(bucketName: string, objectName: string, filePath: string, getOpts?: GetObjectOpts): Promise { + // Input validation. + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + if (!isString(filePath)) { + throw new TypeError('filePath should be of type "string"') + } + + const downloadToTmpFile = async (): Promise => { + let partFileStream: stream.Writable + const objStat = await this.statObject(bucketName, objectName, getOpts) + const encodedEtag = Buffer.from(objStat.etag).toString('base64') + const partFile = `${filePath}.${encodedEtag}.part.minio` + + await fsp.mkdir(path.dirname(filePath), { recursive: true }) + + let offset = 0 + try { + const stats = await fsp.stat(partFile) + if (objStat.size === stats.size) { + return partFile + } + offset = stats.size + partFileStream = fs.createWriteStream(partFile, { flags: 'a' }) + } catch (e) { + if (e instanceof Error && (e as unknown as { code: string }).code === 'ENOENT') { + // file not exist + partFileStream = fs.createWriteStream(partFile, { flags: 'w' }) + } else { + // other error, maybe access deny + throw e + } + } + + const downloadStream = await this.getPartialObject(bucketName, objectName, offset, 0, getOpts) + + await streamPromise.pipeline(downloadStream, partFileStream) + const stats = await fsp.stat(partFile) + if (stats.size === objStat.size) { + return partFile + } + + throw new Error('Size mismatch between downloaded file and the object') + } + + const partFile = await downloadToTmpFile() + await fsp.rename(partFile, filePath) + } + + /** + * Stat information of the object. + */ + async statObject(bucketName: string, objectName: string, statOpts?: StatObjectOpts): Promise { + const statOptDef = statOpts || {} + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + + if (!isObject(statOptDef)) { + throw new errors.InvalidArgumentError('statOpts should be of type "object"') + } + + const query = qs.stringify(statOptDef) + const method = 'HEAD' + const res = await this.makeRequestAsyncOmit({ method, bucketName, objectName, query }) + + return { + size: parseInt(res.headers['content-length'] as string), + metaData: extractMetadata(res.headers as ResponseHeader), + lastModified: new Date(res.headers['last-modified'] as string), + versionId: getVersionId(res.headers as ResponseHeader), + etag: sanitizeETag(res.headers.etag), + } + } + + async removeObject(bucketName: string, objectName: string, removeOpts?: RemoveOptions): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + + if (removeOpts && !isObject(removeOpts)) { + throw new errors.InvalidArgumentError('removeOpts should be of type "object"') + } + + const method = 'DELETE' + + const headers: RequestHeaders = {} + if (removeOpts?.governanceBypass) { + headers['X-Amz-Bypass-Governance-Retention'] = true + } + if (removeOpts?.forceDelete) { + headers['x-minio-force-delete'] = true + } + + const queryParams: Record = {} + if (removeOpts?.versionId) { + queryParams.versionId = `${removeOpts.versionId}` + } + const query = qs.stringify(queryParams) + + await this.makeRequestAsyncOmit({ method, bucketName, objectName, headers, query }, '', [200, 204]) + } + + // Calls implemented below are related to multipart. + + listIncompleteUploads( + bucket: string, + prefix: string, + recursive: boolean, + ): BucketStream { + if (prefix === undefined) { + prefix = '' + } + if (recursive === undefined) { + recursive = false + } + if (!isValidBucketName(bucket)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucket) + } + if (!isValidPrefix(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`) + } + if (!isBoolean(recursive)) { + throw new TypeError('recursive should be of type "boolean"') + } + const delimiter = recursive ? '' : '/' + let keyMarker = '' + let uploadIdMarker = '' + const uploads: unknown[] = [] + let ended = false + + // TODO: refactor this with async/await and `stream.Readable.from` + const readStream = new stream.Readable({ objectMode: true }) + readStream._read = () => { + // push one upload info per _read() + if (uploads.length) { + return readStream.push(uploads.shift()) + } + if (ended) { + return readStream.push(null) + } + this.listIncompleteUploadsQuery(bucket, prefix, keyMarker, uploadIdMarker, delimiter).then( + (result) => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + result.prefixes.forEach((prefix) => uploads.push(prefix)) + async.eachSeries( + result.uploads, + (upload, cb) => { + // for each incomplete upload add the sizes of its uploaded parts + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + this.listParts(bucket, upload.key, upload.uploadId).then( + (parts: Part[]) => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + upload.size = parts.reduce((acc, item) => acc + item.size, 0) + uploads.push(upload) + cb() + }, + (err: Error) => cb(err), + ) + }, + (err) => { + if (err) { + readStream.emit('error', err) + return + } + if (result.isTruncated) { + keyMarker = result.nextKeyMarker + uploadIdMarker = result.nextUploadIdMarker + } else { + ended = true + } + + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + readStream._read() + }, + ) + }, + (e) => { + readStream.emit('error', e) + }, + ) + } + return readStream + } + + /** + * Called by listIncompleteUploads to fetch a batch of incomplete uploads. + */ + async listIncompleteUploadsQuery( + bucketName: string, + prefix: string, + keyMarker: string, + uploadIdMarker: string, + delimiter: string, + ): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isString(prefix)) { + throw new TypeError('prefix should be of type "string"') + } + if (!isString(keyMarker)) { + throw new TypeError('keyMarker should be of type "string"') + } + if (!isString(uploadIdMarker)) { + throw new TypeError('uploadIdMarker should be of type "string"') + } + if (!isString(delimiter)) { + throw new TypeError('delimiter should be of type "string"') + } + const queries = [] + queries.push(`prefix=${uriEscape(prefix)}`) + queries.push(`delimiter=${uriEscape(delimiter)}`) + + if (keyMarker) { + queries.push(`key-marker=${uriEscape(keyMarker)}`) + } + if (uploadIdMarker) { + queries.push(`upload-id-marker=${uploadIdMarker}`) + } + + const maxUploads = 1000 + queries.push(`max-uploads=${maxUploads}`) + queries.sort() + queries.unshift('uploads') + let query = '' + if (queries.length > 0) { + query = `${queries.join('&')}` + } + const method = 'GET' + const res = await this.makeRequestAsync({ method, bucketName, query }) + const body = await readAsString(res) + return xmlParsers.parseListMultipart(body) + } + + /** + * Initiate a new multipart upload. + * @internal + */ + async initiateNewMultipartUpload(bucketName: string, objectName: string, headers: RequestHeaders): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + if (!isObject(headers)) { + throw new errors.InvalidObjectNameError('contentType should be of type "object"') + } + const method = 'POST' + const query = 'uploads' + const res = await this.makeRequestAsync({ method, bucketName, objectName, query, headers }) + const body = await readAsBuffer(res) + return parseInitiateMultipart(body.toString()) + } + + /** + * Internal Method to abort a multipart upload request in case of any errors. + * + * @param bucketName - Bucket Name + * @param objectName - Object Name + * @param uploadId - id of a multipart upload to cancel during compose object sequence. + */ + async abortMultipartUpload(bucketName: string, objectName: string, uploadId: string): Promise { + const method = 'DELETE' + const query = `uploadId=${uploadId}` + + const requestOptions = { method, bucketName, objectName: objectName, query } + await this.makeRequestAsyncOmit(requestOptions, '', [204]) + } + + async findUploadId(bucketName: string, objectName: string): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + + let latestUpload: ListMultipartResult['uploads'][number] | undefined + let keyMarker = '' + let uploadIdMarker = '' + for (;;) { + const result = await this.listIncompleteUploadsQuery(bucketName, objectName, keyMarker, uploadIdMarker, '') + for (const upload of result.uploads) { + if (upload.key === objectName) { + if (!latestUpload || upload.initiated.getTime() > latestUpload.initiated.getTime()) { + latestUpload = upload + } + } + } + if (result.isTruncated) { + keyMarker = result.nextKeyMarker + uploadIdMarker = result.nextUploadIdMarker + continue + } + + break + } + return latestUpload?.uploadId + } + + /** + * this call will aggregate the parts on the server into a single object. + */ + async completeMultipartUpload( + bucketName: string, + objectName: string, + uploadId: string, + etags: { + part: number + etag?: string + }[], + ): Promise<{ etag: string; versionId: string | null }> { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + if (!isString(uploadId)) { + throw new TypeError('uploadId should be of type "string"') + } + if (!isObject(etags)) { + throw new TypeError('etags should be of type "Array"') + } + + if (!uploadId) { + throw new errors.InvalidArgumentError('uploadId cannot be empty') + } + + const method = 'POST' + const query = `uploadId=${uriEscape(uploadId)}` + + const builder = new xml2js.Builder() + const payload = builder.buildObject({ + CompleteMultipartUpload: { + $: { + xmlns: 'http://s3.amazonaws.com/doc/2006-03-01/', + }, + Part: etags.map((etag) => { + return { + PartNumber: etag.part, + ETag: etag.etag, + } + }), + }, + }) + + const res = await this.makeRequestAsync({ method, bucketName, objectName, query }, payload) + const body = await readAsBuffer(res) + const result = parseCompleteMultipart(body.toString()) + if (!result) { + throw new Error('BUG: failed to parse server response') + } + + if (result.errCode) { + // Multipart Complete API returns an error XML after a 200 http status + throw new errors.S3Error(result.errMessage) + } + + return { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + etag: result.etag as string, + versionId: getVersionId(res.headers as ResponseHeader), + } + } + + /** + * Get part-info of all parts of an incomplete upload specified by uploadId. + */ + protected async listParts(bucketName: string, objectName: string, uploadId: string): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + if (!isString(uploadId)) { + throw new TypeError('uploadId should be of type "string"') + } + if (!uploadId) { + throw new errors.InvalidArgumentError('uploadId cannot be empty') + } + + const parts: UploadedPart[] = [] + let marker = 0 + let result + do { + result = await this.listPartsQuery(bucketName, objectName, uploadId, marker) + marker = result.marker + parts.push(...result.parts) + } while (result.isTruncated) + + return parts + } + + /** + * Called by listParts to fetch a batch of part-info + */ + private async listPartsQuery(bucketName: string, objectName: string, uploadId: string, marker: number) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + if (!isString(uploadId)) { + throw new TypeError('uploadId should be of type "string"') + } + if (!isNumber(marker)) { + throw new TypeError('marker should be of type "number"') + } + if (!uploadId) { + throw new errors.InvalidArgumentError('uploadId cannot be empty') + } + + let query = `uploadId=${uriEscape(uploadId)}` + if (marker) { + query += `&part-number-marker=${marker}` + } + + const method = 'GET' + const res = await this.makeRequestAsync({ method, bucketName, objectName, query }) + return xmlParsers.parseListParts(await readAsString(res)) + } + + async listBuckets(): Promise { + const method = 'GET' + const regionConf = this.region || DEFAULT_REGION + const httpRes = await this.makeRequestAsync({ method }, '', [200], regionConf) + const xmlResult = await readAsString(httpRes) + return xmlParsers.parseListBucket(xmlResult) + } + + /** + * Calculate part size given the object size. Part size will be atleast this.partSize + */ + calculatePartSize(size: number) { + if (!isNumber(size)) { + throw new TypeError('size should be of type "number"') + } + if (size > this.maxObjectSize) { + throw new TypeError(`size should not be more than ${this.maxObjectSize}`) + } + if (this.overRidePartSize) { + return this.partSize + } + let partSize = this.partSize + for (;;) { + // while(true) {...} throws linting error. + // If partSize is big enough to accomodate the object size, then use it. + if (partSize * 10000 > size) { + return partSize + } + // Try part sizes as 64MB, 80MB, 96MB etc. + partSize += 16 * 1024 * 1024 + } + } + + /** + * Uploads the object using contents from a file + */ + async fPutObject(bucketName: string, objectName: string, filePath: string, metaData?: ObjectMetaData) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + + if (!isString(filePath)) { + throw new TypeError('filePath should be of type "string"') + } + if (metaData && !isObject(metaData)) { + throw new TypeError('metaData should be of type "object"') + } + + // Inserts correct `content-type` attribute based on metaData and filePath + metaData = insertContentType(metaData || {}, filePath) + const stat = await fsp.stat(filePath) + return await this.putObject(bucketName, objectName, fs.createReadStream(filePath), stat.size, metaData) + } + + /** + * Uploading a stream, "Buffer" or "string". + * It's recommended to pass `size` argument with stream. + */ + async putObject( + bucketName: string, + objectName: string, + stream: stream.Readable | Buffer | string, + size?: number, + metaData?: ItemBucketMetadata, + ): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + + // We'll need to shift arguments to the left because of metaData + // and size being optional. + if (isObject(size)) { + metaData = size + } + // Ensures Metadata has appropriate prefix for A3 API + const headers = prependXAMZMeta(metaData) + if (typeof stream === 'string' || stream instanceof Buffer) { + // Adapts the non-stream interface into a stream. + size = stream.length + stream = readableStream(stream) + } else if (!isReadableStream(stream)) { + throw new TypeError('third argument should be of type "stream.Readable" or "Buffer" or "string"') + } + + if (isNumber(size) && size < 0) { + throw new errors.InvalidArgumentError(`size cannot be negative, given size: ${size}`) + } + + // Get the part size and forward that to the BlockStream. Default to the + // largest block size possible if necessary. + if (!isNumber(size)) { + size = this.maxObjectSize + } + + // Get the part size and forward that to the BlockStream. Default to the + // largest block size possible if necessary. + if (size === undefined) { + const statSize = await getContentLength(stream) + if (statSize !== null) { + size = statSize + } + } + + if (!isNumber(size)) { + // Backward compatibility + size = this.maxObjectSize + } + if (size === 0) { + return this.uploadBuffer(bucketName, objectName, headers, Buffer.from('')) + } + + const partSize = this.calculatePartSize(size) + if (typeof stream === 'string' || Buffer.isBuffer(stream) || size <= partSize) { + const buf = isReadableStream(stream) ? await readAsBuffer(stream) : Buffer.from(stream) + return this.uploadBuffer(bucketName, objectName, headers, buf) + } + + return this.uploadStream(bucketName, objectName, headers, stream, partSize) + } + + /** + * method to upload buffer in one call + * @private + */ + private async uploadBuffer( + bucketName: string, + objectName: string, + headers: RequestHeaders, + buf: Buffer, + ): Promise { + const { md5sum, sha256sum } = hashBinary(buf, this.enableSHA256) + headers['Content-Length'] = buf.length + if (!this.enableSHA256) { + headers['Content-MD5'] = md5sum + } + const res = await this.makeRequestStreamAsync( + { + method: 'PUT', + bucketName, + objectName, + headers, + }, + buf, + sha256sum, + [200], + '', + ) + await drainResponse(res) + return { + etag: sanitizeETag(res.headers.etag), + versionId: getVersionId(res.headers as ResponseHeader), + } + } + + /** + * upload stream with MultipartUpload + * @private + */ + private async uploadStream( + bucketName: string, + objectName: string, + headers: RequestHeaders, + body: stream.Readable, + partSize: number, + ): Promise { + // A map of the previously uploaded chunks, for resuming a file upload. This + // will be null if we aren't resuming an upload. + const oldParts: Record = {} + + // Keep track of the etags for aggregating the chunks together later. Each + // etag represents a single chunk of the file. + const eTags: Part[] = [] + + const previousUploadId = await this.findUploadId(bucketName, objectName) + let uploadId: string + if (!previousUploadId) { + uploadId = await this.initiateNewMultipartUpload(bucketName, objectName, headers) + } else { + uploadId = previousUploadId + const oldTags = await this.listParts(bucketName, objectName, previousUploadId) + oldTags.forEach((e) => { + oldParts[e.part] = e + }) + } + + const chunkier = new BlockStream2({ size: partSize, zeroPadding: false }) + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const [_, o] = await Promise.all([ + new Promise((resolve, reject) => { + body.pipe(chunkier).on('error', reject) + chunkier.on('end', resolve).on('error', reject) + }), + (async () => { + let partNumber = 1 + + for await (const chunk of chunkier) { + const md5 = crypto.createHash('md5').update(chunk).digest() + + const oldPart = oldParts[partNumber] + if (oldPart) { + if (oldPart.etag === md5.toString('hex')) { + eTags.push({ part: partNumber, etag: oldPart.etag }) + partNumber++ + continue + } + } + + partNumber++ + + // now start to upload missing part + const options: RequestOption = { + method: 'PUT', + query: qs.stringify({ partNumber, uploadId }), + headers: { + 'Content-Length': chunk.length, + 'Content-MD5': md5.toString('base64'), + }, + bucketName, + objectName, + } + + const response = await this.makeRequestAsyncOmit(options, chunk) + + let etag = response.headers.etag + if (etag) { + etag = etag.replace(/^"/, '').replace(/"$/, '') + } else { + etag = '' + } + + eTags.push({ part: partNumber, etag }) + } + + return await this.completeMultipartUpload(bucketName, objectName, uploadId, eTags) + })(), + ]) + + return o + } + + async removeBucketReplication(bucketName: string): Promise + removeBucketReplication(bucketName: string, callback: NoResultCallback): void + async removeBucketReplication(bucketName: string): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + const method = 'DELETE' + const query = 'replication' + await this.makeRequestAsyncOmit({ method, bucketName, query }, '', [200, 204], '') + } + + setBucketReplication(bucketName: string, replicationConfig: ReplicationConfigOpts): void + async setBucketReplication(bucketName: string, replicationConfig: ReplicationConfigOpts): Promise + async setBucketReplication(bucketName: string, replicationConfig: ReplicationConfigOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isObject(replicationConfig)) { + throw new errors.InvalidArgumentError('replicationConfig should be of type "object"') + } else { + if (_.isEmpty(replicationConfig.role)) { + throw new errors.InvalidArgumentError('Role cannot be empty') + } else if (replicationConfig.role && !isString(replicationConfig.role)) { + throw new errors.InvalidArgumentError('Invalid value for role', replicationConfig.role) + } + if (_.isEmpty(replicationConfig.rules)) { + throw new errors.InvalidArgumentError('Minimum one replication rule must be specified') + } + } + const method = 'PUT' + const query = 'replication' + const headers: Record = {} + + const replicationParamsConfig = { + ReplicationConfiguration: { + Role: replicationConfig.role, + Rule: replicationConfig.rules, + }, + } + + const builder = new xml2js.Builder({ renderOpts: { pretty: false }, headless: true }) + const payload = builder.buildObject(replicationParamsConfig) + headers['Content-MD5'] = toMd5(payload) + await this.makeRequestAsyncOmit({ method, bucketName, query, headers }, payload) + } + + getBucketReplication(bucketName: string): void + async getBucketReplication(bucketName: string): Promise + async getBucketReplication(bucketName: string) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + const method = 'GET' + const query = 'replication' + + const httpRes = await this.makeRequestAsync({ method, bucketName, query }, '', [200, 204]) + const xmlResult = await readAsString(httpRes) + return xmlParsers.parseReplicationConfig(xmlResult) + } + + getObjectLegalHold( + bucketName: string, + objectName: string, + getOpts?: GetObjectLegalHoldOptions, + callback?: ResultCallback, + ): Promise + async getObjectLegalHold( + bucketName: string, + objectName: string, + getOpts?: GetObjectLegalHoldOptions, + ): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + + if (getOpts) { + if (!isObject(getOpts)) { + throw new TypeError('getOpts should be of type "Object"') + } else if (Object.keys(getOpts).length > 0 && getOpts.versionId && !isString(getOpts.versionId)) { + throw new TypeError('versionId should be of type string.:', getOpts.versionId) + } + } + + const method = 'GET' + let query = 'legal-hold' + + if (getOpts?.versionId) { + query += `&versionId=${getOpts.versionId}` + } + + const httpRes = await this.makeRequestAsync({ method, bucketName, objectName, query }, '', [200]) + const strRes = await readAsString(httpRes) + return parseObjectLegalHoldConfig(strRes) + } + + setObjectLegalHold(bucketName: string, objectName: string, setOpts?: PutObjectLegalHoldOptions): void + async setObjectLegalHold( + bucketName: string, + objectName: string, + setOpts = { + status: LEGAL_HOLD_STATUS.ENABLED, + } as PutObjectLegalHoldOptions, + ): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + + if (!isObject(setOpts)) { + throw new TypeError('setOpts should be of type "Object"') + } else { + if (![LEGAL_HOLD_STATUS.ENABLED, LEGAL_HOLD_STATUS.DISABLED].includes(setOpts?.status)) { + throw new TypeError('Invalid status: ' + setOpts.status) + } + if (setOpts.versionId && !setOpts.versionId.length) { + throw new TypeError('versionId should be of type string.:' + setOpts.versionId) + } + } + + const method = 'PUT' + let query = 'legal-hold' + + if (setOpts.versionId) { + query += `&versionId=${setOpts.versionId}` + } + + const config = { + Status: setOpts.status, + } + + const builder = new xml2js.Builder({ rootName: 'LegalHold', renderOpts: { pretty: false }, headless: true }) + const payload = builder.buildObject(config) + const headers: Record = {} + headers['Content-MD5'] = toMd5(payload) + + await this.makeRequestAsyncOmit({ method, bucketName, objectName, query, headers }, payload) + } + + /** + * Get Tags associated with a Bucket + */ + async getBucketTagging(bucketName: string): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`) + } + + const method = 'GET' + const query = 'tagging' + const requestOptions = { method, bucketName, query } + + const response = await this.makeRequestAsync(requestOptions) + const body = await readAsString(response) + return xmlParsers.parseTagging(body) + } + + /** + * Get the tags associated with a bucket OR an object + */ + async getObjectTagging(bucketName: string, objectName: string, getOpts?: GetObjectOpts): Promise { + const method = 'GET' + let query = 'tagging' + + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidBucketNameError('Invalid object name: ' + objectName) + } + if (getOpts && !isObject(getOpts)) { + throw new errors.InvalidArgumentError('getOpts should be of type "object"') + } + + if (getOpts && getOpts.versionId) { + query = `${query}&versionId=${getOpts.versionId}` + } + const requestOptions: RequestOption = { method, bucketName, query } + if (objectName) { + requestOptions['objectName'] = objectName + } + + const response = await this.makeRequestAsync(requestOptions) + const body = await readAsString(response) + return xmlParsers.parseTagging(body) + } + + /** + * Set the policy on a bucket or an object prefix. + */ + async setBucketPolicy(bucketName: string, policy: string): Promise { + // Validate arguments. + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`) + } + if (!isString(policy)) { + throw new errors.InvalidBucketPolicyError(`Invalid bucket policy: ${policy} - must be "string"`) + } + + const query = 'policy' + + let method = 'DELETE' + if (policy) { + method = 'PUT' + } + + await this.makeRequestAsyncOmit({ method, bucketName, query }, policy, [204], '') + } + + /** + * Get the policy on a bucket or an object prefix. + */ + async getBucketPolicy(bucketName: string): Promise { + // Validate arguments. + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`) + } + + const method = 'GET' + const query = 'policy' + const res = await this.makeRequestAsync({ method, bucketName, query }) + return await readAsString(res) + } + + async putObjectRetention(bucketName: string, objectName: string, retentionOpts: Retention = {}): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + if (!isObject(retentionOpts)) { + throw new errors.InvalidArgumentError('retentionOpts should be of type "object"') + } else { + if (retentionOpts.governanceBypass && !isBoolean(retentionOpts.governanceBypass)) { + throw new errors.InvalidArgumentError(`Invalid value for governanceBypass: ${retentionOpts.governanceBypass}`) + } + if ( + retentionOpts.mode && + ![RETENTION_MODES.COMPLIANCE, RETENTION_MODES.GOVERNANCE].includes(retentionOpts.mode) + ) { + throw new errors.InvalidArgumentError(`Invalid object retention mode: ${retentionOpts.mode}`) + } + if (retentionOpts.retainUntilDate && !isString(retentionOpts.retainUntilDate)) { + throw new errors.InvalidArgumentError(`Invalid value for retainUntilDate: ${retentionOpts.retainUntilDate}`) + } + if (retentionOpts.versionId && !isString(retentionOpts.versionId)) { + throw new errors.InvalidArgumentError(`Invalid value for versionId: ${retentionOpts.versionId}`) + } + } + + const method = 'PUT' + let query = 'retention' + + const headers: RequestHeaders = {} + if (retentionOpts.governanceBypass) { + headers['X-Amz-Bypass-Governance-Retention'] = true + } + + const builder = new xml2js.Builder({ rootName: 'Retention', renderOpts: { pretty: false }, headless: true }) + const params: Record = {} + + if (retentionOpts.mode) { + params.Mode = retentionOpts.mode + } + if (retentionOpts.retainUntilDate) { + params.RetainUntilDate = retentionOpts.retainUntilDate + } + if (retentionOpts.versionId) { + query += `&versionId=${retentionOpts.versionId}` + } + + const payload = builder.buildObject(params) + + headers['Content-MD5'] = toMd5(payload) + await this.makeRequestAsyncOmit({ method, bucketName, objectName, query, headers }, payload, [200, 204]) + } + + getObjectLockConfig(bucketName: string, callback: ResultCallback): void + getObjectLockConfig(bucketName: string): void + async getObjectLockConfig(bucketName: string): Promise + async getObjectLockConfig(bucketName: string) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + const method = 'GET' + const query = 'object-lock' + + const httpRes = await this.makeRequestAsync({ method, bucketName, query }) + const xmlResult = await readAsString(httpRes) + return xmlParsers.parseObjectLockConfig(xmlResult) + } + + setObjectLockConfig(bucketName: string, lockConfigOpts: Omit): void + async setObjectLockConfig( + bucketName: string, + lockConfigOpts: Omit, + ): Promise + async setObjectLockConfig(bucketName: string, lockConfigOpts: Omit) { + const retentionModes = [RETENTION_MODES.COMPLIANCE, RETENTION_MODES.GOVERNANCE] + const validUnits = [RETENTION_VALIDITY_UNITS.DAYS, RETENTION_VALIDITY_UNITS.YEARS] + + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + + if (lockConfigOpts.mode && !retentionModes.includes(lockConfigOpts.mode)) { + throw new TypeError(`lockConfigOpts.mode should be one of ${retentionModes}`) + } + if (lockConfigOpts.unit && !validUnits.includes(lockConfigOpts.unit)) { + throw new TypeError(`lockConfigOpts.unit should be one of ${validUnits}`) + } + if (lockConfigOpts.validity && !isNumber(lockConfigOpts.validity)) { + throw new TypeError(`lockConfigOpts.validity should be a number`) + } + + const method = 'PUT' + const query = 'object-lock' + + const config: ObjectLockConfigParam = { + ObjectLockEnabled: 'Enabled', + } + const configKeys = Object.keys(lockConfigOpts) + + const isAllKeysSet = ['unit', 'mode', 'validity'].every((lck) => configKeys.includes(lck)) + // Check if keys are present and all keys are present. + if (configKeys.length > 0) { + if (!isAllKeysSet) { + throw new TypeError( + `lockConfigOpts.mode,lockConfigOpts.unit,lockConfigOpts.validity all the properties should be specified.`, + ) + } else { + config.Rule = { + DefaultRetention: {}, + } + if (lockConfigOpts.mode) { + config.Rule.DefaultRetention.Mode = lockConfigOpts.mode + } + if (lockConfigOpts.unit === RETENTION_VALIDITY_UNITS.DAYS) { + config.Rule.DefaultRetention.Days = lockConfigOpts.validity + } else if (lockConfigOpts.unit === RETENTION_VALIDITY_UNITS.YEARS) { + config.Rule.DefaultRetention.Years = lockConfigOpts.validity + } + } + } + + const builder = new xml2js.Builder({ + rootName: 'ObjectLockConfiguration', + renderOpts: { pretty: false }, + headless: true, + }) + const payload = builder.buildObject(config) + + const headers: RequestHeaders = {} + headers['Content-MD5'] = toMd5(payload) + + await this.makeRequestAsyncOmit({ method, bucketName, query, headers }, payload) + } + + async getBucketVersioning(bucketName: string): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + const method = 'GET' + const query = 'versioning' + + const httpRes = await this.makeRequestAsync({ method, bucketName, query }) + const xmlResult = await readAsString(httpRes) + return await xmlParsers.parseBucketVersioningConfig(xmlResult) + } + + async setBucketVersioning(bucketName: string, versionConfig: BucketVersioningConfiguration): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!Object.keys(versionConfig).length) { + throw new errors.InvalidArgumentError('versionConfig should be of type "object"') + } + + const method = 'PUT' + const query = 'versioning' + const builder = new xml2js.Builder({ + rootName: 'VersioningConfiguration', + renderOpts: { pretty: false }, + headless: true, + }) + const payload = builder.buildObject(versionConfig) + + await this.makeRequestAsyncOmit({ method, bucketName, query }, payload) + } + + private async setTagging(taggingParams: PutTaggingParams): Promise { + const { bucketName, objectName, tags, putOpts } = taggingParams + const method = 'PUT' + let query = 'tagging' + + if (putOpts && putOpts?.versionId) { + query = `${query}&versionId=${putOpts.versionId}` + } + const tagsList = [] + for (const [key, value] of Object.entries(tags)) { + tagsList.push({ Key: key, Value: value }) + } + const taggingConfig = { + Tagging: { + TagSet: { + Tag: tagsList, + }, + }, + } + const headers = {} as RequestHeaders + const builder = new xml2js.Builder({ headless: true, renderOpts: { pretty: false } }) + const payloadBuf = Buffer.from(builder.buildObject(taggingConfig)) + const requestOptions = { + method, + bucketName, + query, + headers, + + ...(objectName && { objectName: objectName }), + } + + headers['Content-MD5'] = toMd5(payloadBuf) + + await this.makeRequestAsyncOmit(requestOptions, payloadBuf) + } + + private async removeTagging({ bucketName, objectName, removeOpts }: RemoveTaggingParams): Promise { + const method = 'DELETE' + let query = 'tagging' + + if (removeOpts && Object.keys(removeOpts).length && removeOpts.versionId) { + query = `${query}&versionId=${removeOpts.versionId}` + } + const requestOptions = { method, bucketName, objectName, query } + + if (objectName) { + requestOptions['objectName'] = objectName + } + await this.makeRequestAsync(requestOptions, '', [200, 204]) + } + + async setBucketTagging(bucketName: string, tags: Tags): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isPlainObject(tags)) { + throw new errors.InvalidArgumentError('tags should be of type "object"') + } + if (Object.keys(tags).length > 10) { + throw new errors.InvalidArgumentError('maximum tags allowed is 10"') + } + + await this.setTagging({ bucketName, tags }) + } + + async removeBucketTagging(bucketName: string) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + await this.removeTagging({ bucketName }) + } + + async setObjectTagging(bucketName: string, objectName: string, tags: Tags, putOpts?: TaggingOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidBucketNameError('Invalid object name: ' + objectName) + } + + if (!isPlainObject(tags)) { + throw new errors.InvalidArgumentError('tags should be of type "object"') + } + if (Object.keys(tags).length > 10) { + throw new errors.InvalidArgumentError('Maximum tags allowed is 10"') + } + + await this.setTagging({ bucketName, objectName, tags, putOpts }) + } + + async removeObjectTagging(bucketName: string, objectName: string, removeOpts: TaggingOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidBucketNameError('Invalid object name: ' + objectName) + } + if (removeOpts && Object.keys(removeOpts).length && !isObject(removeOpts)) { + throw new errors.InvalidArgumentError('removeOpts should be of type "object"') + } + + await this.removeTagging({ bucketName, objectName, removeOpts }) + } + + async selectObjectContent( + bucketName: string, + objectName: string, + selectOpts: SelectOptions, + ): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + if (!_.isEmpty(selectOpts)) { + if (!isString(selectOpts.expression)) { + throw new TypeError('sqlExpression should be of type "string"') + } + if (!_.isEmpty(selectOpts.inputSerialization)) { + if (!isObject(selectOpts.inputSerialization)) { + throw new TypeError('inputSerialization should be of type "object"') + } + } else { + throw new TypeError('inputSerialization is required') + } + if (!_.isEmpty(selectOpts.outputSerialization)) { + if (!isObject(selectOpts.outputSerialization)) { + throw new TypeError('outputSerialization should be of type "object"') + } + } else { + throw new TypeError('outputSerialization is required') + } + } else { + throw new TypeError('valid select configuration is required') + } + + const method = 'POST' + const query = `select&select-type=2` + + const config: Record[] = [ + { + Expression: selectOpts.expression, + }, + { + ExpressionType: selectOpts.expressionType || 'SQL', + }, + { + InputSerialization: [selectOpts.inputSerialization], + }, + { + OutputSerialization: [selectOpts.outputSerialization], + }, + ] + + // Optional + if (selectOpts.requestProgress) { + config.push({ RequestProgress: selectOpts?.requestProgress }) + } + // Optional + if (selectOpts.scanRange) { + config.push({ ScanRange: selectOpts.scanRange }) + } + + const builder = new xml2js.Builder({ + rootName: 'SelectObjectContentRequest', + renderOpts: { pretty: false }, + headless: true, + }) + const payload = builder.buildObject(config) + + const res = await this.makeRequestAsync({ method, bucketName, objectName, query }, payload) + const body = await readAsBuffer(res) + return parseSelectObjectContentResponse(body) + } + + private async applyBucketLifecycle(bucketName: string, policyConfig: LifeCycleConfigParam): Promise { + const method = 'PUT' + const query = 'lifecycle' + + const headers: RequestHeaders = {} + const builder = new xml2js.Builder({ + rootName: 'LifecycleConfiguration', + headless: true, + renderOpts: { pretty: false }, + }) + const payload = builder.buildObject(policyConfig) + headers['Content-MD5'] = toMd5(payload) + + await this.makeRequestAsyncOmit({ method, bucketName, query, headers }, payload) + } + + async removeBucketLifecycle(bucketName: string): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + const method = 'DELETE' + const query = 'lifecycle' + await this.makeRequestAsyncOmit({ method, bucketName, query }, '', [204]) + } + + async setBucketLifecycle(bucketName: string, lifeCycleConfig: LifeCycleConfigParam): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (_.isEmpty(lifeCycleConfig)) { + await this.removeBucketLifecycle(bucketName) + } else { + await this.applyBucketLifecycle(bucketName, lifeCycleConfig) + } + } + + async getBucketLifecycle(bucketName: string): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + const method = 'GET' + const query = 'lifecycle' + + const res = await this.makeRequestAsync({ method, bucketName, query }) + const body = await readAsString(res) + return xmlParsers.parseLifecycleConfig(body) + } + + async setBucketEncryption(bucketName: string, encryptionConfig?: EncryptionConfig): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!_.isEmpty(encryptionConfig) && encryptionConfig.Rule.length > 1) { + throw new errors.InvalidArgumentError('Invalid Rule length. Only one rule is allowed.: ' + encryptionConfig.Rule) + } + + let encryptionObj = encryptionConfig + if (_.isEmpty(encryptionConfig)) { + encryptionObj = { + // Default MinIO Server Supported Rule + Rule: [ + { + ApplyServerSideEncryptionByDefault: { + SSEAlgorithm: 'AES256', + }, + }, + ], + } + } + + const method = 'PUT' + const query = 'encryption' + const builder = new xml2js.Builder({ + rootName: 'ServerSideEncryptionConfiguration', + renderOpts: { pretty: false }, + headless: true, + }) + const payload = builder.buildObject(encryptionObj) + + const headers: RequestHeaders = {} + headers['Content-MD5'] = toMd5(payload) + + await this.makeRequestAsyncOmit({ method, bucketName, query, headers }, payload) + } + + async getBucketEncryption(bucketName: string) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + const method = 'GET' + const query = 'encryption' + + const res = await this.makeRequestAsync({ method, bucketName, query }) + const body = await readAsString(res) + return xmlParsers.parseBucketEncryptionConfig(body) + } + + async removeBucketEncryption(bucketName: string) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + const method = 'DELETE' + const query = 'encryption' + + await this.makeRequestAsyncOmit({ method, bucketName, query }, '', [204]) + } + + async getObjectRetention( + bucketName: string, + objectName: string, + getOpts?: GetObjectRetentionOpts, + ): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + if (getOpts && !isObject(getOpts)) { + throw new errors.InvalidArgumentError('getOpts should be of type "object"') + } else if (getOpts?.versionId && !isString(getOpts.versionId)) { + throw new errors.InvalidArgumentError('versionId should be of type "string"') + } + + const method = 'GET' + let query = 'retention' + if (getOpts?.versionId) { + query += `&versionId=${getOpts.versionId}` + } + const res = await this.makeRequestAsync({ method, bucketName, objectName, query }) + const body = await readAsString(res) + return xmlParsers.parseObjectRetentionConfig(body) + } + + async removeObjects(bucketName: string, objectsList: RemoveObjectsParam): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!Array.isArray(objectsList)) { + throw new errors.InvalidArgumentError('objectsList should be a list') + } + + const runDeleteObjects = async (batch: RemoveObjectsParam): Promise => { + const delObjects: RemoveObjectsRequestEntry[] = batch.map((value) => { + return isObject(value) ? { Key: value.name, VersionId: value.versionId } : { Key: value } + }) + + const remObjects = { Delete: { Quiet: true, Object: delObjects } } + const payload = Buffer.from(new xml2js.Builder({ headless: true }).buildObject(remObjects)) + const headers: RequestHeaders = { 'Content-MD5': toMd5(payload) } + + const res = await this.makeRequestAsync({ method: 'POST', bucketName, query: 'delete', headers }, payload) + const body = await readAsString(res) + return xmlParsers.removeObjectsParser(body) + } + + const maxEntries = 1000 // max entries accepted in server for DeleteMultipleObjects API. + // Client side batching + const batches = [] + for (let i = 0; i < objectsList.length; i += maxEntries) { + batches.push(objectsList.slice(i, i + maxEntries)) + } + + const batchResults = await Promise.all(batches.map(runDeleteObjects)) + return batchResults.flat() + } + + async removeIncompleteUpload(bucketName: string, objectName: string): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.IsValidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + const removeUploadId = await this.findUploadId(bucketName, objectName) + const method = 'DELETE' + const query = `uploadId=${removeUploadId}` + await this.makeRequestAsyncOmit({ method, bucketName, objectName, query }, '', [204]) + } + + private async copyObjectV1( + targetBucketName: string, + targetObjectName: string, + sourceBucketNameAndObjectName: string, + conditions?: null | CopyConditions, + ) { + if (typeof conditions == 'function') { + conditions = null + } + + if (!isValidBucketName(targetBucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + targetBucketName) + } + if (!isValidObjectName(targetObjectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${targetObjectName}`) + } + if (!isString(sourceBucketNameAndObjectName)) { + throw new TypeError('sourceBucketNameAndObjectName should be of type "string"') + } + if (sourceBucketNameAndObjectName === '') { + throw new errors.InvalidPrefixError(`Empty source prefix`) + } + + if (conditions != null && !(conditions instanceof CopyConditions)) { + throw new TypeError('conditions should be of type "CopyConditions"') + } + + const headers: RequestHeaders = {} + headers['x-amz-copy-source'] = uriResourceEscape(sourceBucketNameAndObjectName) + + if (conditions) { + if (conditions.modified !== '') { + headers['x-amz-copy-source-if-modified-since'] = conditions.modified + } + if (conditions.unmodified !== '') { + headers['x-amz-copy-source-if-unmodified-since'] = conditions.unmodified + } + if (conditions.matchETag !== '') { + headers['x-amz-copy-source-if-match'] = conditions.matchETag + } + if (conditions.matchETagExcept !== '') { + headers['x-amz-copy-source-if-none-match'] = conditions.matchETagExcept + } + } + + const method = 'PUT' + + const res = await this.makeRequestAsync({ + method, + bucketName: targetBucketName, + objectName: targetObjectName, + headers, + }) + const body = await readAsString(res) + return xmlParsers.parseCopyObject(body) + } + + private async copyObjectV2( + sourceConfig: CopySourceOptions, + destConfig: CopyDestinationOptions, + ): Promise { + if (!(sourceConfig instanceof CopySourceOptions)) { + throw new errors.InvalidArgumentError('sourceConfig should of type CopySourceOptions ') + } + if (!(destConfig instanceof CopyDestinationOptions)) { + throw new errors.InvalidArgumentError('destConfig should of type CopyDestinationOptions ') + } + if (!destConfig.validate()) { + return Promise.reject() + } + if (!destConfig.validate()) { + return Promise.reject() + } + + const headers = Object.assign({}, sourceConfig.getHeaders(), destConfig.getHeaders()) + + const bucketName = destConfig.Bucket + const objectName = destConfig.Object + + const method = 'PUT' + + const res = await this.makeRequestAsync({ method, bucketName, objectName, headers }) + const body = await readAsString(res) + const copyRes = xmlParsers.parseCopyObject(body) + const resHeaders: IncomingHttpHeaders = res.headers + + const sizeHeaderValue = resHeaders && resHeaders['content-length'] + const size = typeof sizeHeaderValue === 'number' ? sizeHeaderValue : undefined + + return { + Bucket: destConfig.Bucket, + Key: destConfig.Object, + LastModified: copyRes.lastModified, + MetaData: extractMetadata(resHeaders as ResponseHeader), + VersionId: getVersionId(resHeaders as ResponseHeader), + SourceVersionId: getSourceVersionId(resHeaders as ResponseHeader), + Etag: sanitizeETag(resHeaders.etag), + Size: size, + } + } + + async copyObject(source: CopySourceOptions, dest: CopyDestinationOptions): Promise + async copyObject( + targetBucketName: string, + targetObjectName: string, + sourceBucketNameAndObjectName: string, + conditions?: CopyConditions, + ): Promise + async copyObject(...allArgs: CopyObjectParams): Promise { + if (typeof allArgs[0] === 'string') { + const [targetBucketName, targetObjectName, sourceBucketNameAndObjectName, conditions] = allArgs as [ + string, + string, + string, + CopyConditions?, + ] + return await this.copyObjectV1(targetBucketName, targetObjectName, sourceBucketNameAndObjectName, conditions) + } + const [source, dest] = allArgs as [CopySourceOptions, CopyDestinationOptions] + return await this.copyObjectV2(source, dest) + } + + async uploadPart( + partConfig: { + bucketName: string + objectName: string + uploadID: string + partNumber: number + headers: RequestHeaders + }, + payload?: Binary, + ) { + const { bucketName, objectName, uploadID, partNumber, headers } = partConfig + + const method = 'PUT' + const query = `uploadId=${uploadID}&partNumber=${partNumber}` + const requestOptions = { method, bucketName, objectName: objectName, query, headers } + const res = await this.makeRequestAsync(requestOptions, payload) + const body = await readAsString(res) + const partRes = uploadPartParser(body) + const partEtagVal = sanitizeETag(res.headers.etag) || sanitizeETag(partRes.ETag) + return { + etag: partEtagVal, + key: objectName, + part: partNumber, + } + } + + async composeObject( + destObjConfig: CopyDestinationOptions, + sourceObjList: CopySourceOptions[], + { maxConcurrency = 10 } = {}, + ): Promise | CopyObjectResult> { + const sourceFilesLength = sourceObjList.length + + if (!Array.isArray(sourceObjList)) { + throw new errors.InvalidArgumentError('sourceConfig should an array of CopySourceOptions ') + } + if (!(destObjConfig instanceof CopyDestinationOptions)) { + throw new errors.InvalidArgumentError('destConfig should of type CopyDestinationOptions ') + } + + if (sourceFilesLength < 1 || sourceFilesLength > PART_CONSTRAINTS.MAX_PARTS_COUNT) { + throw new errors.InvalidArgumentError( + `"There must be as least one and up to ${PART_CONSTRAINTS.MAX_PARTS_COUNT} source objects.`, + ) + } + + for (let i = 0; i < sourceFilesLength; i++) { + const sObj = sourceObjList[i] as CopySourceOptions + if (!sObj.validate()) { + return false + } + } + + if (!(destObjConfig as CopyDestinationOptions).validate()) { + return false + } + + const getStatOptions = (srcConfig: CopySourceOptions) => { + let statOpts = {} + if (!_.isEmpty(srcConfig.VersionID)) { + statOpts = { + versionId: srcConfig.VersionID, + } + } + return statOpts + } + const srcObjectSizes: number[] = [] + let totalSize = 0 + let totalParts = 0 + + const sourceObjStats = sourceObjList.map((srcItem) => + this.statObject(srcItem.Bucket, srcItem.Object, getStatOptions(srcItem)), + ) + + const srcObjectInfos = await Promise.all(sourceObjStats) + + const validatedStats = srcObjectInfos.map((resItemStat, index) => { + const srcConfig: CopySourceOptions | undefined = sourceObjList[index] + + let srcCopySize = resItemStat.size + // Check if a segment is specified, and if so, is the + // segment within object bounds? + if (srcConfig && srcConfig.MatchRange) { + // Since range is specified, + // 0 <= src.srcStart <= src.srcEnd + // so only invalid case to check is: + const srcStart = srcConfig.Start + const srcEnd = srcConfig.End + if (srcEnd >= srcCopySize || srcStart < 0) { + throw new errors.InvalidArgumentError( + `CopySrcOptions ${index} has invalid segment-to-copy [${srcStart}, ${srcEnd}] (size is ${srcCopySize})`, + ) + } + srcCopySize = srcEnd - srcStart + 1 + } + + // Only the last source may be less than `absMinPartSize` + if (srcCopySize < PART_CONSTRAINTS.ABS_MIN_PART_SIZE && index < sourceFilesLength - 1) { + throw new errors.InvalidArgumentError( + `CopySrcOptions ${index} is too small (${srcCopySize}) and it is not the last part.`, + ) + } + + // Is data to copy too large? + totalSize += srcCopySize + if (totalSize > PART_CONSTRAINTS.MAX_MULTIPART_PUT_OBJECT_SIZE) { + throw new errors.InvalidArgumentError(`Cannot compose an object of size ${totalSize} (> 5TiB)`) + } + + // record source size + srcObjectSizes[index] = srcCopySize + + // calculate parts needed for current source + totalParts += partsRequired(srcCopySize) + // Do we need more parts than we are allowed? + if (totalParts > PART_CONSTRAINTS.MAX_PARTS_COUNT) { + throw new errors.InvalidArgumentError( + `Your proposed compose object requires more than ${PART_CONSTRAINTS.MAX_PARTS_COUNT} parts`, + ) + } + + return resItemStat + }) + + if ((totalParts === 1 && totalSize <= PART_CONSTRAINTS.MAX_PART_SIZE) || totalSize === 0) { + return await this.copyObject(sourceObjList[0] as CopySourceOptions, destObjConfig) // use copyObjectV2 + } + + // preserve etag to avoid modification of object while copying. + for (let i = 0; i < sourceFilesLength; i++) { + ;(sourceObjList[i] as CopySourceOptions).MatchETag = (validatedStats[i] as BucketItemStat).etag + } + + const splitPartSizeList = validatedStats.map((resItemStat, idx) => { + return calculateEvenSplits(srcObjectSizes[idx] as number, sourceObjList[idx] as CopySourceOptions) + }) + + const getUploadPartConfigList = (uploadId: string) => { + const uploadPartConfigList: UploadPartConfig[] = [] + + splitPartSizeList.forEach((splitSize, splitIndex: number) => { + if (splitSize) { + const { startIndex: startIdx, endIndex: endIdx, objInfo: objConfig } = splitSize + + const partIndex = splitIndex + 1 // part index starts from 1. + const totalUploads = Array.from(startIdx) + + const headers = (sourceObjList[splitIndex] as CopySourceOptions).getHeaders() + + totalUploads.forEach((splitStart, upldCtrIdx) => { + const splitEnd = endIdx[upldCtrIdx] + + const sourceObj = `${objConfig.Bucket}/${objConfig.Object}` + headers['x-amz-copy-source'] = `${sourceObj}` + headers['x-amz-copy-source-range'] = `bytes=${splitStart}-${splitEnd}` + + const uploadPartConfig = { + bucketName: destObjConfig.Bucket, + objectName: destObjConfig.Object, + uploadID: uploadId, + partNumber: partIndex, + headers: headers, + sourceObj: sourceObj, + } + + uploadPartConfigList.push(uploadPartConfig) + }) + } + }) + + return uploadPartConfigList + } + + const uploadAllParts = async (uploadList: UploadPartConfig[]) => { + const partUploads: Awaited>[] = [] + + // Process upload parts in batches to avoid too many concurrent requests + for (const batch of _.chunk(uploadList, maxConcurrency)) { + const batchResults = await Promise.all(batch.map((item) => this.uploadPart(item))) + + partUploads.push(...batchResults) + } + + // Process results here if needed + return partUploads + } + + const performUploadParts = async (uploadId: string) => { + const uploadList = getUploadPartConfigList(uploadId) + const partsRes = await uploadAllParts(uploadList) + return partsRes.map((partCopy) => ({ etag: partCopy.etag, part: partCopy.part })) + } + + const newUploadHeaders = destObjConfig.getHeaders() + + const uploadId = await this.initiateNewMultipartUpload(destObjConfig.Bucket, destObjConfig.Object, newUploadHeaders) + try { + const partsDone = await performUploadParts(uploadId) + return await this.completeMultipartUpload(destObjConfig.Bucket, destObjConfig.Object, uploadId, partsDone) + } catch (err) { + return await this.abortMultipartUpload(destObjConfig.Bucket, destObjConfig.Object, uploadId) + } + } + + async presignedUrl( + method: string, + bucketName: string, + objectName: string, + expires?: number | PreSignRequestParams | undefined, + reqParams?: PreSignRequestParams | Date, + requestDate?: Date, + ): Promise { + if (this.anonymous) { + throw new errors.AnonymousRequestError(`Presigned ${method} url cannot be generated for anonymous requests`) + } + + if (!expires) { + expires = PRESIGN_EXPIRY_DAYS_MAX + } + if (!reqParams) { + reqParams = {} + } + if (!requestDate) { + requestDate = new Date() + } + + // Type assertions + if (expires && typeof expires !== 'number') { + throw new TypeError('expires should be of type "number"') + } + if (reqParams && typeof reqParams !== 'object') { + throw new TypeError('reqParams should be of type "object"') + } + if ((requestDate && !(requestDate instanceof Date)) || (requestDate && isNaN(requestDate?.getTime()))) { + throw new TypeError('requestDate should be of type "Date" and valid') + } + + const query = reqParams ? qs.stringify(reqParams) : undefined + + try { + const region = await this.getBucketRegionAsync(bucketName) + await this.checkAndRefreshCreds() + const reqOptions = this.getRequestOptions({ method, region, bucketName, objectName, query }) + + return presignSignatureV4( + reqOptions, + this.accessKey, + this.secretKey, + this.sessionToken, + region, + requestDate, + expires, + ) + } catch (err) { + if (err instanceof errors.InvalidBucketNameError) { + throw new errors.InvalidArgumentError(`Unable to get bucket region for ${bucketName}.`) + } + + throw err + } + } + + async presignedGetObject( + bucketName: string, + objectName: string, + expires?: number, + respHeaders?: PreSignRequestParams | Date, + requestDate?: Date, + ): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + + const validRespHeaders = [ + 'response-content-type', + 'response-content-language', + 'response-expires', + 'response-cache-control', + 'response-content-disposition', + 'response-content-encoding', + ] + validRespHeaders.forEach((header) => { + // @ts-ignore + if (respHeaders !== undefined && respHeaders[header] !== undefined && !isString(respHeaders[header])) { + throw new TypeError(`response header ${header} should be of type "string"`) + } + }) + return this.presignedUrl('GET', bucketName, objectName, expires, respHeaders, requestDate) + } + + async presignedPutObject(bucketName: string, objectName: string, expires?: number): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`) + } + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`) + } + + return this.presignedUrl('PUT', bucketName, objectName, expires) + } + + newPostPolicy(): PostPolicy { + return new PostPolicy() + } + + async presignedPostPolicy(postPolicy: PostPolicy): Promise { + if (this.anonymous) { + throw new errors.AnonymousRequestError('Presigned POST policy cannot be generated for anonymous requests') + } + if (!isObject(postPolicy)) { + throw new TypeError('postPolicy should be of type "object"') + } + const bucketName = postPolicy.formData.bucket as string + try { + const region = await this.getBucketRegionAsync(bucketName) + + const date = new Date() + const dateStr = makeDateLong(date) + await this.checkAndRefreshCreds() + + if (!postPolicy.policy.expiration) { + // 'expiration' is mandatory field for S3. + // Set default expiration date of 7 days. + const expires = new Date() + expires.setSeconds(PRESIGN_EXPIRY_DAYS_MAX) + postPolicy.setExpires(expires) + } + + postPolicy.policy.conditions.push(['eq', '$x-amz-date', dateStr]) + postPolicy.formData['x-amz-date'] = dateStr + + postPolicy.policy.conditions.push(['eq', '$x-amz-algorithm', 'AWS4-HMAC-SHA256']) + postPolicy.formData['x-amz-algorithm'] = 'AWS4-HMAC-SHA256' + + postPolicy.policy.conditions.push(['eq', '$x-amz-credential', this.accessKey + '/' + getScope(region, date)]) + postPolicy.formData['x-amz-credential'] = this.accessKey + '/' + getScope(region, date) + + if (this.sessionToken) { + postPolicy.policy.conditions.push(['eq', '$x-amz-security-token', this.sessionToken]) + postPolicy.formData['x-amz-security-token'] = this.sessionToken + } + + const policyBase64 = Buffer.from(JSON.stringify(postPolicy.policy)).toString('base64') + + postPolicy.formData.policy = policyBase64 + + postPolicy.formData['x-amz-signature'] = postPresignSignatureV4(region, date, this.secretKey, policyBase64) + const opts = { + region: region, + bucketName: bucketName, + method: 'POST', + } + const reqOptions = this.getRequestOptions(opts) + const portStr = this.port == 80 || this.port === 443 ? '' : `:${this.port.toString()}` + const urlStr = `${reqOptions.protocol}//${reqOptions.host}${portStr}${reqOptions.path}` + return { postURL: urlStr, formData: postPolicy.formData } + } catch (err) { + if (err instanceof errors.InvalidBucketNameError) { + throw new errors.InvalidArgumentError(`Unable to get bucket region for ${bucketName}.`) + } + + throw err + } + } + // list a batch of objects + async listObjectsQuery(bucketName: string, prefix?: string, marker?: string, listQueryOpts?: ListObjectQueryOpts) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isString(prefix)) { + throw new TypeError('prefix should be of type "string"') + } + if (marker && !isString(marker)) { + throw new TypeError('marker should be of type "string"') + } + + if (listQueryOpts && !isObject(listQueryOpts)) { + throw new TypeError('listQueryOpts should be of type "object"') + } + let { Delimiter, MaxKeys, IncludeVersion, versionIdMarker, keyMarker } = listQueryOpts as ListObjectQueryOpts + + if (!isString(Delimiter)) { + throw new TypeError('Delimiter should be of type "string"') + } + if (!isNumber(MaxKeys)) { + throw new TypeError('MaxKeys should be of type "number"') + } + + const queries = [] + // escape every value in query string, except maxKeys + queries.push(`prefix=${uriEscape(prefix)}`) + queries.push(`delimiter=${uriEscape(Delimiter)}`) + queries.push(`encoding-type=url`) + + if (IncludeVersion) { + queries.push(`versions`) + } + + if (IncludeVersion) { + // v1 version listing.. + if (keyMarker) { + queries.push(`key-marker=${keyMarker}`) + } + if (versionIdMarker) { + queries.push(`version-id-marker=${versionIdMarker}`) + } + } else if (marker) { + marker = uriEscape(marker) + queries.push(`marker=${marker}`) + } + + // no need to escape maxKeys + if (MaxKeys) { + if (MaxKeys >= 1000) { + MaxKeys = 1000 + } + queries.push(`max-keys=${MaxKeys}`) + } + queries.sort() + let query = '' + if (queries.length > 0) { + query = `${queries.join('&')}` + } + + const method = 'GET' + const res = await this.makeRequestAsync({ method, bucketName, query }) + const body = await readAsString(res) + const listQryList = parseListObjects(body) + return listQryList + } + + listObjects( + bucketName: string, + prefix?: string, + recursive?: boolean, + listOpts?: ListObjectQueryOpts | undefined, + ): BucketStream { + if (prefix === undefined) { + prefix = '' + } + if (recursive === undefined) { + recursive = false + } + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidPrefix(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`) + } + if (!isString(prefix)) { + throw new TypeError('prefix should be of type "string"') + } + if (!isBoolean(recursive)) { + throw new TypeError('recursive should be of type "boolean"') + } + if (listOpts && !isObject(listOpts)) { + throw new TypeError('listOpts should be of type "object"') + } + let marker: string | undefined = '' + let keyMarker: string | undefined = '' + let versionIdMarker: string | undefined = '' + let objects: ObjectInfo[] = [] + let ended = false + const readStream: stream.Readable = new stream.Readable({ objectMode: true }) + readStream._read = async () => { + // push one object per _read() + if (objects.length) { + readStream.push(objects.shift()) + return + } + if (ended) { + return readStream.push(null) + } + + try { + const listQueryOpts = { + Delimiter: recursive ? '' : '/', // if recursive is false set delimiter to '/' + MaxKeys: 1000, + IncludeVersion: listOpts?.IncludeVersion, + // version listing specific options + keyMarker: keyMarker, + versionIdMarker: versionIdMarker, + } + + const result: ListObjectQueryRes = await this.listObjectsQuery(bucketName, prefix, marker, listQueryOpts) + if (result.isTruncated) { + marker = result.nextMarker || undefined + if (result.keyMarker) { + keyMarker = result.keyMarker + } + if (result.versionIdMarker) { + versionIdMarker = result.versionIdMarker + } + } else { + ended = true + } + if (result.objects) { + objects = result.objects + } + // @ts-ignore + readStream._read() + } catch (err) { + readStream.emit('error', err) + } + } + return readStream + } + + async listObjectsV2Query( + bucketName: string, + prefix: string, + continuationToken: string, + delimiter: string, + maxKeys: number, + startAfter: string, + ): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isString(prefix)) { + throw new TypeError('prefix should be of type "string"') + } + if (!isString(continuationToken)) { + throw new TypeError('continuationToken should be of type "string"') + } + if (!isString(delimiter)) { + throw new TypeError('delimiter should be of type "string"') + } + if (!isNumber(maxKeys)) { + throw new TypeError('maxKeys should be of type "number"') + } + if (!isString(startAfter)) { + throw new TypeError('startAfter should be of type "string"') + } + + const queries = [] + queries.push(`list-type=2`) + queries.push(`encoding-type=url`) + queries.push(`prefix=${uriEscape(prefix)}`) + queries.push(`delimiter=${uriEscape(delimiter)}`) + + if (continuationToken) { + queries.push(`continuation-token=${uriEscape(continuationToken)}`) + } + if (startAfter) { + queries.push(`start-after=${uriEscape(startAfter)}`) + } + if (maxKeys) { + if (maxKeys >= 1000) { + maxKeys = 1000 + } + queries.push(`max-keys=${maxKeys}`) + } + queries.sort() + let query = '' + if (queries.length > 0) { + query = `${queries.join('&')}` + } + + const method = 'GET' + const res = await this.makeRequestAsync({ method, bucketName, query }) + const body = await readAsString(res) + return parseListObjectsV2(body) + } + + listObjectsV2( + bucketName: string, + prefix?: string, + recursive?: boolean, + startAfter?: string, + ): BucketStream { + if (prefix === undefined) { + prefix = '' + } + if (recursive === undefined) { + recursive = false + } + if (startAfter === undefined) { + startAfter = '' + } + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidPrefix(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`) + } + if (!isString(prefix)) { + throw new TypeError('prefix should be of type "string"') + } + if (!isBoolean(recursive)) { + throw new TypeError('recursive should be of type "boolean"') + } + if (!isString(startAfter)) { + throw new TypeError('startAfter should be of type "string"') + } + + const delimiter = recursive ? '' : '/' + const prefixStr = prefix + const startAfterStr = startAfter + let continuationToken = '' + let objects: BucketItem[] = [] + let ended = false + const readStream: stream.Readable = new stream.Readable({ objectMode: true }) + readStream._read = async () => { + if (objects.length) { + readStream.push(objects.shift()) + return + } + if (ended) { + return readStream.push(null) + } + + try { + const result = await this.listObjectsV2Query( + bucketName, + prefixStr, + continuationToken, + delimiter, + 1000, + startAfterStr, + ) + if (result.isTruncated) { + continuationToken = result.nextContinuationToken + } else { + ended = true + } + objects = result.objects + // @ts-ignore + readStream._read() + } catch (err) { + readStream.emit('error', err) + } + } + return readStream + } + + async setBucketNotification(bucketName: string, config: NotificationConfig): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isObject(config)) { + throw new TypeError('notification config should be of type "Object"') + } + const method = 'PUT' + const query = 'notification' + const builder = new xml2js.Builder({ + rootName: 'NotificationConfiguration', + renderOpts: { pretty: false }, + headless: true, + }) + const payload = builder.buildObject(config) + await this.makeRequestAsyncOmit({ method, bucketName, query }, payload) + } + + async removeAllBucketNotification(bucketName: string): Promise { + await this.setBucketNotification(bucketName, new NotificationConfig()) + } + + async getBucketNotification(bucketName: string): Promise { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + const method = 'GET' + const query = 'notification' + const res = await this.makeRequestAsync({ method, bucketName, query }) + const body = await readAsString(res) + return parseBucketNotification(body) + } + + listenBucketNotification( + bucketName: string, + prefix: string, + suffix: string, + events: NotificationEvent[], + ): NotificationPoller { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`) + } + if (!isString(prefix)) { + throw new TypeError('prefix must be of type string') + } + if (!isString(suffix)) { + throw new TypeError('suffix must be of type string') + } + if (!Array.isArray(events)) { + throw new TypeError('events must be of type Array') + } + const listener = new NotificationPoller(this, bucketName, prefix, suffix, events) + listener.start() + return listener + } +} diff --git a/node_modules/minio/src/internal/copy-conditions.ts b/node_modules/minio/src/internal/copy-conditions.ts new file mode 100644 index 0000000..b6710a6 --- /dev/null +++ b/node_modules/minio/src/internal/copy-conditions.ts @@ -0,0 +1,30 @@ +export class CopyConditions { + public modified = '' + public unmodified = '' + public matchETag = '' + public matchETagExcept = '' + + setModified(date: Date): void { + if (!(date instanceof Date)) { + throw new TypeError('date must be of type Date') + } + + this.modified = date.toUTCString() + } + + setUnmodified(date: Date): void { + if (!(date instanceof Date)) { + throw new TypeError('date must be of type Date') + } + + this.unmodified = date.toUTCString() + } + + setMatchETag(etag: string): void { + this.matchETag = etag + } + + setMatchETagExcept(etag: string): void { + this.matchETagExcept = etag + } +} diff --git a/node_modules/minio/src/internal/extensions.ts b/node_modules/minio/src/internal/extensions.ts new file mode 100644 index 0000000..b2484d1 --- /dev/null +++ b/node_modules/minio/src/internal/extensions.ts @@ -0,0 +1,140 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2020 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as stream from 'node:stream' + +import * as errors from '../errors.ts' +import type { TypedClient } from './client.ts' +import { isBoolean, isString, isValidBucketName, isValidPrefix, uriEscape } from './helper.ts' +import { readAsString } from './response.ts' +import type { BucketItemWithMetadata, BucketStream } from './type.ts' +import { parseListObjectsV2WithMetadata } from './xml-parser.ts' + +export class Extensions { + private readonly client: TypedClient + + constructor(client: TypedClient) { + this.client = client + } + + /** + * List the objects in the bucket using S3 ListObjects V2 With Metadata + * + * @param bucketName - name of the bucket + * @param prefix - the prefix of the objects that should be listed (optional, default `''`) + * @param recursive - `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'. (optional, default `false`) + * @param startAfter - Specifies the key to start after when listing objects in a bucket. (optional, default `''`) + * @returns stream emitting the objects in the bucket, the object is of the format: + */ + public listObjectsV2WithMetadata( + bucketName: string, + prefix?: string, + recursive?: boolean, + startAfter?: string, + ): BucketStream { + if (prefix === undefined) { + prefix = '' + } + if (recursive === undefined) { + recursive = false + } + if (startAfter === undefined) { + startAfter = '' + } + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName) + } + if (!isValidPrefix(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`) + } + if (!isString(prefix)) { + throw new TypeError('prefix should be of type "string"') + } + if (!isBoolean(recursive)) { + throw new TypeError('recursive should be of type "boolean"') + } + if (!isString(startAfter)) { + throw new TypeError('startAfter should be of type "string"') + } + + // if recursive is false set delimiter to '/' + const delimiter = recursive ? '' : '/' + return stream.Readable.from(this.listObjectsV2WithMetadataGen(bucketName, prefix, delimiter, startAfter), { + objectMode: true, + }) + } + + private async *listObjectsV2WithMetadataGen( + bucketName: string, + prefix: string, + delimiter: string, + startAfter: string, + ): AsyncIterable { + let ended = false + let continuationToken = '' + do { + const result = await this.listObjectsV2WithMetadataQuery( + bucketName, + prefix, + continuationToken, + delimiter, + startAfter, + ) + ended = !result.isTruncated + continuationToken = result.nextContinuationToken + for (const obj of result.objects) { + yield obj + } + } while (!ended) + } + + private async listObjectsV2WithMetadataQuery( + bucketName: string, + prefix: string, + continuationToken: string, + delimiter: string, + startAfter: string, + ) { + const queries = [] + + // Call for listing objects v2 API + queries.push(`list-type=2`) + queries.push(`encoding-type=url`) + // escape every value in query string, except maxKeys + queries.push(`prefix=${uriEscape(prefix)}`) + queries.push(`delimiter=${uriEscape(delimiter)}`) + queries.push(`metadata=true`) + + if (continuationToken) { + continuationToken = uriEscape(continuationToken) + queries.push(`continuation-token=${continuationToken}`) + } + // Set start-after + if (startAfter) { + startAfter = uriEscape(startAfter) + queries.push(`start-after=${startAfter}`) + } + queries.push(`max-keys=1000`) + queries.sort() + let query = '' + if (queries.length > 0) { + query = `${queries.join('&')}` + } + const method = 'GET' + const res = await this.client.makeRequestAsync({ method, bucketName, query }) + return parseListObjectsV2WithMetadata(await readAsString(res)) + } +} diff --git a/node_modules/minio/src/internal/helper.ts b/node_modules/minio/src/internal/helper.ts new file mode 100644 index 0000000..0a0c576 --- /dev/null +++ b/node_modules/minio/src/internal/helper.ts @@ -0,0 +1,606 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as crypto from 'node:crypto' +import * as stream from 'node:stream' + +import { XMLParser } from 'fast-xml-parser' +import ipaddr from 'ipaddr.js' +import _ from 'lodash' +import * as mime from 'mime-types' + +import { fsp, fstat } from './async.ts' +import type { Binary, Encryption, ObjectMetaData, RequestHeaders, ResponseHeader } from './type.ts' +import { ENCRYPTION_TYPES } from './type.ts' + +const MetaDataHeaderPrefix = 'x-amz-meta-' + +export function hashBinary(buf: Buffer, enableSHA256: boolean) { + let sha256sum = '' + if (enableSHA256) { + sha256sum = crypto.createHash('sha256').update(buf).digest('hex') + } + const md5sum = crypto.createHash('md5').update(buf).digest('base64') + + return { md5sum, sha256sum } +} + +// S3 percent-encodes some extra non-standard characters in a URI . So comply with S3. +const encodeAsHex = (c: string) => `%${c.charCodeAt(0).toString(16).toUpperCase()}` +export function uriEscape(uriStr: string): string { + return encodeURIComponent(uriStr).replace(/[!'()*]/g, encodeAsHex) +} + +export function uriResourceEscape(string: string) { + return uriEscape(string).replace(/%2F/g, '/') +} + +export function getScope(region: string, date: Date, serviceName = 's3') { + return `${makeDateShort(date)}/${region}/${serviceName}/aws4_request` +} + +/** + * isAmazonEndpoint - true if endpoint is 's3.amazonaws.com' or 's3.cn-north-1.amazonaws.com.cn' + */ +export function isAmazonEndpoint(endpoint: string) { + return endpoint === 's3.amazonaws.com' || endpoint === 's3.cn-north-1.amazonaws.com.cn' +} + +/** + * isVirtualHostStyle - verify if bucket name is support with virtual + * hosts. bucketNames with periods should be always treated as path + * style if the protocol is 'https:', this is due to SSL wildcard + * limitation. For all other buckets and Amazon S3 endpoint we will + * default to virtual host style. + */ +export function isVirtualHostStyle(endpoint: string, protocol: string, bucket: string, pathStyle: boolean) { + if (protocol === 'https:' && bucket.includes('.')) { + return false + } + return isAmazonEndpoint(endpoint) || !pathStyle +} + +export function isValidIP(ip: string) { + return ipaddr.isValid(ip) +} + +/** + * @returns if endpoint is valid domain. + */ +export function isValidEndpoint(endpoint: string) { + return isValidDomain(endpoint) || isValidIP(endpoint) +} + +/** + * @returns if input host is a valid domain. + */ +export function isValidDomain(host: string) { + if (!isString(host)) { + return false + } + // See RFC 1035, RFC 3696. + if (host.length === 0 || host.length > 255) { + return false + } + // Host cannot start or end with a '-' + if (host[0] === '-' || host.slice(-1) === '-') { + return false + } + // Host cannot start or end with a '_' + if (host[0] === '_' || host.slice(-1) === '_') { + return false + } + // Host cannot start with a '.' + if (host[0] === '.') { + return false + } + + const nonAlphaNumerics = '`~!@#$%^&*()+={}[]|\\"\';:> 63) { + return false + } + // bucket with successive periods is invalid. + if (bucket.includes('..')) { + return false + } + // bucket cannot have ip address style. + if (/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/.test(bucket)) { + return false + } + // bucket should begin with alphabet/number and end with alphabet/number, + // with alphabet/number/.- in the middle. + if (/^[a-z0-9][a-z0-9.-]+[a-z0-9]$/.test(bucket)) { + return true + } + return false +} + +/** + * check if objectName is a valid object name + */ +export function isValidObjectName(objectName: unknown) { + if (!isValidPrefix(objectName)) { + return false + } + + return objectName.length !== 0 +} + +/** + * check if prefix is valid + */ +export function isValidPrefix(prefix: unknown): prefix is string { + if (!isString(prefix)) { + return false + } + if (prefix.length > 1024) { + return false + } + return true +} + +/** + * check if typeof arg number + */ +export function isNumber(arg: unknown): arg is number { + return typeof arg === 'number' +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type AnyFunction = (...args: any[]) => any + +/** + * check if typeof arg function + */ +export function isFunction(arg: unknown): arg is AnyFunction { + return typeof arg === 'function' +} + +/** + * check if typeof arg string + */ +export function isString(arg: unknown): arg is string { + return typeof arg === 'string' +} + +/** + * check if typeof arg object + */ +export function isObject(arg: unknown): arg is object { + return typeof arg === 'object' && arg !== null +} +/** + * check if typeof arg is plain object + */ +export function isPlainObject(arg: unknown): arg is Record { + return Object.prototype.toString.call(arg) === '[object Object]' +} +/** + * check if object is readable stream + */ +export function isReadableStream(arg: unknown): arg is stream.Readable { + // eslint-disable-next-line @typescript-eslint/unbound-method + return isObject(arg) && isFunction((arg as stream.Readable)._read) +} + +/** + * check if arg is boolean + */ +export function isBoolean(arg: unknown): arg is boolean { + return typeof arg === 'boolean' +} + +export function isEmpty(o: unknown): o is null | undefined { + return _.isEmpty(o) +} + +export function isEmptyObject(o: Record): boolean { + return Object.values(o).filter((x) => x !== undefined).length !== 0 +} + +export function isDefined(o: T): o is Exclude { + return o !== null && o !== undefined +} + +/** + * check if arg is a valid date + */ +export function isValidDate(arg: unknown): arg is Date { + // @ts-expect-error checknew Date(Math.NaN) + return arg instanceof Date && !isNaN(arg) +} + +/** + * Create a Date string with format: 'YYYYMMDDTHHmmss' + Z + */ +export function makeDateLong(date?: Date): string { + date = date || new Date() + + // Gives format like: '2017-08-07T16:28:59.889Z' + const s = date.toISOString() + + return s.slice(0, 4) + s.slice(5, 7) + s.slice(8, 13) + s.slice(14, 16) + s.slice(17, 19) + 'Z' +} + +/** + * Create a Date string with format: 'YYYYMMDD' + */ +export function makeDateShort(date?: Date) { + date = date || new Date() + + // Gives format like: '2017-08-07T16:28:59.889Z' + const s = date.toISOString() + + return s.slice(0, 4) + s.slice(5, 7) + s.slice(8, 10) +} + +/** + * pipesetup sets up pipe() from left to right os streams array + * pipesetup will also make sure that error emitted at any of the upstream Stream + * will be emitted at the last stream. This makes error handling simple + */ +export function pipesetup(...streams: [stream.Readable, ...stream.Duplex[], stream.Writable]) { + // @ts-expect-error ts can't narrow this + return streams.reduce((src: stream.Readable, dst: stream.Writable) => { + src.on('error', (err) => dst.emit('error', err)) + return src.pipe(dst) + }) +} + +/** + * return a Readable stream that emits data + */ +export function readableStream(data: unknown): stream.Readable { + const s = new stream.Readable() + s._read = () => {} + s.push(data) + s.push(null) + return s +} + +/** + * Process metadata to insert appropriate value to `content-type` attribute + */ +export function insertContentType(metaData: ObjectMetaData, filePath: string): ObjectMetaData { + // check if content-type attribute present in metaData + for (const key in metaData) { + if (key.toLowerCase() === 'content-type') { + return metaData + } + } + + // if `content-type` attribute is not present in metadata, then infer it from the extension in filePath + return { + ...metaData, + 'content-type': probeContentType(filePath), + } +} + +/** + * Function prepends metadata with the appropriate prefix if it is not already on + */ +export function prependXAMZMeta(metaData?: ObjectMetaData): RequestHeaders { + if (!metaData) { + return {} + } + + return _.mapKeys(metaData, (value, key) => { + if (isAmzHeader(key) || isSupportedHeader(key) || isStorageClassHeader(key)) { + return key + } + + return MetaDataHeaderPrefix + key + }) +} + +/** + * Checks if it is a valid header according to the AmazonS3 API + */ +export function isAmzHeader(key: string) { + const temp = key.toLowerCase() + return ( + temp.startsWith(MetaDataHeaderPrefix) || + temp === 'x-amz-acl' || + temp.startsWith('x-amz-server-side-encryption-') || + temp === 'x-amz-server-side-encryption' + ) +} + +/** + * Checks if it is a supported Header + */ +export function isSupportedHeader(key: string) { + const supported_headers = [ + 'content-type', + 'cache-control', + 'content-encoding', + 'content-disposition', + 'content-language', + 'x-amz-website-redirect-location', + 'if-none-match', + 'if-match', + ] + return supported_headers.includes(key.toLowerCase()) +} + +/** + * Checks if it is a storage header + */ +export function isStorageClassHeader(key: string) { + return key.toLowerCase() === 'x-amz-storage-class' +} + +export function extractMetadata(headers: ResponseHeader) { + return _.mapKeys( + _.pickBy(headers, (value, key) => isSupportedHeader(key) || isStorageClassHeader(key) || isAmzHeader(key)), + (value, key) => { + const lower = key.toLowerCase() + if (lower.startsWith(MetaDataHeaderPrefix)) { + return lower.slice(MetaDataHeaderPrefix.length) + } + + return key + }, + ) +} + +export function getVersionId(headers: ResponseHeader = {}) { + return headers['x-amz-version-id'] || null +} + +export function getSourceVersionId(headers: ResponseHeader = {}) { + return headers['x-amz-copy-source-version-id'] || null +} + +export function sanitizeETag(etag = ''): string { + const replaceChars: Record = { + '"': '', + '"': '', + '"': '', + '"': '', + '"': '', + } + return etag.replace(/^("|"|")|("|"|")$/g, (m) => replaceChars[m] as string) +} + +export function toMd5(payload: Binary): string { + // use string from browser and buffer from nodejs + // browser support is tested only against minio server + return crypto.createHash('md5').update(Buffer.from(payload)).digest().toString('base64') +} + +export function toSha256(payload: Binary): string { + return crypto.createHash('sha256').update(payload).digest('hex') +} + +/** + * toArray returns a single element array with param being the element, + * if param is just a string, and returns 'param' back if it is an array + * So, it makes sure param is always an array + */ +export function toArray(param: T | T[]): Array { + if (!Array.isArray(param)) { + return [param] as T[] + } + return param +} + +export function sanitizeObjectKey(objectName: string): string { + // + symbol characters are not decoded as spaces in JS. so replace them first and decode to get the correct result. + const asStrName = (objectName ? objectName.toString() : '').replace(/\+/g, ' ') + return decodeURIComponent(asStrName) +} + +export function sanitizeSize(size?: string): number | undefined { + return size ? Number.parseInt(size) : undefined +} + +export const PART_CONSTRAINTS = { + // absMinPartSize - absolute minimum part size (5 MiB) + ABS_MIN_PART_SIZE: 1024 * 1024 * 5, + // MIN_PART_SIZE - minimum part size 16MiB per object after which + MIN_PART_SIZE: 1024 * 1024 * 16, + // MAX_PARTS_COUNT - maximum number of parts for a single multipart session. + MAX_PARTS_COUNT: 10000, + // MAX_PART_SIZE - maximum part size 5GiB for a single multipart upload + // operation. + MAX_PART_SIZE: 1024 * 1024 * 1024 * 5, + // MAX_SINGLE_PUT_OBJECT_SIZE - maximum size 5GiB of object per PUT + // operation. + MAX_SINGLE_PUT_OBJECT_SIZE: 1024 * 1024 * 1024 * 5, + // MAX_MULTIPART_PUT_OBJECT_SIZE - maximum size 5TiB of object for + // Multipart operation. + MAX_MULTIPART_PUT_OBJECT_SIZE: 1024 * 1024 * 1024 * 1024 * 5, +} + +const GENERIC_SSE_HEADER = 'X-Amz-Server-Side-Encryption' + +const ENCRYPTION_HEADERS = { + // sseGenericHeader is the AWS SSE header used for SSE-S3 and SSE-KMS. + sseGenericHeader: GENERIC_SSE_HEADER, + // sseKmsKeyID is the AWS SSE-KMS key id. + sseKmsKeyID: GENERIC_SSE_HEADER + '-Aws-Kms-Key-Id', +} as const + +/** + * Return Encryption headers + * @param encConfig + * @returns an object with key value pairs that can be used in headers. + */ +export function getEncryptionHeaders(encConfig: Encryption): RequestHeaders { + const encType = encConfig.type + + if (!isEmpty(encType)) { + if (encType === ENCRYPTION_TYPES.SSEC) { + return { + [ENCRYPTION_HEADERS.sseGenericHeader]: 'AES256', + } + } else if (encType === ENCRYPTION_TYPES.KMS) { + return { + [ENCRYPTION_HEADERS.sseGenericHeader]: encConfig.SSEAlgorithm, + [ENCRYPTION_HEADERS.sseKmsKeyID]: encConfig.KMSMasterKeyID, + } + } + } + + return {} +} + +export function partsRequired(size: number): number { + const maxPartSize = PART_CONSTRAINTS.MAX_MULTIPART_PUT_OBJECT_SIZE / (PART_CONSTRAINTS.MAX_PARTS_COUNT - 1) + let requiredPartSize = size / maxPartSize + if (size % maxPartSize > 0) { + requiredPartSize++ + } + requiredPartSize = Math.trunc(requiredPartSize) + return requiredPartSize +} + +/** + * calculateEvenSplits - computes splits for a source and returns + * start and end index slices. Splits happen evenly to be sure that no + * part is less than 5MiB, as that could fail the multipart request if + * it is not the last part. + */ +export function calculateEvenSplits( + size: number, + objInfo: T, +): { + startIndex: number[] + objInfo: T + endIndex: number[] +} | null { + if (size === 0) { + return null + } + const reqParts = partsRequired(size) + const startIndexParts: number[] = [] + const endIndexParts: number[] = [] + + let start = objInfo.Start + if (isEmpty(start) || start === -1) { + start = 0 + } + const divisorValue = Math.trunc(size / reqParts) + + const reminderValue = size % reqParts + + let nextStart = start + + for (let i = 0; i < reqParts; i++) { + let curPartSize = divisorValue + if (i < reminderValue) { + curPartSize++ + } + + const currentStart = nextStart + const currentEnd = currentStart + curPartSize - 1 + nextStart = currentEnd + 1 + + startIndexParts.push(currentStart) + endIndexParts.push(currentEnd) + } + + return { startIndex: startIndexParts, endIndex: endIndexParts, objInfo: objInfo } +} +const fxp = new XMLParser({ numberParseOptions: { eNotation: false, hex: true, leadingZeros: true } }) + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function parseXml(xml: string): any { + const result = fxp.parse(xml) + if (result.Error) { + throw result.Error + } + + return result +} + +/** + * get content size of object content to upload + */ +export async function getContentLength(s: stream.Readable | Buffer | string): Promise { + // use length property of string | Buffer + if (typeof s === 'string' || Buffer.isBuffer(s)) { + return s.length + } + + // property of `fs.ReadStream` + const filePath = (s as unknown as Record).path as string | undefined + if (filePath && typeof filePath === 'string') { + const stat = await fsp.lstat(filePath) + return stat.size + } + + // property of `fs.ReadStream` + const fd = (s as unknown as Record).fd as number | null | undefined + if (fd && typeof fd === 'number') { + const stat = await fstat(fd) + return stat.size + } + + return null +} diff --git a/node_modules/minio/src/internal/join-host-port.ts b/node_modules/minio/src/internal/join-host-port.ts new file mode 100644 index 0000000..bfdf4d1 --- /dev/null +++ b/node_modules/minio/src/internal/join-host-port.ts @@ -0,0 +1,23 @@ +/** + * joinHostPort combines host and port into a network address of the + * form "host:port". If host contains a colon, as found in literal + * IPv6 addresses, then JoinHostPort returns "[host]:port". + * + * @param host + * @param port + * @returns Cleaned up host + * @internal + */ +export function joinHostPort(host: string, port?: number): string { + if (port === undefined) { + return host + } + + // We assume that host is a literal IPv6 address if host has + // colons. + if (host.includes(':')) { + return `[${host}]:${port.toString()}` + } + + return `${host}:${port.toString()}` +} diff --git a/node_modules/minio/src/internal/post-policy.ts b/node_modules/minio/src/internal/post-policy.ts new file mode 100644 index 0000000..78a6ae8 --- /dev/null +++ b/node_modules/minio/src/internal/post-policy.ts @@ -0,0 +1,99 @@ +// Build PostPolicy object that can be signed by presignedPostPolicy +import * as errors from '../errors.ts' +import { isObject, isValidBucketName, isValidObjectName, isValidPrefix } from './helper.ts' +import type { ObjectMetaData } from './type.ts' + +export class PostPolicy { + public policy: { conditions: (string | number)[][]; expiration?: string } = { + conditions: [], + } + public formData: Record = {} + + // set expiration date + setExpires(date: Date) { + if (!date) { + throw new errors.InvalidDateError('Invalid date: cannot be null') + } + this.policy.expiration = date.toISOString() + } + + // set object name + setKey(objectName: string) { + if (!isValidObjectName(objectName)) { + throw new errors.InvalidObjectNameError(`Invalid object name : ${objectName}`) + } + this.policy.conditions.push(['eq', '$key', objectName]) + this.formData.key = objectName + } + + // set object name prefix, i.e policy allows any keys with this prefix + setKeyStartsWith(prefix: string) { + if (!isValidPrefix(prefix)) { + throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`) + } + this.policy.conditions.push(['starts-with', '$key', prefix]) + this.formData.key = prefix + } + + // set bucket name + setBucket(bucketName: string) { + if (!isValidBucketName(bucketName)) { + throw new errors.InvalidBucketNameError(`Invalid bucket name : ${bucketName}`) + } + this.policy.conditions.push(['eq', '$bucket', bucketName]) + this.formData.bucket = bucketName + } + + // set Content-Type + setContentType(type: string) { + if (!type) { + throw new Error('content-type cannot be null') + } + this.policy.conditions.push(['eq', '$Content-Type', type]) + this.formData['Content-Type'] = type + } + + // set Content-Type prefix, i.e image/ allows any image + setContentTypeStartsWith(prefix: string) { + if (!prefix) { + throw new Error('content-type cannot be null') + } + this.policy.conditions.push(['starts-with', '$Content-Type', prefix]) + this.formData['Content-Type'] = prefix + } + + // set Content-Disposition + setContentDisposition(value: string) { + if (!value) { + throw new Error('content-disposition cannot be null') + } + this.policy.conditions.push(['eq', '$Content-Disposition', value]) + this.formData['Content-Disposition'] = value + } + + // set minimum/maximum length of what Content-Length can be. + setContentLengthRange(min: number, max: number) { + if (min > max) { + throw new Error('min cannot be more than max') + } + if (min < 0) { + throw new Error('min should be > 0') + } + if (max < 0) { + throw new Error('max should be > 0') + } + this.policy.conditions.push(['content-length-range', min, max]) + } + + // set user defined metadata + setUserMetaData(metaData: ObjectMetaData) { + if (!isObject(metaData)) { + throw new TypeError('metadata should be of type "object"') + } + Object.entries(metaData).forEach(([key, value]) => { + const amzMetaDataKey = `x-amz-meta-${key}` + this.policy.conditions.push(['eq', `$${amzMetaDataKey}`, value]) + this.formData[amzMetaDataKey] = value.toString() + }) + } +} diff --git a/node_modules/minio/src/internal/request.ts b/node_modules/minio/src/internal/request.ts new file mode 100644 index 0000000..0d8bce6 --- /dev/null +++ b/node_modules/minio/src/internal/request.ts @@ -0,0 +1,102 @@ +import type * as http from 'node:http' +import type * as https from 'node:https' +import type * as stream from 'node:stream' +import { pipeline } from 'node:stream' +import { promisify } from 'node:util' + +import type { Transport } from './type.ts' + +const pipelineAsync = promisify(pipeline) + +export async function request( + transport: Transport, + opt: https.RequestOptions, + body: Buffer | string | stream.Readable | null = null, +): Promise { + return new Promise((resolve, reject) => { + const requestObj = transport.request(opt, (response) => { + resolve(response) + }) + + requestObj.on('error', reject) + + if (!body || Buffer.isBuffer(body) || typeof body === 'string') { + requestObj.end(body) + } else { + pipelineAsync(body, requestObj).catch(reject) + } + }) +} + +const MAX_RETRIES = 1 +const BASE_DELAY_MS = 100 // Base delay for exponential backoff +const MAX_DELAY_MS = 60000 // Max delay for exponential backoff + +// Retryable error codes for HTTP ( ref: minio-go) +export const retryHttpCodes: Record = { + 408: true, + 429: true, + 499: true, + 500: true, + 502: true, + 503: true, + 504: true, + 520: true, +} + +const isHttpRetryable = (httpResCode: number) => { + return retryHttpCodes[httpResCode] !== undefined +} + +const sleep = (ms: number) => { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +const getExpBackOffDelay = (retryCount: number, baseDelayMs: number, maximumDelayMs: number) => { + const backOffBy = baseDelayMs * (1 << retryCount) + const additionalDelay = Math.random() * backOffBy + return Math.min(backOffBy + additionalDelay, maximumDelayMs) +} + +export async function requestWithRetry( + transport: Transport, + opt: https.RequestOptions, + body: Buffer | string | stream.Readable | null = null, + maxRetries: number = MAX_RETRIES, + baseDelayMs: number = BASE_DELAY_MS, + maximumDelayMs: number = MAX_DELAY_MS, +): Promise { + let attempt = 0 + let isRetryable = false + while (attempt <= maxRetries) { + try { + const response = await request(transport, opt, body) + // Check if the HTTP status code is retryable + if (isHttpRetryable(response.statusCode as number)) { + isRetryable = true + throw new Error(`Retryable HTTP status: ${response.statusCode}`) // trigger retry attempt with calculated delay + } + + return response // Success, return the raw response + } catch (err: unknown) { + if (isRetryable) { + attempt++ + isRetryable = false + + if (attempt > maxRetries) { + throw new Error(`Request failed after ${maxRetries} retries: ${err}`) + } + const delay = getExpBackOffDelay(attempt, baseDelayMs, maximumDelayMs) + // eslint-disable-next-line no-console + console.warn( + `${new Date().toLocaleString()} Retrying request (attempt ${attempt}/${maxRetries}) after ${delay}ms due to: ${err}`, + ) + await sleep(delay) + } else { + throw err // re-throw if any request, syntax errors + } + } + } + + throw new Error(`${MAX_RETRIES} Retries exhausted, request failed.`) +} diff --git a/node_modules/minio/src/internal/response.ts b/node_modules/minio/src/internal/response.ts new file mode 100644 index 0000000..bb3a0b1 --- /dev/null +++ b/node_modules/minio/src/internal/response.ts @@ -0,0 +1,26 @@ +import type http from 'node:http' +import type stream from 'node:stream' + +export async function readAsBuffer(res: stream.Readable): Promise { + return new Promise((resolve, reject) => { + const body: Buffer[] = [] + res + .on('data', (chunk: Buffer) => body.push(chunk)) + .on('error', (e) => reject(e)) + .on('end', () => resolve(Buffer.concat(body))) + }) +} + +export async function readAsString(res: http.IncomingMessage): Promise { + const body = await readAsBuffer(res) + return body.toString() +} + +export async function drainResponse(res: stream.Readable): Promise { + return new Promise((resolve, reject) => { + res + .on('data', () => {}) + .on('error', (e) => reject(e)) + .on('end', () => resolve()) + }) +} diff --git a/node_modules/minio/src/internal/s3-endpoints.ts b/node_modules/minio/src/internal/s3-endpoints.ts new file mode 100644 index 0000000..e61c9eb --- /dev/null +++ b/node_modules/minio/src/internal/s3-endpoints.ts @@ -0,0 +1,70 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015, 2016 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isString } from './helper.ts' + +// List of currently supported endpoints. +const awsS3Endpoint = { + 'af-south-1': 's3.af-south-1.amazonaws.com', + 'ap-east-1': 's3.ap-east-1.amazonaws.com', + 'ap-south-1': 's3.ap-south-1.amazonaws.com', + 'ap-south-2': 's3.ap-south-2.amazonaws.com', + 'ap-southeast-1': 's3.ap-southeast-1.amazonaws.com', + 'ap-southeast-2': 's3.ap-southeast-2.amazonaws.com', + 'ap-southeast-3': 's3.ap-southeast-3.amazonaws.com', + 'ap-southeast-4': 's3.ap-southeast-4.amazonaws.com', + 'ap-southeast-5': 's3.ap-southeast-5.amazonaws.com', + 'ap-northeast-1': 's3.ap-northeast-1.amazonaws.com', + 'ap-northeast-2': 's3.ap-northeast-2.amazonaws.com', + 'ap-northeast-3': 's3.ap-northeast-3.amazonaws.com', + 'ca-central-1': 's3.ca-central-1.amazonaws.com', + 'ca-west-1': 's3.ca-west-1.amazonaws.com', + 'cn-north-1': 's3.cn-north-1.amazonaws.com.cn', + 'eu-central-1': 's3.eu-central-1.amazonaws.com', + 'eu-central-2': 's3.eu-central-2.amazonaws.com', + 'eu-north-1': 's3.eu-north-1.amazonaws.com', + 'eu-south-1': 's3.eu-south-1.amazonaws.com', + 'eu-south-2': 's3.eu-south-2.amazonaws.com', + 'eu-west-1': 's3.eu-west-1.amazonaws.com', + 'eu-west-2': 's3.eu-west-2.amazonaws.com', + 'eu-west-3': 's3.eu-west-3.amazonaws.com', + 'il-central-1': 's3.il-central-1.amazonaws.com', + 'me-central-1': 's3.me-central-1.amazonaws.com', + 'me-south-1': 's3.me-south-1.amazonaws.com', + 'sa-east-1': 's3.sa-east-1.amazonaws.com', + 'us-east-1': 's3.us-east-1.amazonaws.com', + 'us-east-2': 's3.us-east-2.amazonaws.com', + 'us-west-1': 's3.us-west-1.amazonaws.com', + 'us-west-2': 's3.us-west-2.amazonaws.com', + 'us-gov-east-1': 's3.us-gov-east-1.amazonaws.com', + 'us-gov-west-1': 's3.us-gov-west-1.amazonaws.com', + // Add new endpoints here. +} + +export type Region = keyof typeof awsS3Endpoint | string + +// getS3Endpoint get relevant endpoint for the region. +export function getS3Endpoint(region: Region): string { + if (!isString(region)) { + throw new TypeError(`Invalid region: ${region}`) + } + + const endpoint = (awsS3Endpoint as Record)[region] + if (endpoint) { + return endpoint + } + return 's3.amazonaws.com' +} diff --git a/node_modules/minio/src/internal/type.ts b/node_modules/minio/src/internal/type.ts new file mode 100644 index 0000000..1f3583c --- /dev/null +++ b/node_modules/minio/src/internal/type.ts @@ -0,0 +1,577 @@ +import type * as http from 'node:http' +import type { Readable as ReadableStream } from 'node:stream' + +import type { CopyDestinationOptions, CopySourceOptions } from '../helpers.ts' +import type { CopyConditions } from './copy-conditions.ts' + +export type VersionIdentificator = { + versionId?: string +} + +export type GetObjectOpts = VersionIdentificator & { + SSECustomerAlgorithm?: string + SSECustomerKey?: string + SSECustomerKeyMD5?: string +} + +export type Binary = string | Buffer + +// nodejs IncomingHttpHeaders is Record, but it's actually this: +export type ResponseHeader = Record + +export type ObjectMetaData = Record + +export type RequestHeaders = Record +export type EnabledOrDisabledStatus = 'Enabled' | 'Disabled' + +export const ENCRYPTION_TYPES = { + SSEC: 'SSE-C', + KMS: 'KMS', +} as const + +export type ENCRYPTION_TYPES = (typeof ENCRYPTION_TYPES)[keyof typeof ENCRYPTION_TYPES] + +export type Encryption = + | { + type: typeof ENCRYPTION_TYPES.SSEC + } + | { + type: typeof ENCRYPTION_TYPES.KMS + SSEAlgorithm?: string + KMSMasterKeyID?: string + } + +export const RETENTION_MODES = { + GOVERNANCE: 'GOVERNANCE', + COMPLIANCE: 'COMPLIANCE', +} as const +export type RETENTION_MODES = (typeof RETENTION_MODES)[keyof typeof RETENTION_MODES] + +export const RETENTION_VALIDITY_UNITS = { + DAYS: 'Days', + YEARS: 'Years', +} as const +export type RETENTION_VALIDITY_UNITS = (typeof RETENTION_VALIDITY_UNITS)[keyof typeof RETENTION_VALIDITY_UNITS] + +export const LEGAL_HOLD_STATUS = { + ENABLED: 'ON', + DISABLED: 'OFF', +} as const +export type LEGAL_HOLD_STATUS = (typeof LEGAL_HOLD_STATUS)[keyof typeof LEGAL_HOLD_STATUS] + +export type Transport = Pick + +export interface IRequest { + protocol: string + port?: number | string + method: string + path: string + headers: RequestHeaders +} + +export type ICanonicalRequest = string + +export interface IncompleteUploadedBucketItem { + key: string + uploadId: string + size: number +} + +export interface MetadataItem { + Key: string + Value: string +} + +export interface ItemBucketMetadataList { + Items: MetadataItem[] +} + +export interface ItemBucketMetadata { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [key: string]: any +} +export interface ItemBucketTags { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [key: string]: any +} + +export interface BucketItemFromList { + name: string + creationDate: Date +} + +export interface BucketItemCopy { + etag: string + lastModified: Date +} + +export type BucketItem = + | { + name: string + size: number + etag: string + prefix?: never + lastModified: Date + } + | { + name?: never + etag?: never + lastModified?: never + prefix: string + size: 0 + } + +export type BucketItemWithMetadata = BucketItem & { + metadata?: ItemBucketMetadata | ItemBucketMetadataList + tags?: ItemBucketTags +} + +export interface BucketStream extends ReadableStream { + on(event: 'data', listener: (item: T) => void): this + + on(event: 'end' | 'pause' | 'readable' | 'resume' | 'close', listener: () => void): this + + on(event: 'error', listener: (err: Error) => void): this + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + on(event: string | symbol, listener: (...args: any[]) => void): this +} + +export interface BucketItemStat { + size: number + etag: string + lastModified: Date + metaData: ItemBucketMetadata + versionId?: string | null +} + +export type StatObjectOpts = { + versionId?: string +} + +/* Replication Config types */ +export type ReplicationRuleStatus = { + Status: EnabledOrDisabledStatus +} + +export type Tag = { + Key: string + Value: string +} + +export type Tags = Record + +export type ReplicationRuleDestination = { + Bucket: string + StorageClass: string +} +export type ReplicationRuleAnd = { + Prefix: string + Tags: Tag[] +} + +export type ReplicationRuleFilter = { + Prefix: string + And: ReplicationRuleAnd + Tag: Tag +} + +export type ReplicaModifications = { + Status: ReplicationRuleStatus +} + +export type SourceSelectionCriteria = { + ReplicaModifications: ReplicaModifications +} + +export type ExistingObjectReplication = { + Status: ReplicationRuleStatus +} + +export type ReplicationRule = { + ID: string + Status: ReplicationRuleStatus + Priority: number + DeleteMarkerReplication: ReplicationRuleStatus // should be set to "Disabled" by default + DeleteReplication: ReplicationRuleStatus + Destination: ReplicationRuleDestination + Filter: ReplicationRuleFilter + SourceSelectionCriteria: SourceSelectionCriteria + ExistingObjectReplication: ExistingObjectReplication +} + +export type ReplicationConfigOpts = { + role: string + rules: ReplicationRule[] +} + +export type ReplicationConfig = { + ReplicationConfiguration: ReplicationConfigOpts +} +/* Replication Config types */ + +export type ResultCallback = (error: Error | null, result: T) => void + +export type GetObjectLegalHoldOptions = { + versionId: string +} +/** + * @deprecated keep for backward compatible, use `LEGAL_HOLD_STATUS` instead + */ +export type LegalHoldStatus = LEGAL_HOLD_STATUS + +export type PutObjectLegalHoldOptions = { + versionId?: string + status: LEGAL_HOLD_STATUS +} + +export interface UploadedObjectInfo { + etag: string + versionId: string | null +} + +export interface RetentionOptions { + versionId: string + mode?: RETENTION_MODES + retainUntilDate?: IsoDate + governanceBypass?: boolean +} +export type Retention = RetentionOptions | EmptyObject +export type IsoDate = string +export type EmptyObject = Record + +export type ObjectLockInfo = + | { + objectLockEnabled: EnabledOrDisabledStatus + mode: RETENTION_MODES + unit: RETENTION_VALIDITY_UNITS + validity: number + } + | EmptyObject + +export type ObjectLockConfigParam = { + ObjectLockEnabled?: 'Enabled' | undefined + Rule?: + | { + DefaultRetention: + | { + Mode: RETENTION_MODES + Days: number + Years: number + } + | EmptyObject + } + | EmptyObject +} + +export type VersioningEnabled = 'Enabled' +export type VersioningSuspended = 'Suspended' + +export type TaggingOpts = { + versionId: string +} + +export type PutTaggingParams = { + bucketName: string + objectName?: string + tags: Tags + putOpts?: TaggingOpts +} + +export type RemoveTaggingParams = { + bucketName: string + objectName?: string + removeOpts?: TaggingOpts +} + +export type InputSerialization = { + CompressionType?: 'NONE' | 'GZIP' | 'BZIP2' + CSV?: { + AllowQuotedRecordDelimiter?: boolean + Comments?: string + FieldDelimiter?: string + FileHeaderInfo?: 'NONE' | 'IGNORE' | 'USE' + QuoteCharacter?: string + QuoteEscapeCharacter?: string + RecordDelimiter?: string + } + JSON?: { + Type: 'DOCUMENT' | 'LINES' + } + Parquet?: EmptyObject +} + +export type OutputSerialization = { + CSV?: { + FieldDelimiter?: string + QuoteCharacter?: string + QuoteEscapeCharacter?: string + QuoteFields?: string + RecordDelimiter?: string + } + JSON?: { + RecordDelimiter?: string + } +} + +export type SelectProgress = { Enabled: boolean } +export type ScanRange = { Start: number; End: number } +export type SelectOptions = { + expression: string + expressionType?: string + inputSerialization: InputSerialization + outputSerialization: OutputSerialization + requestProgress?: SelectProgress + scanRange?: ScanRange +} +export type Expiration = { + Date?: string + Days: number + DeleteMarker?: boolean + DeleteAll?: boolean +} + +export type RuleFilterAnd = { + Prefix: string + Tags: Tag[] +} +export type RuleFilter = { + And?: RuleFilterAnd + Prefix: string + Tag?: Tag[] +} + +export type NoncurrentVersionExpiration = { + NoncurrentDays: number + NewerNoncurrentVersions?: number +} + +export type NoncurrentVersionTransition = { + StorageClass: string + NoncurrentDays?: number + NewerNoncurrentVersions?: number +} + +export type Transition = { + Date?: string + StorageClass: string + Days: number +} +export type AbortIncompleteMultipartUpload = { + DaysAfterInitiation: number +} +export type LifecycleRule = { + AbortIncompleteMultipartUpload?: AbortIncompleteMultipartUpload + ID: string + Prefix?: string + Status?: string + Expiration?: Expiration + Filter?: RuleFilter + NoncurrentVersionExpiration?: NoncurrentVersionExpiration + NoncurrentVersionTransition?: NoncurrentVersionTransition + Transition?: Transition +} + +export type LifecycleConfig = { + Rule: LifecycleRule[] +} + +export type LifeCycleConfigParam = LifecycleConfig | null | undefined | '' + +export type ApplySSEByDefault = { + KmsMasterKeyID?: string + SSEAlgorithm: string +} + +export type EncryptionRule = { + ApplyServerSideEncryptionByDefault?: ApplySSEByDefault +} + +export type EncryptionConfig = { + Rule: EncryptionRule[] +} + +export type GetObjectRetentionOpts = { + versionId: string +} + +export type ObjectRetentionInfo = { + mode: RETENTION_MODES + retainUntilDate: string +} + +export type RemoveObjectsEntry = { + name: string + versionId?: string +} +export type ObjectName = string + +export type RemoveObjectsParam = ObjectName[] | RemoveObjectsEntry[] + +export type RemoveObjectsRequestEntry = { + Key: string + VersionId?: string +} + +export type RemoveObjectsResponse = + | null + | undefined + | { + Error?: { + Code?: string + Message?: string + Key?: string + VersionId?: string + } + } + +export type CopyObjectResultV1 = { + etag: string + lastModified: string | Date +} +export type CopyObjectResultV2 = { + Bucket?: string + Key?: string + LastModified: string | Date + MetaData?: ResponseHeader + VersionId?: string | null + SourceVersionId?: string | null + Etag?: string + Size?: number +} + +export type CopyObjectResult = CopyObjectResultV1 | CopyObjectResultV2 +export type CopyObjectParams = [CopySourceOptions, CopyDestinationOptions] | [string, string, string, CopyConditions?] + +export type ExcludedPrefix = { + Prefix: string +} +export type BucketVersioningConfiguration = { + Status: VersioningEnabled | VersioningSuspended + /* Below are minio only extensions */ + MFADelete?: string + ExcludedPrefixes?: ExcludedPrefix[] + ExcludeFolders?: boolean +} + +export type UploadPartConfig = { + bucketName: string + objectName: string + uploadID: string + partNumber: number + headers: RequestHeaders + sourceObj: string +} + +export type PreSignRequestParams = { [key: string]: string } + +/** List object api types **/ + +// Common types +export type CommonPrefix = { + Prefix: string +} + +export type Owner = { + ID: string + DisplayName: string +} + +export type Metadata = { + Items: MetadataItem[] +} + +export type ObjectInfo = { + key?: string + name?: string + lastModified?: Date // time string of format "2006-01-02T15:04:05.000Z" + etag?: string + owner?: Owner + storageClass?: string + userMetadata?: Metadata + userTags?: string + prefix?: string + size?: number +} + +export type ListObjectQueryRes = { + isTruncated?: boolean + nextMarker?: string + objects?: ObjectInfo[] + // version listing + keyMarker?: string + versionIdMarker?: string +} + +export type ListObjectQueryOpts = { + Delimiter?: string + MaxKeys?: number + IncludeVersion?: boolean + // version listing + keyMarker?: string + versionIdMarker?: string +} +/** List object api types **/ + +export type ObjectVersionEntry = { + IsLatest?: string + VersionId?: string +} + +export type ObjectRowEntry = ObjectVersionEntry & { + Key: string + LastModified?: Date | undefined + ETag?: string + Size?: string + Owner?: Owner + StorageClass?: string +} + +export type ListObjectV2Res = { + objects: BucketItem[] + isTruncated: boolean + nextContinuationToken: string +} + +export type NotificationConfigEntry = { + Id: string + Event: string[] + Filter: { Name: string; Value: string }[] +} + +export type TopicConfigEntry = NotificationConfigEntry & { Topic: string } +export type QueueConfigEntry = NotificationConfigEntry & { Queue: string } +export type CloudFunctionConfigEntry = NotificationConfigEntry & { CloudFunction: string } + +export type NotificationConfigResult = { + TopicConfiguration: TopicConfigEntry[] + QueueConfiguration: QueueConfigEntry[] + CloudFunctionConfiguration: CloudFunctionConfigEntry[] +} + +export interface ListBucketResultV1 { + Name?: string + Prefix?: string + ContinuationToken?: string + KeyCount?: string + Marker?: string + MaxKeys?: string + Delimiter?: string + IsTruncated?: boolean + Contents?: ObjectRowEntry[] + NextKeyMarker?: string + CommonPrefixes?: CommonPrefix[] + Version?: ObjectRowEntry[] + DeleteMarker?: ObjectRowEntry[] + VersionIdMarker?: string + NextVersionIdMarker?: string + NextMarker?: string +} + +export interface PostPolicyResult { + postURL: string + formData: { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [key: string]: any + } +} diff --git a/node_modules/minio/src/internal/xml-parser.ts b/node_modules/minio/src/internal/xml-parser.ts new file mode 100644 index 0000000..281bdbe --- /dev/null +++ b/node_modules/minio/src/internal/xml-parser.ts @@ -0,0 +1,870 @@ +import type * as http from 'node:http' +import type stream from 'node:stream' + +import crc32 from 'buffer-crc32' +import { XMLParser } from 'fast-xml-parser' + +import * as errors from '../errors.ts' +import { SelectResults } from '../helpers.ts' +import { isObject, parseXml, readableStream, sanitizeETag, sanitizeObjectKey, sanitizeSize, toArray } from './helper.ts' +import { readAsString } from './response.ts' +import type { + BucketItemFromList, + BucketItemWithMetadata, + CloudFunctionConfigEntry, + CommonPrefix, + CopyObjectResultV1, + ListBucketResultV1, + ListObjectV2Res, + NotificationConfigResult, + ObjectInfo, + ObjectLockInfo, + ObjectRowEntry, + QueueConfigEntry, + ReplicationConfig, + Tag, + Tags, + TopicConfigEntry, +} from './type.ts' +import { RETENTION_VALIDITY_UNITS } from './type.ts' + +// parse XML response for bucket region +export function parseBucketRegion(xml: string): string { + // return region information + return parseXml(xml).LocationConstraint +} + +const fxp = new XMLParser() + +const fxpWithoutNumParser = new XMLParser({ + // @ts-ignore + numberParseOptions: { + skipLike: /./, + }, +}) + +// Parse XML and return information as Javascript types +// parse error XML response +export function parseError(xml: string, headerInfo: Record) { + let xmlErr = {} + const xmlObj = fxp.parse(xml) + if (xmlObj.Error) { + xmlErr = xmlObj.Error + } + const e = new errors.S3Error() as unknown as Record + Object.entries(xmlErr).forEach(([key, value]) => { + e[key.toLowerCase()] = value + }) + Object.entries(headerInfo).forEach(([key, value]) => { + e[key] = value + }) + return e +} + +// Generates an Error object depending on http statusCode and XML body +export async function parseResponseError(response: http.IncomingMessage): Promise> { + const statusCode = response.statusCode + let code = '', + message = '' + if (statusCode === 301) { + code = 'MovedPermanently' + message = 'Moved Permanently' + } else if (statusCode === 307) { + code = 'TemporaryRedirect' + message = 'Are you using the correct endpoint URL?' + } else if (statusCode === 403) { + code = 'AccessDenied' + message = 'Valid and authorized credentials required' + } else if (statusCode === 404) { + code = 'NotFound' + message = 'Not Found' + } else if (statusCode === 405) { + code = 'MethodNotAllowed' + message = 'Method Not Allowed' + } else if (statusCode === 501) { + code = 'MethodNotAllowed' + message = 'Method Not Allowed' + } else if (statusCode === 503) { + code = 'SlowDown' + message = 'Please reduce your request rate.' + } else { + const hErrCode = response.headers['x-minio-error-code'] as string + const hErrDesc = response.headers['x-minio-error-desc'] as string + + if (hErrCode && hErrDesc) { + code = hErrCode + message = hErrDesc + } + } + const headerInfo: Record = {} + // A value created by S3 compatible server that uniquely identifies the request. + headerInfo.amzRequestid = response.headers['x-amz-request-id'] as string | undefined + // A special token that helps troubleshoot API replies and issues. + headerInfo.amzId2 = response.headers['x-amz-id-2'] as string | undefined + + // Region where the bucket is located. This header is returned only + // in HEAD bucket and ListObjects response. + headerInfo.amzBucketRegion = response.headers['x-amz-bucket-region'] as string | undefined + + const xmlString = await readAsString(response) + + if (xmlString) { + throw parseError(xmlString, headerInfo) + } + + // Message should be instantiated for each S3Errors. + const e = new errors.S3Error(message, { cause: headerInfo }) + // S3 Error code. + e.code = code + Object.entries(headerInfo).forEach(([key, value]) => { + // @ts-expect-error force set error properties + e[key] = value + }) + + throw e +} + +/** + * parse XML response for list objects v2 with metadata in a bucket + */ +export function parseListObjectsV2WithMetadata(xml: string) { + const result: { + objects: Array + isTruncated: boolean + nextContinuationToken: string + } = { + objects: [], + isTruncated: false, + nextContinuationToken: '', + } + + let xmlobj = parseXml(xml) + if (!xmlobj.ListBucketResult) { + throw new errors.InvalidXMLError('Missing tag: "ListBucketResult"') + } + xmlobj = xmlobj.ListBucketResult + if (xmlobj.IsTruncated) { + result.isTruncated = xmlobj.IsTruncated + } + if (xmlobj.NextContinuationToken) { + result.nextContinuationToken = xmlobj.NextContinuationToken + } + + if (xmlobj.Contents) { + toArray(xmlobj.Contents).forEach((content) => { + const name = sanitizeObjectKey(content.Key) + const lastModified = new Date(content.LastModified) + const etag = sanitizeETag(content.ETag) + const size = content.Size + + let tags: Tags = {} + if (content.UserTags != null) { + toArray(content.UserTags.split('&')).forEach((tag) => { + const [key, value] = tag.split('=') + tags[key] = value + }) + } else { + tags = {} + } + + let metadata + if (content.UserMetadata != null) { + metadata = toArray(content.UserMetadata)[0] + } else { + metadata = null + } + result.objects.push({ name, lastModified, etag, size, metadata, tags }) + }) + } + + if (xmlobj.CommonPrefixes) { + toArray(xmlobj.CommonPrefixes).forEach((commonPrefix) => { + result.objects.push({ prefix: sanitizeObjectKey(toArray(commonPrefix.Prefix)[0]), size: 0 }) + }) + } + return result +} + +export function parseListObjectsV2(xml: string): ListObjectV2Res { + const result: ListObjectV2Res = { + objects: [], + isTruncated: false, + nextContinuationToken: '', + } + + let xmlobj = parseXml(xml) + if (!xmlobj.ListBucketResult) { + throw new errors.InvalidXMLError('Missing tag: "ListBucketResult"') + } + xmlobj = xmlobj.ListBucketResult + if (xmlobj.IsTruncated) { + result.isTruncated = xmlobj.IsTruncated + } + if (xmlobj.NextContinuationToken) { + result.nextContinuationToken = xmlobj.NextContinuationToken + } + if (xmlobj.Contents) { + toArray(xmlobj.Contents).forEach((content) => { + const name = sanitizeObjectKey(toArray(content.Key)[0]) + const lastModified = new Date(content.LastModified) + const etag = sanitizeETag(content.ETag) + const size = content.Size + result.objects.push({ name, lastModified, etag, size }) + }) + } + if (xmlobj.CommonPrefixes) { + toArray(xmlobj.CommonPrefixes).forEach((commonPrefix) => { + result.objects.push({ prefix: sanitizeObjectKey(toArray(commonPrefix.Prefix)[0]), size: 0 }) + }) + } + return result +} + +export function parseBucketNotification(xml: string): NotificationConfigResult { + const result: NotificationConfigResult = { + TopicConfiguration: [], + QueueConfiguration: [], + CloudFunctionConfiguration: [], + } + + const genEvents = (events: unknown): string[] => { + if (!events) { + return [] + } + return toArray(events) as string[] + } + + const genFilterRules = (filters: unknown): { Name: string; Value: string }[] => { + const rules: { Name: string; Value: string }[] = [] + if (!filters) { + return rules + } + const filterArr = toArray(filters) as Record[] + if (filterArr[0]?.S3Key) { + const s3KeyArr = toArray((filterArr[0] as Record).S3Key) as Record[] + if (s3KeyArr[0]?.FilterRule) { + toArray(s3KeyArr[0].FilterRule).forEach((rule: unknown) => { + const r = rule as Record + const Name = toArray(r.Name)[0] as string + const Value = toArray(r.Value)[0] as string + rules.push({ Name, Value }) + }) + } + } + return rules + } + + let xmlobj = parseXml(xml) + xmlobj = xmlobj.NotificationConfiguration + + if (xmlobj.TopicConfiguration) { + toArray(xmlobj.TopicConfiguration).forEach((config: Record) => { + const Id = toArray(config.Id)[0] as string + const Topic = toArray(config.Topic)[0] as string + const Event = genEvents(config.Event) + const Filter = genFilterRules(config.Filter) + result.TopicConfiguration.push({ Id, Topic, Event, Filter } as TopicConfigEntry) + }) + } + if (xmlobj.QueueConfiguration) { + toArray(xmlobj.QueueConfiguration).forEach((config: Record) => { + const Id = toArray(config.Id)[0] as string + const Queue = toArray(config.Queue)[0] as string + const Event = genEvents(config.Event) + const Filter = genFilterRules(config.Filter) + result.QueueConfiguration.push({ Id, Queue, Event, Filter } as QueueConfigEntry) + }) + } + if (xmlobj.CloudFunctionConfiguration) { + toArray(xmlobj.CloudFunctionConfiguration).forEach((config: Record) => { + const Id = toArray(config.Id)[0] as string + const CloudFunction = toArray(config.CloudFunction)[0] as string + const Event = genEvents(config.Event) + const Filter = genFilterRules(config.Filter) + result.CloudFunctionConfiguration.push({ Id, CloudFunction, Event, Filter } as CloudFunctionConfigEntry) + }) + } + + return result +} + +export type UploadedPart = { + part: number + lastModified?: Date + etag: string + size: number +} + +// parse XML response for list parts of an in progress multipart upload +export function parseListParts(xml: string): { + isTruncated: boolean + marker: number + parts: UploadedPart[] +} { + let xmlobj = parseXml(xml) + const result: { + isTruncated: boolean + marker: number + parts: UploadedPart[] + } = { + isTruncated: false, + parts: [], + marker: 0, + } + if (!xmlobj.ListPartsResult) { + throw new errors.InvalidXMLError('Missing tag: "ListPartsResult"') + } + xmlobj = xmlobj.ListPartsResult + if (xmlobj.IsTruncated) { + result.isTruncated = xmlobj.IsTruncated + } + if (xmlobj.NextPartNumberMarker) { + result.marker = toArray(xmlobj.NextPartNumberMarker)[0] || '' + } + if (xmlobj.Part) { + toArray(xmlobj.Part).forEach((p) => { + const part = parseInt(toArray(p.PartNumber)[0], 10) + const lastModified = new Date(p.LastModified) + const etag = p.ETag.replace(/^"/g, '') + .replace(/"$/g, '') + .replace(/^"/g, '') + .replace(/"$/g, '') + .replace(/^"/g, '') + .replace(/"$/g, '') + result.parts.push({ part, lastModified, etag, size: parseInt(p.Size, 10) }) + }) + } + return result +} + +export function parseListBucket(xml: string): BucketItemFromList[] { + let result: BucketItemFromList[] = [] + const listBucketResultParser = new XMLParser({ + parseTagValue: true, // Enable parsing of values + numberParseOptions: { + leadingZeros: false, // Disable number parsing for values with leading zeros + hex: false, // Disable hex number parsing - Invalid bucket name + skipLike: /^[0-9]+$/, // Skip number parsing if the value consists entirely of digits + }, + tagValueProcessor: (tagName, tagValue = '') => { + // Ensure that the Name tag is always treated as a string + if (tagName === 'Name') { + return tagValue.toString() + } + return tagValue + }, + ignoreAttributes: false, // Ensure that all attributes are parsed + }) + + const parsedXmlRes = listBucketResultParser.parse(xml) + + if (!parsedXmlRes.ListAllMyBucketsResult) { + throw new errors.InvalidXMLError('Missing tag: "ListAllMyBucketsResult"') + } + + const { ListAllMyBucketsResult: { Buckets = {} } = {} } = parsedXmlRes + + if (Buckets.Bucket) { + result = toArray(Buckets.Bucket).map((bucket = {}) => { + const { Name: bucketName, CreationDate } = bucket + const creationDate = new Date(CreationDate) + + return { name: bucketName, creationDate } + }) + } + + return result +} + +export function parseInitiateMultipart(xml: string): string { + let xmlobj = parseXml(xml) + + if (!xmlobj.InitiateMultipartUploadResult) { + throw new errors.InvalidXMLError('Missing tag: "InitiateMultipartUploadResult"') + } + xmlobj = xmlobj.InitiateMultipartUploadResult + + if (xmlobj.UploadId) { + return xmlobj.UploadId + } + throw new errors.InvalidXMLError('Missing tag: "UploadId"') +} + +export function parseReplicationConfig(xml: string): ReplicationConfig { + const xmlObj = parseXml(xml) + const { Role, Rule } = xmlObj.ReplicationConfiguration + return { + ReplicationConfiguration: { + role: Role, + rules: toArray(Rule), + }, + } +} + +export function parseObjectLegalHoldConfig(xml: string) { + const xmlObj = parseXml(xml) + return xmlObj.LegalHold +} + +export function parseTagging(xml: string) { + const xmlObj = parseXml(xml) + let result: Tag[] = [] + if (xmlObj.Tagging && xmlObj.Tagging.TagSet && xmlObj.Tagging.TagSet.Tag) { + const tagResult: Tag = xmlObj.Tagging.TagSet.Tag + // if it is a single tag convert into an array so that the return value is always an array. + if (Array.isArray(tagResult)) { + result = [...tagResult] + } else { + result.push(tagResult) + } + } + return result +} + +// parse XML response when a multipart upload is completed +export function parseCompleteMultipart(xml: string) { + const xmlobj = parseXml(xml).CompleteMultipartUploadResult + if (xmlobj.Location) { + const location = toArray(xmlobj.Location)[0] + const bucket = toArray(xmlobj.Bucket)[0] + const key = xmlobj.Key + const etag = xmlobj.ETag.replace(/^"/g, '') + .replace(/"$/g, '') + .replace(/^"/g, '') + .replace(/"$/g, '') + .replace(/^"/g, '') + .replace(/"$/g, '') + + return { location, bucket, key, etag } + } + // Complete Multipart can return XML Error after a 200 OK response + if (xmlobj.Code && xmlobj.Message) { + const errCode = toArray(xmlobj.Code)[0] + const errMessage = toArray(xmlobj.Message)[0] + return { errCode, errMessage } + } +} + +type UploadID = string + +export type ListMultipartResult = { + uploads: { + key: string + uploadId: UploadID + initiator?: { id: string; displayName: string } + owner?: { id: string; displayName: string } + storageClass: unknown + initiated: Date + }[] + prefixes: { + prefix: string + }[] + isTruncated: boolean + nextKeyMarker: string + nextUploadIdMarker: string +} + +// parse XML response for listing in-progress multipart uploads +export function parseListMultipart(xml: string): ListMultipartResult { + const result: ListMultipartResult = { + prefixes: [], + uploads: [], + isTruncated: false, + nextKeyMarker: '', + nextUploadIdMarker: '', + } + + let xmlobj = parseXml(xml) + + if (!xmlobj.ListMultipartUploadsResult) { + throw new errors.InvalidXMLError('Missing tag: "ListMultipartUploadsResult"') + } + xmlobj = xmlobj.ListMultipartUploadsResult + if (xmlobj.IsTruncated) { + result.isTruncated = xmlobj.IsTruncated + } + if (xmlobj.NextKeyMarker) { + result.nextKeyMarker = xmlobj.NextKeyMarker + } + if (xmlobj.NextUploadIdMarker) { + result.nextUploadIdMarker = xmlobj.nextUploadIdMarker || '' + } + + if (xmlobj.CommonPrefixes) { + toArray(xmlobj.CommonPrefixes).forEach((prefix) => { + // @ts-expect-error index check + result.prefixes.push({ prefix: sanitizeObjectKey(toArray(prefix.Prefix)[0]) }) + }) + } + + if (xmlobj.Upload) { + toArray(xmlobj.Upload).forEach((upload) => { + const uploadItem: ListMultipartResult['uploads'][number] = { + key: upload.Key, + uploadId: upload.UploadId, + storageClass: upload.StorageClass, + initiated: new Date(upload.Initiated), + } + if (upload.Initiator) { + uploadItem.initiator = { id: upload.Initiator.ID, displayName: upload.Initiator.DisplayName } + } + if (upload.Owner) { + uploadItem.owner = { id: upload.Owner.ID, displayName: upload.Owner.DisplayName } + } + result.uploads.push(uploadItem) + }) + } + return result +} + +export function parseObjectLockConfig(xml: string): ObjectLockInfo { + const xmlObj = parseXml(xml) + let lockConfigResult = {} as ObjectLockInfo + if (xmlObj.ObjectLockConfiguration) { + lockConfigResult = { + objectLockEnabled: xmlObj.ObjectLockConfiguration.ObjectLockEnabled, + } as ObjectLockInfo + let retentionResp + if ( + xmlObj.ObjectLockConfiguration && + xmlObj.ObjectLockConfiguration.Rule && + xmlObj.ObjectLockConfiguration.Rule.DefaultRetention + ) { + retentionResp = xmlObj.ObjectLockConfiguration.Rule.DefaultRetention || {} + lockConfigResult.mode = retentionResp.Mode + } + if (retentionResp) { + const isUnitYears = retentionResp.Years + if (isUnitYears) { + lockConfigResult.validity = isUnitYears + lockConfigResult.unit = RETENTION_VALIDITY_UNITS.YEARS + } else { + lockConfigResult.validity = retentionResp.Days + lockConfigResult.unit = RETENTION_VALIDITY_UNITS.DAYS + } + } + } + + return lockConfigResult +} + +export function parseBucketVersioningConfig(xml: string) { + const xmlObj = parseXml(xml) + return xmlObj.VersioningConfiguration +} + +// Used only in selectObjectContent API. +// extractHeaderType extracts the first half of the header message, the header type. +function extractHeaderType(stream: stream.Readable): string | undefined { + const headerNameLen = Buffer.from(stream.read(1)).readUInt8() + const headerNameWithSeparator = Buffer.from(stream.read(headerNameLen)).toString() + const splitBySeparator = (headerNameWithSeparator || '').split(':') + return splitBySeparator.length >= 1 ? splitBySeparator[1] : '' +} + +function extractHeaderValue(stream: stream.Readable) { + const bodyLen = Buffer.from(stream.read(2)).readUInt16BE() + return Buffer.from(stream.read(bodyLen)).toString() +} + +export function parseSelectObjectContentResponse(res: Buffer) { + const selectResults = new SelectResults({}) // will be returned + + const responseStream = readableStream(res) // convert byte array to a readable responseStream + // @ts-ignore + while (responseStream._readableState.length) { + // Top level responseStream read tracker. + let msgCrcAccumulator // accumulate from start of the message till the message crc start. + + const totalByteLengthBuffer = Buffer.from(responseStream.read(4)) + msgCrcAccumulator = crc32(totalByteLengthBuffer) + + const headerBytesBuffer = Buffer.from(responseStream.read(4)) + msgCrcAccumulator = crc32(headerBytesBuffer, msgCrcAccumulator) + + const calculatedPreludeCrc = msgCrcAccumulator.readInt32BE() // use it to check if any CRC mismatch in header itself. + + const preludeCrcBuffer = Buffer.from(responseStream.read(4)) // read 4 bytes i.e 4+4 =8 + 4 = 12 ( prelude + prelude crc) + msgCrcAccumulator = crc32(preludeCrcBuffer, msgCrcAccumulator) + + const totalMsgLength = totalByteLengthBuffer.readInt32BE() + const headerLength = headerBytesBuffer.readInt32BE() + const preludeCrcByteValue = preludeCrcBuffer.readInt32BE() + + if (preludeCrcByteValue !== calculatedPreludeCrc) { + // Handle Header CRC mismatch Error + throw new Error( + `Header Checksum Mismatch, Prelude CRC of ${preludeCrcByteValue} does not equal expected CRC of ${calculatedPreludeCrc}`, + ) + } + + const headers: Record = {} + if (headerLength > 0) { + const headerBytes = Buffer.from(responseStream.read(headerLength)) + msgCrcAccumulator = crc32(headerBytes, msgCrcAccumulator) + const headerReaderStream = readableStream(headerBytes) + // @ts-ignore + while (headerReaderStream._readableState.length) { + const headerTypeName = extractHeaderType(headerReaderStream) + headerReaderStream.read(1) // just read and ignore it. + if (headerTypeName) { + headers[headerTypeName] = extractHeaderValue(headerReaderStream) + } + } + } + + let payloadStream + const payLoadLength = totalMsgLength - headerLength - 16 + if (payLoadLength > 0) { + const payLoadBuffer = Buffer.from(responseStream.read(payLoadLength)) + msgCrcAccumulator = crc32(payLoadBuffer, msgCrcAccumulator) + // read the checksum early and detect any mismatch so we can avoid unnecessary further processing. + const messageCrcByteValue = Buffer.from(responseStream.read(4)).readInt32BE() + const calculatedCrc = msgCrcAccumulator.readInt32BE() + // Handle message CRC Error + if (messageCrcByteValue !== calculatedCrc) { + throw new Error( + `Message Checksum Mismatch, Message CRC of ${messageCrcByteValue} does not equal expected CRC of ${calculatedCrc}`, + ) + } + payloadStream = readableStream(payLoadBuffer) + } + const messageType = headers['message-type'] + + switch (messageType) { + case 'error': { + const errorMessage = headers['error-code'] + ':"' + headers['error-message'] + '"' + throw new Error(errorMessage) + } + case 'event': { + const contentType = headers['content-type'] + const eventType = headers['event-type'] + + switch (eventType) { + case 'End': { + selectResults.setResponse(res) + return selectResults + } + + case 'Records': { + const readData = payloadStream?.read(payLoadLength) + selectResults.setRecords(readData) + break + } + + case 'Progress': + { + switch (contentType) { + case 'text/xml': { + const progressData = payloadStream?.read(payLoadLength) + selectResults.setProgress(progressData.toString()) + break + } + default: { + const errorMessage = `Unexpected content-type ${contentType} sent for event-type Progress` + throw new Error(errorMessage) + } + } + } + break + case 'Stats': + { + switch (contentType) { + case 'text/xml': { + const statsData = payloadStream?.read(payLoadLength) + selectResults.setStats(statsData.toString()) + break + } + default: { + const errorMessage = `Unexpected content-type ${contentType} sent for event-type Stats` + throw new Error(errorMessage) + } + } + } + break + default: { + // Continuation message: Not sure if it is supported. did not find a reference or any message in response. + // It does not have a payload. + const warningMessage = `Un implemented event detected ${messageType}.` + // eslint-disable-next-line no-console + console.warn(warningMessage) + } + } + } + } + } +} + +export function parseLifecycleConfig(xml: string) { + const xmlObj = parseXml(xml) + return xmlObj.LifecycleConfiguration +} + +export function parseBucketEncryptionConfig(xml: string) { + return parseXml(xml) +} + +export function parseObjectRetentionConfig(xml: string) { + const xmlObj = parseXml(xml) + const retentionConfig = xmlObj.Retention + return { + mode: retentionConfig.Mode, + retainUntilDate: retentionConfig.RetainUntilDate, + } +} + +export function removeObjectsParser(xml: string) { + const xmlObj = parseXml(xml) + if (xmlObj.DeleteResult && xmlObj.DeleteResult.Error) { + // return errors as array always. as the response is object in case of single object passed in removeObjects + return toArray(xmlObj.DeleteResult.Error) + } + return [] +} + +// parse XML response for copy object +export function parseCopyObject(xml: string): CopyObjectResultV1 { + const result: CopyObjectResultV1 = { + etag: '', + lastModified: '', + } + + let xmlobj = parseXml(xml) + if (!xmlobj.CopyObjectResult) { + throw new errors.InvalidXMLError('Missing tag: "CopyObjectResult"') + } + xmlobj = xmlobj.CopyObjectResult + if (xmlobj.ETag) { + result.etag = xmlobj.ETag.replace(/^"/g, '') + .replace(/"$/g, '') + .replace(/^"/g, '') + .replace(/"$/g, '') + .replace(/^"/g, '') + .replace(/"$/g, '') + } + if (xmlobj.LastModified) { + result.lastModified = new Date(xmlobj.LastModified) + } + + return result +} + +const formatObjInfo = (content: ObjectRowEntry, opts: { IsDeleteMarker?: boolean } = {}) => { + const { Key, LastModified, ETag, Size, VersionId, IsLatest } = content + + if (!isObject(opts)) { + opts = {} + } + + const name = sanitizeObjectKey(toArray(Key)[0] || '') + const lastModified = LastModified ? new Date(toArray(LastModified)[0] || '') : undefined + const etag = sanitizeETag(toArray(ETag)[0] || '') + const size = sanitizeSize(Size || '') + + return { + name, + lastModified, + etag, + size, + versionId: VersionId, + isLatest: IsLatest, + isDeleteMarker: opts.IsDeleteMarker ? opts.IsDeleteMarker : false, + } +} + +// parse XML response for list objects in a bucket +export function parseListObjects(xml: string) { + const result: { + objects: ObjectInfo[] + isTruncated?: boolean + nextMarker?: string + versionIdMarker?: string + keyMarker?: string + } = { + objects: [], + isTruncated: false, + nextMarker: undefined, + versionIdMarker: undefined, + keyMarker: undefined, + } + let isTruncated = false + let nextMarker + const xmlobj = fxpWithoutNumParser.parse(xml) + + const parseCommonPrefixesEntity = (commonPrefixEntry: CommonPrefix[]) => { + if (commonPrefixEntry) { + toArray(commonPrefixEntry).forEach((commonPrefix) => { + result.objects.push({ prefix: sanitizeObjectKey(toArray(commonPrefix.Prefix)[0] || ''), size: 0 }) + }) + } + } + + const listBucketResult: ListBucketResultV1 = xmlobj.ListBucketResult + const listVersionsResult: ListBucketResultV1 = xmlobj.ListVersionsResult + + if (listBucketResult) { + if (listBucketResult.IsTruncated) { + isTruncated = listBucketResult.IsTruncated + } + if (listBucketResult.Contents) { + toArray(listBucketResult.Contents).forEach((content) => { + const name = sanitizeObjectKey(toArray(content.Key)[0] || '') + const lastModified = new Date(toArray(content.LastModified)[0] || '') + const etag = sanitizeETag(toArray(content.ETag)[0] || '') + const size = sanitizeSize(content.Size || '') + result.objects.push({ name, lastModified, etag, size }) + }) + } + + if (listBucketResult.Marker) { + nextMarker = listBucketResult.Marker + } + if (listBucketResult.NextMarker) { + nextMarker = listBucketResult.NextMarker + } else if (isTruncated && result.objects.length > 0) { + nextMarker = result.objects[result.objects.length - 1]?.name + } + if (listBucketResult.CommonPrefixes) { + parseCommonPrefixesEntity(listBucketResult.CommonPrefixes) + } + } + + if (listVersionsResult) { + if (listVersionsResult.IsTruncated) { + isTruncated = listVersionsResult.IsTruncated + } + + if (listVersionsResult.Version) { + toArray(listVersionsResult.Version).forEach((content) => { + result.objects.push(formatObjInfo(content)) + }) + } + if (listVersionsResult.DeleteMarker) { + toArray(listVersionsResult.DeleteMarker).forEach((content) => { + result.objects.push(formatObjInfo(content, { IsDeleteMarker: true })) + }) + } + + if (listVersionsResult.NextKeyMarker) { + result.keyMarker = listVersionsResult.NextKeyMarker + } + if (listVersionsResult.NextVersionIdMarker) { + result.versionIdMarker = listVersionsResult.NextVersionIdMarker + } + if (listVersionsResult.CommonPrefixes) { + parseCommonPrefixesEntity(listVersionsResult.CommonPrefixes) + } + } + + result.isTruncated = isTruncated + if (isTruncated) { + result.nextMarker = nextMarker + } + return result +} + +export function uploadPartParser(xml: string) { + const xmlObj = parseXml(xml) + const respEl = xmlObj.CopyPartResult + return respEl +} diff --git a/node_modules/minio/src/minio.ts b/node_modules/minio/src/minio.ts new file mode 100644 index 0000000..02bb731 --- /dev/null +++ b/node_modules/minio/src/minio.ts @@ -0,0 +1,155 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { LEGAL_HOLD_STATUS, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from './helpers.ts' +import { callbackify } from './internal/callbackify.ts' +import { TypedClient } from './internal/client.ts' +import { CopyConditions } from './internal/copy-conditions.ts' +import { PostPolicy } from './internal/post-policy.ts' + +export * from './errors.ts' +export * from './helpers.ts' +export * from './notification.ts' +export { CopyConditions, PostPolicy } +export { IamAwsProvider } from './IamAwsProvider.ts' +export type { MakeBucketOpt } from './internal/client.ts' +export type { ClientOptions, NoResultCallback, RemoveOptions } from './internal/client.ts' +export type { Region } from './internal/s3-endpoints.ts' +export type { + BucketItem, + BucketItemCopy, + BucketItemFromList, + BucketItemStat, + BucketItemWithMetadata, + BucketStream, + EmptyObject, + ExistingObjectReplication, + GetObjectLegalHoldOptions, + IncompleteUploadedBucketItem, + InputSerialization, + IsoDate, + ItemBucketMetadata, + ItemBucketMetadataList, + LegalHoldStatus, + LifecycleConfig, + LifecycleRule, + MetadataItem, + ObjectLockInfo, + OutputSerialization, + PostPolicyResult, + PutObjectLegalHoldOptions, + ReplicaModifications, + ReplicationConfig, + ReplicationConfigOpts, + ReplicationRule, + ReplicationRuleAnd, + ReplicationRuleDestination, + ReplicationRuleFilter, + ReplicationRuleStatus, + Retention, + RetentionOptions, + ScanRange, + SelectOptions, + SelectProgress, + SourceSelectionCriteria, + Tag, +} from './internal/type.ts' + +/** + * @deprecated keep for backward compatible, use `RETENTION_MODES` instead + */ +export type Mode = RETENTION_MODES + +/** + * @deprecated keep for backward compatible + */ +export type LockUnit = RETENTION_VALIDITY_UNITS + +export type VersioningConfig = Record +export type TagList = Record + +export interface LockConfig { + mode: RETENTION_MODES + unit: RETENTION_VALIDITY_UNITS + validity: number +} + +export interface LegalHoldOptions { + versionId: string + status: LEGAL_HOLD_STATUS +} + +export interface SourceObjectStats { + size: number + metaData: string + lastModicied: Date + versionId: string + etag: string +} + +export class Client extends TypedClient {} + +// refactored API use promise internally +Client.prototype.makeBucket = callbackify(Client.prototype.makeBucket) +Client.prototype.bucketExists = callbackify(Client.prototype.bucketExists) +Client.prototype.removeBucket = callbackify(Client.prototype.removeBucket) +Client.prototype.listBuckets = callbackify(Client.prototype.listBuckets) + +Client.prototype.getObject = callbackify(Client.prototype.getObject) +Client.prototype.fGetObject = callbackify(Client.prototype.fGetObject) +Client.prototype.getPartialObject = callbackify(Client.prototype.getPartialObject) +Client.prototype.statObject = callbackify(Client.prototype.statObject) +Client.prototype.putObjectRetention = callbackify(Client.prototype.putObjectRetention) +Client.prototype.putObject = callbackify(Client.prototype.putObject) +Client.prototype.fPutObject = callbackify(Client.prototype.fPutObject) +Client.prototype.removeObject = callbackify(Client.prototype.removeObject) + +Client.prototype.removeBucketReplication = callbackify(Client.prototype.removeBucketReplication) +Client.prototype.setBucketReplication = callbackify(Client.prototype.setBucketReplication) +Client.prototype.getBucketReplication = callbackify(Client.prototype.getBucketReplication) +Client.prototype.getObjectLegalHold = callbackify(Client.prototype.getObjectLegalHold) +Client.prototype.setObjectLegalHold = callbackify(Client.prototype.setObjectLegalHold) +Client.prototype.setObjectLockConfig = callbackify(Client.prototype.setObjectLockConfig) +Client.prototype.getObjectLockConfig = callbackify(Client.prototype.getObjectLockConfig) +Client.prototype.getBucketPolicy = callbackify(Client.prototype.getBucketPolicy) +Client.prototype.setBucketPolicy = callbackify(Client.prototype.setBucketPolicy) +Client.prototype.getBucketTagging = callbackify(Client.prototype.getBucketTagging) +Client.prototype.getObjectTagging = callbackify(Client.prototype.getObjectTagging) +Client.prototype.setBucketTagging = callbackify(Client.prototype.setBucketTagging) +Client.prototype.removeBucketTagging = callbackify(Client.prototype.removeBucketTagging) +Client.prototype.setObjectTagging = callbackify(Client.prototype.setObjectTagging) +Client.prototype.removeObjectTagging = callbackify(Client.prototype.removeObjectTagging) +Client.prototype.getBucketVersioning = callbackify(Client.prototype.getBucketVersioning) +Client.prototype.setBucketVersioning = callbackify(Client.prototype.setBucketVersioning) +Client.prototype.selectObjectContent = callbackify(Client.prototype.selectObjectContent) +Client.prototype.setBucketLifecycle = callbackify(Client.prototype.setBucketLifecycle) +Client.prototype.getBucketLifecycle = callbackify(Client.prototype.getBucketLifecycle) +Client.prototype.removeBucketLifecycle = callbackify(Client.prototype.removeBucketLifecycle) +Client.prototype.setBucketEncryption = callbackify(Client.prototype.setBucketEncryption) +Client.prototype.getBucketEncryption = callbackify(Client.prototype.getBucketEncryption) +Client.prototype.removeBucketEncryption = callbackify(Client.prototype.removeBucketEncryption) +Client.prototype.getObjectRetention = callbackify(Client.prototype.getObjectRetention) +Client.prototype.removeObjects = callbackify(Client.prototype.removeObjects) +Client.prototype.removeIncompleteUpload = callbackify(Client.prototype.removeIncompleteUpload) +Client.prototype.copyObject = callbackify(Client.prototype.copyObject) +Client.prototype.composeObject = callbackify(Client.prototype.composeObject) +Client.prototype.presignedUrl = callbackify(Client.prototype.presignedUrl) +Client.prototype.presignedGetObject = callbackify(Client.prototype.presignedGetObject) +Client.prototype.presignedPutObject = callbackify(Client.prototype.presignedPutObject) +Client.prototype.presignedPostPolicy = callbackify(Client.prototype.presignedPostPolicy) +Client.prototype.setBucketNotification = callbackify(Client.prototype.setBucketNotification) +Client.prototype.getBucketNotification = callbackify(Client.prototype.getBucketNotification) +Client.prototype.removeAllBucketNotification = callbackify(Client.prototype.removeAllBucketNotification) diff --git a/node_modules/minio/src/notification.ts b/node_modules/minio/src/notification.ts new file mode 100644 index 0000000..64c2411 --- /dev/null +++ b/node_modules/minio/src/notification.ts @@ -0,0 +1,254 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2016 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { EventEmitter } from 'eventemitter3' +import jsonLineParser from 'stream-json/jsonl/Parser.js' + +import { DEFAULT_REGION } from './helpers.ts' +import type { TypedClient } from './internal/client.ts' +import { pipesetup, uriEscape } from './internal/helper.ts' + +// TODO: type this + +type Event = unknown + +// Base class for three supported configs. +export class TargetConfig { + private Filter?: { S3Key: { FilterRule: { Name: string; Value: string }[] } } + private Event?: Event[] + private Id: unknown + + setId(id: unknown) { + this.Id = id + } + + addEvent(newevent: Event) { + if (!this.Event) { + this.Event = [] + } + this.Event.push(newevent) + } + + addFilterSuffix(suffix: string) { + if (!this.Filter) { + this.Filter = { S3Key: { FilterRule: [] } } + } + this.Filter.S3Key.FilterRule.push({ Name: 'suffix', Value: suffix }) + } + + addFilterPrefix(prefix: string) { + if (!this.Filter) { + this.Filter = { S3Key: { FilterRule: [] } } + } + this.Filter.S3Key.FilterRule.push({ Name: 'prefix', Value: prefix }) + } +} + +// 1. Topic (simple notification service) +export class TopicConfig extends TargetConfig { + private Topic: string + + constructor(arn: string) { + super() + this.Topic = arn + } +} + +// 2. Queue (simple queue service) +export class QueueConfig extends TargetConfig { + private Queue: string + + constructor(arn: string) { + super() + this.Queue = arn + } +} + +// 3. CloudFront (lambda function) +export class CloudFunctionConfig extends TargetConfig { + private CloudFunction: string + + constructor(arn: string) { + super() + this.CloudFunction = arn + } +} + +// Notification config - array of target configs. +// Target configs can be +// 1. Topic (simple notification service) +// 2. Queue (simple queue service) +// 3. CloudFront (lambda function) +export class NotificationConfig { + private TopicConfiguration?: TargetConfig[] + private CloudFunctionConfiguration?: TargetConfig[] + private QueueConfiguration?: TargetConfig[] + + add(target: TargetConfig) { + let instance: TargetConfig[] | undefined + if (target instanceof TopicConfig) { + instance = this.TopicConfiguration ??= [] + } + if (target instanceof QueueConfig) { + instance = this.QueueConfiguration ??= [] + } + if (target instanceof CloudFunctionConfig) { + instance = this.CloudFunctionConfiguration ??= [] + } + if (instance) { + instance.push(target) + } + } +} + +export const buildARN = (partition: string, service: string, region: string, accountId: string, resource: string) => { + return 'arn:' + partition + ':' + service + ':' + region + ':' + accountId + ':' + resource +} +export const ObjectCreatedAll = 's3:ObjectCreated:*' +export const ObjectCreatedPut = 's3:ObjectCreated:Put' +export const ObjectCreatedPost = 's3:ObjectCreated:Post' +export const ObjectCreatedCopy = 's3:ObjectCreated:Copy' +export const ObjectCreatedCompleteMultipartUpload = 's3:ObjectCreated:CompleteMultipartUpload' +export const ObjectRemovedAll = 's3:ObjectRemoved:*' +export const ObjectRemovedDelete = 's3:ObjectRemoved:Delete' +export const ObjectRemovedDeleteMarkerCreated = 's3:ObjectRemoved:DeleteMarkerCreated' +export const ObjectReducedRedundancyLostObject = 's3:ReducedRedundancyLostObject' +export type NotificationEvent = + | 's3:ObjectCreated:*' + | 's3:ObjectCreated:Put' + | 's3:ObjectCreated:Post' + | 's3:ObjectCreated:Copy' + | 's3:ObjectCreated:CompleteMultipartUpload' + | 's3:ObjectRemoved:*' + | 's3:ObjectRemoved:Delete' + | 's3:ObjectRemoved:DeleteMarkerCreated' + | 's3:ReducedRedundancyLostObject' + | 's3:TestEvent' + | 's3:ObjectRestore:Post' + | 's3:ObjectRestore:Completed' + | 's3:Replication:OperationFailedReplication' + | 's3:Replication:OperationMissedThreshold' + | 's3:Replication:OperationReplicatedAfterThreshold' + | 's3:Replication:OperationNotTracked' + | string // put string at least so auto-complete could work + +// TODO: type this +export type NotificationRecord = unknown +// Poll for notifications, used in #listenBucketNotification. +// Listening constitutes repeatedly requesting s3 whether or not any +// changes have occurred. +export class NotificationPoller extends EventEmitter<{ + notification: (event: NotificationRecord) => void + error: (error: unknown) => void +}> { + private client: TypedClient + private bucketName: string + private prefix: string + private suffix: string + private events: NotificationEvent[] + private ending: boolean + + constructor(client: TypedClient, bucketName: string, prefix: string, suffix: string, events: NotificationEvent[]) { + super() + + this.client = client + this.bucketName = bucketName + this.prefix = prefix + this.suffix = suffix + this.events = events + + this.ending = false + } + + // Starts the polling. + start() { + this.ending = false + + process.nextTick(() => { + this.checkForChanges() + }) + } + + // Stops the polling. + stop() { + this.ending = true + } + + checkForChanges() { + // Don't continue if we're looping again but are cancelled. + if (this.ending) { + return + } + + const method = 'GET' + const queries = [] + if (this.prefix) { + const prefix = uriEscape(this.prefix) + queries.push(`prefix=${prefix}`) + } + if (this.suffix) { + const suffix = uriEscape(this.suffix) + queries.push(`suffix=${suffix}`) + } + if (this.events) { + this.events.forEach((s3event) => queries.push('events=' + uriEscape(s3event))) + } + queries.sort() + + let query = '' + if (queries.length > 0) { + query = `${queries.join('&')}` + } + const region = this.client.region || DEFAULT_REGION + + this.client.makeRequestAsync({ method, bucketName: this.bucketName, query }, '', [200], region).then( + (response) => { + const asm = jsonLineParser.make() + + pipesetup(response, asm) + .on('data', (data) => { + // Data is flushed periodically (every 5 seconds), so we should + // handle it after flushing from the JSON parser. + let records = data.value.Records + // If null (= no records), change to an empty array. + if (!records) { + records = [] + } + + // Iterate over the notifications and emit them individually. + records.forEach((record: NotificationRecord) => { + this.emit('notification', record) + }) + + // If we're done, stop. + if (this.ending) { + response?.destroy() + } + }) + .on('error', (e) => this.emit('error', e)) + .on('end', () => { + // Do it again, if we haven't cancelled yet. + process.nextTick(() => { + this.checkForChanges() + }) + }) + }, + (e) => { + return this.emit('error', e) + }, + ) + } +} diff --git a/node_modules/minio/src/signing.ts b/node_modules/minio/src/signing.ts new file mode 100644 index 0000000..7a5480c --- /dev/null +++ b/node_modules/minio/src/signing.ts @@ -0,0 +1,325 @@ +/* + * MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2016 MinIO, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as crypto from 'node:crypto' + +import * as errors from './errors.ts' +import { PRESIGN_EXPIRY_DAYS_MAX } from './helpers.ts' +import { getScope, isNumber, isObject, isString, makeDateLong, makeDateShort, uriEscape } from './internal/helper.ts' +import type { ICanonicalRequest, IRequest, RequestHeaders } from './internal/type.ts' + +const signV4Algorithm = 'AWS4-HMAC-SHA256' + +// getCanonicalRequest generate a canonical request of style. +// +// canonicalRequest = +// \n +// \n +// \n +// \n +// \n +// +// +function getCanonicalRequest( + method: string, + path: string, + headers: RequestHeaders, + signedHeaders: string[], + hashedPayload: string, +): ICanonicalRequest { + if (!isString(method)) { + throw new TypeError('method should be of type "string"') + } + if (!isString(path)) { + throw new TypeError('path should be of type "string"') + } + if (!isObject(headers)) { + throw new TypeError('headers should be of type "object"') + } + if (!Array.isArray(signedHeaders)) { + throw new TypeError('signedHeaders should be of type "array"') + } + if (!isString(hashedPayload)) { + throw new TypeError('hashedPayload should be of type "string"') + } + + const headersArray = signedHeaders.reduce((acc, i) => { + // Trim spaces from the value (required by V4 spec) + const val = `${headers[i]}`.replace(/ +/g, ' ') + acc.push(`${i.toLowerCase()}:${val}`) + return acc + }, [] as string[]) + + const requestResource = path.split('?')[0] + let requestQuery = path.split('?')[1] + if (!requestQuery) { + requestQuery = '' + } + + if (requestQuery) { + requestQuery = requestQuery + .split('&') + .sort() + .map((element) => (!element.includes('=') ? element + '=' : element)) + .join('&') + } + + return [ + method.toUpperCase(), + requestResource, + requestQuery, + headersArray.join('\n') + '\n', + signedHeaders.join(';').toLowerCase(), + hashedPayload, + ].join('\n') +} + +// generate a credential string +function getCredential(accessKey: string, region: string, requestDate?: Date, serviceName = 's3') { + if (!isString(accessKey)) { + throw new TypeError('accessKey should be of type "string"') + } + if (!isString(region)) { + throw new TypeError('region should be of type "string"') + } + if (!isObject(requestDate)) { + throw new TypeError('requestDate should be of type "object"') + } + return `${accessKey}/${getScope(region, requestDate, serviceName)}` +} + +// Returns signed headers array - alphabetically sorted +function getSignedHeaders(headers: RequestHeaders): string[] { + if (!isObject(headers)) { + throw new TypeError('request should be of type "object"') + } + // Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258 + // + // User-Agent: + // + // This is ignored from signing because signing this causes problems with generating pre-signed URLs + // (that are executed by other agents) or when customers pass requests through proxies, which may + // modify the user-agent. + // + // Content-Length: + // + // This is ignored from signing because generating a pre-signed URL should not provide a content-length + // constraint, specifically when vending a S3 pre-signed PUT URL. The corollary to this is that when + // sending regular requests (non-pre-signed), the signature contains a checksum of the body, which + // implicitly validates the payload length (since changing the number of bytes would change the checksum) + // and therefore this header is not valuable in the signature. + // + // Content-Type: + // + // Signing this header causes quite a number of problems in browser environments, where browsers + // like to modify and normalize the content-type header in different ways. There is more information + // on this in https://github.com/aws/aws-sdk-js/issues/244. Avoiding this field simplifies logic + // and reduces the possibility of future bugs + // + // Authorization: + // + // Is skipped for obvious reasons + + const ignoredHeaders = ['authorization', 'content-length', 'content-type', 'user-agent'] + return Object.keys(headers) + .filter((header) => !ignoredHeaders.includes(header)) + .sort() +} + +// returns the key used for calculating signature +function getSigningKey(date: Date, region: string, secretKey: string, serviceName = 's3') { + if (!isObject(date)) { + throw new TypeError('date should be of type "object"') + } + if (!isString(region)) { + throw new TypeError('region should be of type "string"') + } + if (!isString(secretKey)) { + throw new TypeError('secretKey should be of type "string"') + } + const dateLine = makeDateShort(date) + const hmac1 = crypto + .createHmac('sha256', 'AWS4' + secretKey) + .update(dateLine) + .digest(), + hmac2 = crypto.createHmac('sha256', hmac1).update(region).digest(), + hmac3 = crypto.createHmac('sha256', hmac2).update(serviceName).digest() + return crypto.createHmac('sha256', hmac3).update('aws4_request').digest() +} + +// returns the string that needs to be signed +function getStringToSign(canonicalRequest: ICanonicalRequest, requestDate: Date, region: string, serviceName = 's3') { + if (!isString(canonicalRequest)) { + throw new TypeError('canonicalRequest should be of type "string"') + } + if (!isObject(requestDate)) { + throw new TypeError('requestDate should be of type "object"') + } + if (!isString(region)) { + throw new TypeError('region should be of type "string"') + } + const hash = crypto.createHash('sha256').update(canonicalRequest).digest('hex') + const scope = getScope(region, requestDate, serviceName) + const stringToSign = [signV4Algorithm, makeDateLong(requestDate), scope, hash] + + return stringToSign.join('\n') +} + +// calculate the signature of the POST policy +export function postPresignSignatureV4(region: string, date: Date, secretKey: string, policyBase64: string): string { + if (!isString(region)) { + throw new TypeError('region should be of type "string"') + } + if (!isObject(date)) { + throw new TypeError('date should be of type "object"') + } + if (!isString(secretKey)) { + throw new TypeError('secretKey should be of type "string"') + } + if (!isString(policyBase64)) { + throw new TypeError('policyBase64 should be of type "string"') + } + const signingKey = getSigningKey(date, region, secretKey) + return crypto.createHmac('sha256', signingKey).update(policyBase64).digest('hex').toLowerCase() +} + +// Returns the authorization header +export function signV4( + request: IRequest, + accessKey: string, + secretKey: string, + region: string, + requestDate: Date, + sha256sum: string, + serviceName = 's3', +) { + if (!isObject(request)) { + throw new TypeError('request should be of type "object"') + } + if (!isString(accessKey)) { + throw new TypeError('accessKey should be of type "string"') + } + if (!isString(secretKey)) { + throw new TypeError('secretKey should be of type "string"') + } + if (!isString(region)) { + throw new TypeError('region should be of type "string"') + } + + if (!accessKey) { + throw new errors.AccessKeyRequiredError('accessKey is required for signing') + } + if (!secretKey) { + throw new errors.SecretKeyRequiredError('secretKey is required for signing') + } + + const signedHeaders = getSignedHeaders(request.headers) + const canonicalRequest = getCanonicalRequest(request.method, request.path, request.headers, signedHeaders, sha256sum) + const serviceIdentifier = serviceName || 's3' + const stringToSign = getStringToSign(canonicalRequest, requestDate, region, serviceIdentifier) + const signingKey = getSigningKey(requestDate, region, secretKey, serviceIdentifier) + const credential = getCredential(accessKey, region, requestDate, serviceIdentifier) + const signature = crypto.createHmac('sha256', signingKey).update(stringToSign).digest('hex').toLowerCase() + + return `${signV4Algorithm} Credential=${credential}, SignedHeaders=${signedHeaders + .join(';') + .toLowerCase()}, Signature=${signature}` +} + +export function signV4ByServiceName( + request: IRequest, + accessKey: string, + secretKey: string, + region: string, + requestDate: Date, + contentSha256: string, + serviceName = 's3', +): string { + return signV4(request, accessKey, secretKey, region, requestDate, contentSha256, serviceName) +} + +// returns a presigned URL string +export function presignSignatureV4( + request: IRequest, + accessKey: string, + secretKey: string, + sessionToken: string | undefined, + region: string, + requestDate: Date, + expires: number | undefined, +) { + if (!isObject(request)) { + throw new TypeError('request should be of type "object"') + } + if (!isString(accessKey)) { + throw new TypeError('accessKey should be of type "string"') + } + if (!isString(secretKey)) { + throw new TypeError('secretKey should be of type "string"') + } + if (!isString(region)) { + throw new TypeError('region should be of type "string"') + } + + if (!accessKey) { + throw new errors.AccessKeyRequiredError('accessKey is required for presigning') + } + if (!secretKey) { + throw new errors.SecretKeyRequiredError('secretKey is required for presigning') + } + + if (expires && !isNumber(expires)) { + throw new TypeError('expires should be of type "number"') + } + if (expires && expires < 1) { + throw new errors.ExpiresParamError('expires param cannot be less than 1 seconds') + } + if (expires && expires > PRESIGN_EXPIRY_DAYS_MAX) { + throw new errors.ExpiresParamError('expires param cannot be greater than 7 days') + } + + const iso8601Date = makeDateLong(requestDate) + const signedHeaders = getSignedHeaders(request.headers) + const credential = getCredential(accessKey, region, requestDate) + const hashedPayload = 'UNSIGNED-PAYLOAD' + + const requestQuery: string[] = [] + requestQuery.push(`X-Amz-Algorithm=${signV4Algorithm}`) + requestQuery.push(`X-Amz-Credential=${uriEscape(credential)}`) + requestQuery.push(`X-Amz-Date=${iso8601Date}`) + requestQuery.push(`X-Amz-Expires=${expires}`) + requestQuery.push(`X-Amz-SignedHeaders=${uriEscape(signedHeaders.join(';').toLowerCase())}`) + if (sessionToken) { + requestQuery.push(`X-Amz-Security-Token=${uriEscape(sessionToken)}`) + } + + const resource = request.path.split('?')[0] + let query = request.path.split('?')[1] + if (query) { + query = query + '&' + requestQuery.join('&') + } else { + query = requestQuery.join('&') + } + + const path = resource + '?' + query + + const canonicalRequest = getCanonicalRequest(request.method, path, request.headers, signedHeaders, hashedPayload) + + const stringToSign = getStringToSign(canonicalRequest, requestDate, region) + const signingKey = getSigningKey(requestDate, region, secretKey) + const signature = crypto.createHmac('sha256', signingKey).update(stringToSign).digest('hex').toLowerCase() + return request.protocol + '//' + request.headers.host + path + `&X-Amz-Signature=${signature}` +} diff --git a/node_modules/path-expression-matcher/LICENSE b/node_modules/path-expression-matcher/LICENSE new file mode 100644 index 0000000..c13f991 --- /dev/null +++ b/node_modules/path-expression-matcher/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/path-expression-matcher/README.md b/node_modules/path-expression-matcher/README.md new file mode 100644 index 0000000..3f655ba --- /dev/null +++ b/node_modules/path-expression-matcher/README.md @@ -0,0 +1,872 @@ +# path-expression-matcher + +Efficient path tracking and pattern matching for XML, JSON, YAML or any other parsers. + +## 🎯 Purpose + +`path-expression-matcher` provides three core classes for tracking and matching paths: + +- **`Expression`**: Parses and stores pattern expressions (e.g., `"root.users.user[id]"`) +- **`Matcher`**: Tracks current path during parsing and matches against expressions +- **`MatcherView`**: A lightweight read-only view of a `Matcher`, safe to pass to callbacks + +Compatible with [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) and similar tools. + +## 📦 Installation + +```bash +npm install path-expression-matcher +``` + +## 🚀 Quick Start + +```javascript +import { Expression, Matcher } from 'path-expression-matcher'; + +// Create expression (parse once, reuse many times) +const expr = new Expression("root.users.user"); + +// Create matcher (tracks current path) +const matcher = new Matcher(); + +matcher.push("root"); +matcher.push("users"); +matcher.push("user", { id: "123" }); + +// Match current path against expression +if (matcher.matches(expr)) { + console.log("Match found!"); + console.log("Current path:", matcher.toString()); // "root.users.user" +} + +// Namespace support +const nsExpr = new Expression("soap::Envelope.soap::Body..ns::UserId"); +matcher.push("Envelope", null, "soap"); +matcher.push("Body", null, "soap"); +matcher.push("UserId", null, "ns"); +console.log(matcher.toString()); // "soap:Envelope.soap:Body.ns:UserId" +``` + +## 📖 Pattern Syntax + +### Basic Paths + +```javascript +"root.users.user" // Exact path match +"*.users.user" // Wildcard: any parent +"root.*.user" // Wildcard: any middle +"root.users.*" // Wildcard: any child +``` + +### Deep Wildcard + +```javascript +"..user" // user anywhere in tree +"root..user" // user anywhere under root +"..users..user" // users somewhere, then user below it +``` + +### Attribute Matching + +```javascript +"user[id]" // user with "id" attribute +"user[type=admin]" // user with type="admin" (current node only) +"root[lang]..user" // user under root that has "lang" attribute +``` + +### Position Selectors + +```javascript +"user:first" // First user (counter=0) +"user:nth(2)" // Third user (counter=2, zero-based) +"user:odd" // Odd-numbered users (counter=1,3,5...) +"user:even" // Even-numbered users (counter=0,2,4...) +"root.users.user:first" // First user under users +``` + +**Note:** Position selectors use the **counter** (occurrence count of the tag name), not the position (child index). For example, in ``, the second `` has position=2 but counter=1. + +### Namespaces + +```javascript +"ns::user" // user with namespace "ns" +"soap::Envelope" // Envelope with namespace "soap" +"ns::user[id]" // user with namespace "ns" and "id" attribute +"ns::user:first" // First user with namespace "ns" +"*::user" // user with any namespace +"..ns::item" // item with namespace "ns" anywhere in tree +"soap::Envelope.soap::Body" // Nested namespaced elements +"ns::first" // Tag named "first" with namespace "ns" (NO ambiguity!) +``` + +**Namespace syntax:** +- Use **double colon (::)** for namespace: `ns::tag` +- Use **single colon (:)** for position: `tag:first` +- Combined: `ns::tag:first` (namespace + tag + position) + +**Namespace matching rules:** +- Pattern `ns::user` matches only nodes with namespace "ns" and tag "user" +- Pattern `user` (no namespace) matches nodes with tag "user" regardless of namespace +- Pattern `*::user` matches tag "user" with any namespace (wildcard namespace) +- Namespaces are tracked separately for counter/position (e.g., `ns1::item` and `ns2::item` have independent counters) + +### Wildcard Differences + +**Single wildcard (`*`)** - Matches exactly ONE level: +- `"*.fix1"` matches `root.fix1` (2 levels) ✅ +- `"*.fix1"` does NOT match `root.another.fix1` (3 levels) ❌ +- Path depth MUST equal pattern depth + +**Deep wildcard (`..`)** - Matches ZERO or MORE levels: +- `"..fix1"` matches `root.fix1` ✅ +- `"..fix1"` matches `root.another.fix1` ✅ +- `"..fix1"` matches `a.b.c.d.fix1` ✅ +- Works at any depth + +### Combined Patterns + +```javascript +"..user[id]:first" // First user with id, anywhere +"root..user[type=admin]" // Admin user under root +"ns::user[id]:first" // First namespaced user with id +"soap::Envelope..ns::UserId" // UserId with namespace ns under SOAP envelope +``` + +## 🔧 API Reference + +### Expression + +#### Constructor + +```javascript +new Expression(pattern, options = {}, data) +``` + +**Parameters:** +- `pattern` (string): Pattern to parse +- `options.separator` (string): Path separator (default: `'.'`) + +**Example:** +```javascript +const expr1 = new Expression("root.users.user"); +const expr2 = new Expression("root/users/user", { separator: '/' }); +const expr3 = new Expression("root/users/user", { separator: '/' }, { extra: "data"}); +console.log(expr3.data) // { extra: "data" } +``` + +#### Methods + +- `hasDeepWildcard()` → boolean +- `hasAttributeCondition()` → boolean +- `hasPositionSelector()` → boolean +- `toString()` → string + +### Matcher + +#### Constructor + +```javascript +new Matcher(options) +``` + +**Parameters:** +- `options.separator` (string): Default path separator (default: `'.'`) + +#### Path Tracking Methods + +##### `push(tagName, attrValues, namespace)` + +Add a tag to the current path. Position and counter are automatically calculated. + +**Parameters:** +- `tagName` (string): Tag name +- `attrValues` (object, optional): Attribute key-value pairs (current node only) +- `namespace` (string, optional): Namespace for the tag + +**Example:** +```javascript +matcher.push("user", { id: "123", type: "admin" }); +matcher.push("item"); // No attributes +matcher.push("Envelope", null, "soap"); // With namespace +matcher.push("Body", { version: "1.1" }, "soap"); // With both +``` + +**Position vs Counter:** +- **Position**: The child index in the parent (0, 1, 2, 3...) +- **Counter**: How many times this tag name appeared at this level (0, 1, 2...) + +Example: +```xml + + + + + +``` + +##### `pop()` + +Remove the last tag from the path. + +```javascript +matcher.pop(); +``` + +##### `updateCurrent(attrValues)` + +Update current node's attributes (useful when attributes are parsed after push). + +```javascript +matcher.push("user"); // Don't know values yet +// ... parse attributes ... +matcher.updateCurrent({ id: "123" }); +``` + +##### `reset()` + +Clear the entire path. + +```javascript +matcher.reset(); +``` + +#### Query Methods + +##### `matches(expression)` + +Check if current path matches an Expression. + +```javascript +const expr = new Expression("root.users.user"); +if (matcher.matches(expr)) { + // Current path matches +} +``` + +#### `matchesAny(exprSet)` → `boolean` + +Please check `ExpressionSet` class for more details. + +```javascript +const matcher = new Matcher(); +const exprSet = new ExpressionSet(); +exprSet.add(new Expression("root.users.user")); +exprSet.add(new Expression("root.config.*")); +exprSet.seal(); + +if (matcher.matchesAny(exprSet)) { + // Current path matches any expression in the set +} +``` + +##### `getCurrentTag()` + +Get current tag name. + +```javascript +const tag = matcher.getCurrentTag(); // "user" +``` + +##### `getCurrentNamespace()` + +Get current namespace. + +```javascript +const ns = matcher.getCurrentNamespace(); // "soap" or undefined +``` + +##### `getAttrValue(attrName)` + +Get attribute value of current node. + +```javascript +const id = matcher.getAttrValue("id"); // "123" +``` + +##### `hasAttr(attrName)` + +Check if current node has an attribute. + +```javascript +if (matcher.hasAttr("id")) { + // Current node has "id" attribute +} +``` + +##### `getPosition()` + +Get sibling position of current node (child index in parent). + +```javascript +const position = matcher.getPosition(); // 0, 1, 2, ... +``` + +##### `getCounter()` + +Get repeat counter of current node (occurrence count of this tag name). + +```javascript +const counter = matcher.getCounter(); // 0, 1, 2, ... +``` + +##### `getIndex()` (deprecated) + +Alias for `getPosition()`. Use `getPosition()` or `getCounter()` instead for clarity. + +```javascript +const index = matcher.getIndex(); // Same as getPosition() +``` + +##### `getDepth()` + +Get current path depth. + +```javascript +const depth = matcher.getDepth(); // 3 for "root.users.user" +``` + +##### `toString(separator?, includeNamespace?)` + +Get path as string. + +**Parameters:** +- `separator` (string, optional): Path separator (uses default if not provided) +- `includeNamespace` (boolean, optional): Whether to include namespaces (default: true) + +```javascript +const path = matcher.toString(); // "root.ns:user.item" +const path2 = matcher.toString('/'); // "root/ns:user/item" +const path3 = matcher.toString('.', false); // "root.user.item" (no namespaces) +``` + +##### `toArray()` + +Get path as array. + +```javascript +const arr = matcher.toArray(); // ["root", "users", "user"] +``` + +#### State Management + +##### `snapshot()` + +Create a snapshot of current state. + +```javascript +const snapshot = matcher.snapshot(); +``` + +##### `restore(snapshot)` + +Restore from a snapshot. + +```javascript +matcher.restore(snapshot); +``` + +#### Read-Only Access + +##### `readOnly()` + +Returns a **`MatcherView`** — a lightweight, live read-only view of the matcher. All query and inspection methods work normally and always reflect the current state of the underlying matcher. Mutation methods (`push`, `pop`, `reset`, `updateCurrent`, `restore`) simply don't exist on `MatcherView`, so misuse is caught at **compile time** by TypeScript rather than at runtime. + +The **same instance** is returned on every call — no allocation occurs per invocation. This is the recommended way to share the matcher with callbacks, plugins, or any external code that only needs to inspect the current path. + +```javascript +const view = matcher.readOnly(); +// Same reference every time — safe to cache +view === matcher.readOnly(); // true +``` + +**What works on the view:** + +```javascript +view.matches(expr) // ✓ pattern matching +view.getCurrentTag() // ✓ current tag name +view.getCurrentNamespace() // ✓ current namespace +view.getAttrValue("id") // ✓ attribute value +view.hasAttr("id") // ✓ attribute presence check +view.getPosition() // ✓ sibling position +view.getCounter() // ✓ occurrence counter +view.getDepth() // ✓ path depth +view.toString() // ✓ path as string +view.toArray() // ✓ path as array +``` + +**What doesn't exist (compile-time error in TypeScript):** + +```javascript +view.push("child", {}) // ✗ Property 'push' does not exist on type 'MatcherView' +view.pop() // ✗ Property 'pop' does not exist on type 'MatcherView' +view.reset() // ✗ Property 'reset' does not exist on type 'MatcherView' +view.updateCurrent({}) // ✗ Property 'updateCurrent' does not exist on type 'MatcherView' +view.restore(snapshot) // ✗ Property 'restore' does not exist on type 'MatcherView' +``` + +**The view is live** — it always reflects the current state of the underlying matcher. + +```javascript +const matcher = new Matcher(); +const view = matcher.readOnly(); + +matcher.push("root"); +view.getDepth(); // 1 — immediately reflects the push +matcher.push("users"); +view.getDepth(); // 2 — still live +``` + +## 💡 Usage Examples + +### Example 1: XML Parser with stopNodes + +```javascript +import { XMLParser } from 'fast-xml-parser'; +import { Expression, Matcher } from 'path-expression-matcher'; + +class MyParser { + constructor() { + this.matcher = new Matcher(); + + // Pre-compile stop node patterns + this.stopNodeExpressions = [ + new Expression("html.body.script"), + new Expression("html.body.style"), + new Expression("..svg"), + ]; + } + + parseTag(tagName, attrs) { + this.matcher.push(tagName, attrs); + + // Check if this is a stop node + for (const expr of this.stopNodeExpressions) { + if (this.matcher.matches(expr)) { + // Don't parse children, read as raw text + return this.readRawContent(); + } + } + + // Continue normal parsing + this.parseChildren(); + + this.matcher.pop(); + } +} +``` + +### Example 2: Conditional Processing + +```javascript +const matcher = new Matcher(); +const userExpr = new Expression("..user[type=admin]"); +const firstItemExpr = new Expression("..item:first"); + +function processTag(tagName, value, attrs) { + matcher.push(tagName, attrs); + + if (matcher.matches(userExpr)) { + value = enhanceAdminUser(value); + } + + if (matcher.matches(firstItemExpr)) { + value = markAsFirst(value); + } + + matcher.pop(); + return value; +} +``` + +### Example 3: Path-based Filtering + +```javascript +const patterns = [ + new Expression("data.users.user"), + new Expression("data.posts.post"), + new Expression("..comment[approved=true]"), +]; + +function shouldInclude(matcher) { + return patterns.some(expr => matcher.matches(expr)); +} +``` + +### Example 4: Custom Separator + +```javascript +const matcher = new Matcher({ separator: '/' }); +const expr = new Expression("root/config/database", { separator: '/' }); + +matcher.push("root"); +matcher.push("config"); +matcher.push("database"); + +console.log(matcher.toString()); // "root/config/database" +console.log(matcher.matches(expr)); // true +``` + +### Example 5: Attribute Checking + +```javascript +const matcher = new Matcher(); +matcher.push("root"); +matcher.push("user", { id: "123", type: "admin", status: "active" }); + +// Check attribute existence (current node only) +console.log(matcher.hasAttr("id")); // true +console.log(matcher.hasAttr("email")); // false + +// Get attribute value (current node only) +console.log(matcher.getAttrValue("type")); // "admin" + +// Match by attribute +const expr1 = new Expression("user[id]"); +console.log(matcher.matches(expr1)); // true + +const expr2 = new Expression("user[type=admin]"); +console.log(matcher.matches(expr2)); // true +``` + +### Example 6: Position vs Counter + +```javascript +const matcher = new Matcher(); +matcher.push("root"); + +// Mixed tags at same level +matcher.push("item"); // position=0, counter=0 (first item) +matcher.pop(); + +matcher.push("div"); // position=1, counter=0 (first div) +matcher.pop(); + +matcher.push("item"); // position=2, counter=1 (second item) + +console.log(matcher.getPosition()); // 2 (third child overall) +console.log(matcher.getCounter()); // 1 (second "item" specifically) + +// :first uses counter, not position +const expr = new Expression("root.item:first"); +console.log(matcher.matches(expr)); // false (counter=1, not 0) +``` + +### Example 8: Passing a Read-Only View to External Consumers + +When passing the matcher into callbacks, plugins, or other code you don't control, use `readOnly()` to get a `MatcherView` — it can inspect but never mutate parser state. + +```javascript +import { Expression, Matcher } from 'path-expression-matcher'; + +const matcher = new Matcher(); + +const adminExpr = new Expression("..user[type=admin]"); + +function parseTag(tagName, attrs, onTag) { + matcher.push(tagName, attrs); + + // Pass MatcherView — consumer can inspect but not mutate + onTag(matcher.readOnly()); + + matcher.pop(); +} + +// Safe consumer — can only read +function myPlugin(view) { + if (view.matches(adminExpr)) { + console.log("Admin at path:", view.toString()); + console.log("Depth:", view.getDepth()); + console.log("ID:", view.getAttrValue("id")); + } +} + +// view.push(...) or view.reset() don't exist on MatcherView — +// TypeScript catches misuse at compile time. +parseTag("user", { id: "1", type: "admin" }, myPlugin); +``` + +```javascript +const matcher = new Matcher(); +const soapExpr = new Expression("soap::Envelope.soap::Body..ns::UserId"); + +// Parse SOAP document +matcher.push("Envelope", { xmlns: "..." }, "soap"); +matcher.push("Body", null, "soap"); +matcher.push("GetUserRequest", null, "ns"); +matcher.push("UserId", null, "ns"); + +// Match namespaced pattern +if (matcher.matches(soapExpr)) { + console.log("Found UserId in SOAP body"); + console.log(matcher.toString()); // "soap:Envelope.soap:Body.ns:GetUserRequest.ns:UserId" +} + +// Namespace-specific counters +matcher.reset(); +matcher.push("root"); +matcher.push("item", null, "ns1"); // ns1::item counter=0 +matcher.pop(); +matcher.push("item", null, "ns2"); // ns2::item counter=0 (different namespace) +matcher.pop(); +matcher.push("item", null, "ns1"); // ns1::item counter=1 + +const firstNs1Item = new Expression("root.ns1::item:first"); +console.log(matcher.matches(firstNs1Item)); // false (counter=1) + +const secondNs1Item = new Expression("root.ns1::item:nth(1)"); +console.log(matcher.matches(secondNs1Item)); // true + +// NO AMBIGUITY: Tags named after position keywords +matcher.reset(); +matcher.push("root"); +matcher.push("first", null, "ns"); // Tag named "first" with namespace + +const expr = new Expression("root.ns::first"); +console.log(matcher.matches(expr)); // true - matches namespace "ns", tag "first" +``` + +## 🏗️ Architecture + +### Data Storage Strategy + +**Ancestor nodes:** Store only tag name, position, and counter (minimal memory) +**Current node:** Store tag name, position, counter, and attribute values + +This design minimizes memory usage: +- No attribute names stored (derived from values object when needed) +- Attribute values only for current node, not ancestors +- Attribute checking for ancestors is not supported (acceptable trade-off) +- For 1M nodes with 3 attributes each, saves ~50MB vs storing attribute names + +### Matching Strategy + +Matching is performed **bottom-to-top** (from current node toward root): +1. Start at current node +2. Match segments from pattern end to start +3. Attribute checking only works for current node (ancestors have no attribute data) +4. Position selectors use **counter** (occurrence count), not position (child index) + +### Performance + +- **Expression parsing:** One-time cost when Expression is created +- **Expression analysis:** Cached (hasDeepWildcard, hasAttributeCondition, hasPositionSelector) +- **Path tracking:** O(1) for push/pop operations +- **Pattern matching:** O(n*m) where n = path depth, m = pattern segments +- **Memory per ancestor node:** ~40-60 bytes (tag, position, counter only) +- **Memory per current node:** ~80-120 bytes (adds attribute values) + +## 🎓 Design Patterns + +### Pre-compile Patterns (Recommended) + +```javascript +// ✅ GOOD: Parse once, reuse many times +const expr = new Expression("..user[id]"); + +for (let i = 0; i < 1000; i++) { + if (matcher.matches(expr)) { + // ... + } +} +``` + +```javascript +// ❌ BAD: Parse on every iteration +for (let i = 0; i < 1000; i++) { + if (matcher.matches(new Expression("..user[id]"))) { + // ... + } +} +``` + +### Batch Pattern Checking with ExpressionSet (Recommended) + +For checking multiple patterns on every tag, use `ExpressionSet` instead of a manual loop. +It pre-indexes expressions at build time so each call to `matchesAny()` does an O(1) bucket +lookup rather than a full O(N) scan: + +```javascript +import { Expression, ExpressionSet, Matcher } from 'path-expression-matcher'; + +// Build once at config/startup time +const stopNodes = new ExpressionSet(); +stopNodes + .add(new Expression('root.users.user')) + .add(new Expression('root.config.*')) + .add(new Expression('..script')) + .seal(); // prevent accidental mutation during parsing + +// Per-tag — hot path +if (stopNodes.matchesAny(matcher)) { + // handle stop node +} +``` + +This replaces the manual loop pattern: + +```javascript +// ❌ Before — O(N) per tag +function isStopNode(expressions, matcher) { + for (let i = 0; i < expressions.length; i++) { + if (matcher.matches(expressions[i])) return true; + } + return false; +} + +// ✅ After — O(1) lookup per tag +const stopNodes = new ExpressionSet(); +stopNodes.addAll(expressions); +stopNodes.matchesAny(matcher); +//or matcher.matchesAny(stopNodes) +``` + +--- + +## 📦 ExpressionSet API + +`ExpressionSet` is an indexed collection of `Expression` objects designed for efficient +bulk matching. Build it once from your config, then call `matchesAny()` on every tag. + +### Constructor + +```javascript +const set = new ExpressionSet(); +``` + +### `add(expression)` → `this` + +Add a single `Expression`. Duplicate patterns (same pattern string) are silently ignored. +Returns `this` for chaining. Throws `TypeError` if the set is sealed. + +```javascript +set.add(new Expression('root.users.user')); +set.add(new Expression('..script')); +``` + +### `addAll(expressions)` → `this` + +Add an array of `Expression` objects at once. Returns `this` for chaining. + +```javascript +set.addAll(config.stopNodes.map(p => new Expression(p))); +``` + +### `has(expression)` → `boolean` + +Check whether an expression with the same pattern is already present. + +```javascript +set.has(new Expression('root.users.user')); // true / false +``` + +### `seal()` → `this` + +Prevent further additions. Any subsequent call to `add()` or `addAll()` throws a `TypeError`. +Useful to guard against accidental mutation once parsing has started. + +```javascript +const stopNodes = new ExpressionSet(); +stopNodes.addAll(patterns).seal(); + +stopNodes.add(new Expression('root.extra')); // ❌ TypeError: ExpressionSet is sealed +``` + +### `size` → `number` + +Number of distinct expressions in the set. + +```javascript +set.size; // 3 +``` + +### `isSealed` → `boolean` + +Whether `seal()` has been called. + +### `matchesAny(matcher)` → `boolean` + +Returns `true` if the matcher's current path matches **any** expression in the set. +Accepts both a `Matcher` instance and a `MatcherView`. + +```javascript +if (stopNodes.matchesAny(matcher)) { /* ... */ } +if (stopNodes.matchesAny(matcher.readOnly())) { /* ... */ } // also works +``` + +**How indexing works:** expressions are bucketed at `add()` time, not at match time. + +| Expression type | Bucket | Lookup cost | +|---|---|---| +| Fixed path, concrete tag (`root.users.user`) | `depth:tag` map | O(1) | +| Fixed path, wildcard tag (`root.config.*`) | `depth` map | O(1) | +| Deep wildcard (`..script`) | flat list | O(D) — always scanned | + +In practice, deep-wildcard expressions are rare in configs, so the list stays small. + +### `findMatch(matcher)` → `Expression` + +Returns the Expression instance that matched the current path. Accepts both a `Matcher` instance and a `MatcherView`. + +```javascript +const node = stopNodes.findMatch(matcher); +``` + + +### Example 7: ExpressionSet in a real parser loop + +```javascript +import { XMLParser } from 'fast-xml-parser'; +import { Expression, ExpressionSet, Matcher } from 'path-expression-matcher'; + +// Config-time setup +const stopNodes = new ExpressionSet(); +stopNodes + .addAll(['script', 'style'].map(t => new Expression(`..${t}`))) + .seal(); + +const matcher = new Matcher(); + +const parser = new XMLParser({ + onOpenTag(tagName, attrs) { + matcher.push(tagName, attrs); + if (stopNodes.matchesAny(matcher)) { + // treat as stop node + } + }, + onCloseTag() { + matcher.pop(); + }, +}); +``` + + + +## 🔗 Integration with fast-xml-parser + +**Basic integration:** + +```javascript +import { XMLParser } from 'fast-xml-parser'; +import { Expression, Matcher } from 'path-expression-matcher'; + +const parser = new XMLParser({ + // Custom options using path-expression-matcher + stopNodes: ["script", "style"].map(tag => new Expression(`..${tag}`)), + + tagValueProcessor: (tagName, value, jPath, hasAttrs, isLeaf, matcher) => { + // matcher is available in callbacks + if (matcher.matches(new Expression("..user[type=admin]"))) { + return enhanceValue(value); + } + return value; + } +}); +``` + +## 📄 License + +MIT + +## 🤝 Contributing + +Issues and PRs welcome! This package is designed to be used by XML/JSON parsers like fast-xml-parser. But can be used with any formar parser. \ No newline at end of file diff --git a/node_modules/path-expression-matcher/lib/pem.cjs b/node_modules/path-expression-matcher/lib/pem.cjs new file mode 100644 index 0000000..4be499f --- /dev/null +++ b/node_modules/path-expression-matcher/lib/pem.cjs @@ -0,0 +1 @@ +(()=>{"use strict";var t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{Expression:()=>s,ExpressionSet:()=>n,Matcher:()=>h,default:()=>r});class s{constructor(t,e={},s){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=s,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let s=0,i="";for(;s0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const s=e[e.length-1];return void 0!==s.values&&t in s.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class h{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new i(this)}push(t,e=null,s=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const i=this.path.length;this.siblingStacks[i]||(this.siblingStacks[i]=new Map);const h=this.siblingStacks[i],n=s?`${s}:${t}`:t,r=h.get(n)||0;let a=0;for(const t of h.values())a+=t;h.set(n,r+1);const p={tag:t,position:a,counter:r};null!=s&&(p.namespace=s),null!=e&&(p.values=e),this.path.push(p)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const s=t||this.separator;if(s===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(s);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(s)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e=0&&e>=0;){const i=t[s];if("deep-wildcard"===i.type){if(s--,s<0)return!0;const i=t[s];let h=!1;for(let t=e;t>=0;t--)if(this._matchSegment(i,this.path[t],t===this.path.length-1)){e=t-1,s--,h=!0;break}if(!h)return!1}else{if(!this._matchSegment(i,this.path[e],e===this.path.length-1))return!1;e--,s--}}return s<0}_matchSegment(t,e,s){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!s)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!s)return!1;const i=e.counter??0;if("first"===t.position&&0!==i)return!1;if("odd"===t.position&&i%2!=1)return!1;if("even"===t.position&&i%2!=0)return!1;if("nth"===t.position&&i!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}class n{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._patterns=new Set,this._sealed=!1}add(t){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(t.pattern))return this;if(this._patterns.add(t.pattern),t.hasDeepWildcard())return this._deepWildcards.push(t),this;const e=t.length,s=t.segments[t.segments.length-1],i=s?.tag;if(i&&"*"!==i){const s=`${e}:${i}`;this._byDepthAndTag.has(s)||this._byDepthAndTag.set(s,[]),this._byDepthAndTag.get(s).push(t)}else this._wildcardByDepth.has(e)||this._wildcardByDepth.set(e,[]),this._wildcardByDepth.get(e).push(t);return this}addAll(t){for(const e of t)this.add(e);return this}has(t){return this._patterns.has(t.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(t){return null!==this.findMatch(t)}findMatch(t){const e=t.getDepth(),s=`${e}:${t.getCurrentTag()}`,i=this._byDepthAndTag.get(s);if(i)for(let e=0;e; +} + +/** + * Snapshot of matcher state + */ +declare interface MatcherSnapshot { + /** + * Copy of the path stack + */ + path: PathNode[]; + + /** + * Copy of sibling tracking maps + */ + siblingStacks: Map[]; +} + +/** + * ReadOnlyMatcher - A safe, read-only view over a {@link Matcher} instance. + * + * Returned by {@link Matcher.readOnly}. Exposes all query and inspection + * methods but **throws a `TypeError`** if any state-mutating method is called + * (`push`, `pop`, `reset`, `updateCurrent`, `restore`). Direct property + * writes are also blocked. + * + * Pass this to consumers that only need to inspect or match the current path + * so they cannot accidentally corrupt the parser state. + * + * @example + * ```javascript + * const matcher = new Matcher(); + * matcher.push("root", {}); + * matcher.push("users", {}); + * matcher.push("user", { id: "123" }); + * + * const ro: ReadOnlyMatcher = matcher.readOnly(); + * + * ro.matches(expr); // ✓ works + * ro.getCurrentTag(); // ✓ "user" + * ro.getDepth(); // ✓ 3 + * ro.push("child", {}); // ✗ TypeError: Cannot call 'push' on a read-only Matcher + * ro.reset(); // ✗ TypeError: Cannot call 'reset' on a read-only Matcher + * ``` + */ +declare interface ReadOnlyMatcher { + /** + * Default path separator (read-only) + */ + readonly separator: string; + + /** + * Current path stack (each node is a frozen copy) + */ + readonly path: ReadonlyArray>; + + // ── Query methods ─────────────────────────────────────────────────────────── + + /** + * Get current tag name + * @returns Current tag name or undefined if path is empty + */ + getCurrentTag(): string | undefined; + + /** + * Get current namespace + * @returns Current namespace or undefined if not present or path is empty + */ + getCurrentNamespace(): string | undefined; + + /** + * Get current node's attribute value + * @param attrName - Attribute name + * @returns Attribute value or undefined + */ + getAttrValue(attrName: string): any; + + /** + * Check if current node has an attribute + * @param attrName - Attribute name + */ + hasAttr(attrName: string): boolean; + + /** + * Get current node's sibling position (child index in parent) + * @returns Position index or -1 if path is empty + */ + getPosition(): number; + + /** + * Get current node's repeat counter (occurrence count of this tag name) + * @returns Counter value or -1 if path is empty + */ + getCounter(): number; + + /** + * Get current node's sibling index (alias for getPosition for backward compatibility) + * @returns Index or -1 if path is empty + * @deprecated Use getPosition() or getCounter() instead + */ + getIndex(): number; + + /** + * Get current path depth + * @returns Number of nodes in the path + */ + getDepth(): number; + + /** + * Get path as string + * @param separator - Optional separator (uses default if not provided) + * @param includeNamespace - Whether to include namespace in output + * @returns Path string (e.g., "root.users.user" or "ns:root.ns:users.user") + */ + toString(separator?: string, includeNamespace?: boolean): string; + + /** + * Get path as array of tag names + * @returns Array of tag names + */ + toArray(): string[]; + + /** + * Match current path against an Expression + * @param expression - The expression to match against + * @returns True if current path matches the expression + */ + matches(expression: Expression): boolean; + + /** + * Test whether the matcher's current path matches **any** expression in the set. + * + * @param exprSet - A `ExpressionSet` instance + * @returns `true` if at least one expression matches the current path + */ + matchesAny(exprSet: ExpressionSet): boolean; + /** + * Create a snapshot of current state + * @returns State snapshot that can be restored later + */ + snapshot(): MatcherSnapshot; + + // ── Blocked mutating methods ──────────────────────────────────────────────── + // These are present in the type so callers get a compile-time error with a + // helpful message instead of a silent "property does not exist" error. + + /** + * @throws {TypeError} Always – mutation is not allowed on a read-only view. + */ + push(tagName: string, attrValues?: Record | null, namespace?: string | null): never; + + /** + * @throws {TypeError} Always – mutation is not allowed on a read-only view. + */ + pop(): never; + + /** + * @throws {TypeError} Always – mutation is not allowed on a read-only view. + */ + updateCurrent(attrValues: Record): never; + + /** + * @throws {TypeError} Always – mutation is not allowed on a read-only view. + */ + reset(): never; + + /** + * @throws {TypeError} Always – mutation is not allowed on a read-only view. + */ + restore(snapshot: MatcherSnapshot): never; +} + +/** + * Matcher - Tracks current path in XML/JSON tree and matches against Expressions + * + * The matcher maintains a stack of nodes representing the current path from root to + * current tag. It only stores attribute values for the current (top) node to minimize + * memory usage. + * + * @example + * ```javascript + * const { Matcher } = require('path-expression-matcher'); + * const matcher = new Matcher(); + * matcher.push("root", {}); + * matcher.push("users", {}); + * matcher.push("user", { id: "123", type: "admin" }); + * + * const expr = new Expression("root.users.user"); + * matcher.matches(expr); // true + * + * matcher.pop(); + * matcher.matches(expr); // false + * ``` + */ +declare class Matcher { + /** + * Default path separator + */ + readonly separator: string; + + /** + * Current path stack + */ + readonly path: PathNode[]; + + /** + * Create a new Matcher + * @param options - Configuration options + */ + constructor(options?: MatcherOptions); + + /** + * Push a new tag onto the path + * @param tagName - Name of the tag + * @param attrValues - Attribute key-value pairs for current node (optional) + * @param namespace - Namespace for the tag (optional) + * + * @example + * ```javascript + * matcher.push("user", { id: "123", type: "admin" }); + * matcher.push("user", { id: "456" }, "ns"); + * matcher.push("container", null); + * ``` + */ + push(tagName: string, attrValues?: Record | null, namespace?: string | null): void; + + /** + * Pop the last tag from the path + * @returns The popped node or undefined if path is empty + */ + pop(): PathNode | undefined; + + /** + * Update current node's attribute values + * Useful when attributes are parsed after push + * @param attrValues - Attribute values + */ + updateCurrent(attrValues: Record): void; + + /** + * Get current tag name + * @returns Current tag name or undefined if path is empty + */ + getCurrentTag(): string | undefined; + + /** + * Get current namespace + * @returns Current namespace or undefined if not present or path is empty + */ + getCurrentNamespace(): string | undefined; + + /** + * Get current node's attribute value + * @param attrName - Attribute name + * @returns Attribute value or undefined + */ + getAttrValue(attrName: string): any; + + /** + * Check if current node has an attribute + * @param attrName - Attribute name + */ + hasAttr(attrName: string): boolean; + + /** + * Get current node's sibling position (child index in parent) + * @returns Position index or -1 if path is empty + */ + getPosition(): number; + + /** + * Get current node's repeat counter (occurrence count of this tag name) + * @returns Counter value or -1 if path is empty + */ + getCounter(): number; + + /** + * Get current node's sibling index (alias for getPosition for backward compatibility) + * @returns Index or -1 if path is empty + * @deprecated Use getPosition() or getCounter() instead + */ + getIndex(): number; + + /** + * Get current path depth + * @returns Number of nodes in the path + */ + getDepth(): number; + + /** + * Get path as string + * @param separator - Optional separator (uses default if not provided) + * @param includeNamespace - Whether to include namespace in output + * @returns Path string (e.g., "root.users.user" or "ns:root.ns:users.user") + */ + toString(separator?: string, includeNamespace?: boolean): string; + + /** + * Get path as array of tag names + * @returns Array of tag names + */ + toArray(): string[]; + + /** + * Reset the path to empty + */ + reset(): void; + + /** + * Match current path against an Expression + * @param expression - The expression to match against + * @returns True if current path matches the expression + * + * @example + * ```javascript + * const expr = new Expression("root.users.user[id]"); + * const matcher = new Matcher(); + * + * matcher.push("root"); + * matcher.push("users"); + * matcher.push("user", { id: "123" }); + * + * matcher.matches(expr); // true + * ``` + */ + matches(expression: Expression): boolean; + + + /** + * Test whether the matcher's current path matches **any** expression in the set. + * + * Uses the pre-built index to evaluate only the relevant bucket(s): + * 1. Exact depth + tag — O(1) lookup + * 2. Depth-matched wildcard tag — O(1) lookup + * 3. Deep-wildcard expressions — always scanned (typically a small list) + * + * @param exprSet - A `ExpressionSet` instance + * @returns `true` if at least one expression matches the current path + * + * @example + * ```typescript + * // Replaces: + * // for (const expr of stopNodeExpressions) { + * // if (matcher.matches(expr)) return true; + * // } + * + * if (matcher.matchesAny(stopNodes)) { + * // current tag is a stop node + * } + * ``` + */ + matchesAny(exprSet: ExpressionSet): boolean; + /** + * Create a snapshot of current state + * @returns State snapshot that can be restored later + */ + snapshot(): MatcherSnapshot; + + /** + * Restore state from snapshot + * @param snapshot - State snapshot from previous snapshot() call + */ + restore(snapshot: MatcherSnapshot): void; + + /** + * Return a read-only view of this matcher. + */ + readOnly(): ReadOnlyMatcher; +} + +/** + * ExpressionSet - An indexed collection of Expressions for efficient bulk matching + * + * Pre-indexes expressions at insertion time by depth and terminal tag name so + * that `matchesAny()` performs an O(1) bucket lookup rather than a full O(E) + * linear scan on every tag. + * + * @example + * ```javascript + * const { Expression, ExpressionSet, Matcher } = require('path-expression-matcher'); + * + * // Build once at config time + * const stopNodes = new ExpressionSet(); + * stopNodes + * .add(new Expression('root.users.user')) + * .add(new Expression('root.config.*')) + * .add(new Expression('..script')) + * .seal(); + * + * // Per-tag — hot path + * if (stopNodes.matchesAny(matcher)) { ... } + * ``` + */ +declare class ExpressionSet { + constructor(); + + /** Number of expressions currently in the set. */ + readonly size: number; + + /** Whether the set has been sealed against further modifications. */ + readonly isSealed: boolean; + + /** + * Add a single Expression. Duplicate patterns are silently ignored. + * @throws {TypeError} if the set has been sealed + */ + add(expression: Expression): this; + + /** + * Add multiple expressions at once. + * @throws {TypeError} if the set has been sealed + */ + addAll(expressions: Expression[]): this; + + /** Check whether an expression with the same pattern is already present. */ + has(expression: Expression): boolean; + + /** + * Seal the set against further modifications. + * Any subsequent call to add() or addAll() will throw a TypeError. + */ + seal(): this; + + /** + * Test whether the matcher's current path matches any expression in the set. + * Accepts both a Matcher instance and a ReadOnlyMatcher view. + * + * + * @param matcher - A `Matcher` instance or a `ReadOnlyMatcher` view + * @returns Expression if at least one expression matches the current path + */ + matchesAny(matcher: Matcher | ReadOnlyMatcher): boolean; + + /** + * Find the first expression in the set that matches the matcher's current path. + + * + * @param matcher - A `Matcher` instance or a `ReadOnlyMatcher` view + * @returns Expression if at least one expression matches the current path + * + * @example + * ```typescript + * const node = stopNodes.findMatch(matcher); + * ``` + */ + findMatch(matcher: Matcher | ReadOnlyMatcher): Expression; +} + +declare namespace pathExpressionMatcher { + export { + Expression, + Matcher, + ExpressionSet, + ExpressionOptions, + MatcherOptions, + Segment, + PathNode, + MatcherSnapshot, + }; +} + +export = pathExpressionMatcher; diff --git a/node_modules/path-expression-matcher/lib/pem.min.js b/node_modules/path-expression-matcher/lib/pem.min.js new file mode 100644 index 0000000..67b9f39 --- /dev/null +++ b/node_modules/path-expression-matcher/lib/pem.min.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.pem=e():t.pem=e()}(this,()=>(()=>{"use strict";var t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{Expression:()=>s,ExpressionSet:()=>r,Matcher:()=>n,default:()=>h});class s{constructor(t,e={},s){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=s,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let s=0,i="";for(;s0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const s=e[e.length-1];return void 0!==s.values&&t in s.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class n{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new i(this)}push(t,e=null,s=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const i=this.path.length;this.siblingStacks[i]||(this.siblingStacks[i]=new Map);const n=this.siblingStacks[i],r=s?`${s}:${t}`:t,h=n.get(r)||0;let a=0;for(const t of n.values())a+=t;n.set(r,h+1);const p={tag:t,position:a,counter:h};null!=s&&(p.namespace=s),null!=e&&(p.values=e),this.path.push(p)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const s=t||this.separator;if(s===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(s);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(s)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e=0&&e>=0;){const i=t[s];if("deep-wildcard"===i.type){if(s--,s<0)return!0;const i=t[s];let n=!1;for(let t=e;t>=0;t--)if(this._matchSegment(i,this.path[t],t===this.path.length-1)){e=t-1,s--,n=!0;break}if(!n)return!1}else{if(!this._matchSegment(i,this.path[e],e===this.path.length-1))return!1;e--,s--}}return s<0}_matchSegment(t,e,s){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!s)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!s)return!1;const i=e.counter??0;if("first"===t.position&&0!==i)return!1;if("odd"===t.position&&i%2!=1)return!1;if("even"===t.position&&i%2!=0)return!1;if("nth"===t.position&&i!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}class r{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._patterns=new Set,this._sealed=!1}add(t){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(t.pattern))return this;if(this._patterns.add(t.pattern),t.hasDeepWildcard())return this._deepWildcards.push(t),this;const e=t.length,s=t.segments[t.segments.length-1],i=s?.tag;if(i&&"*"!==i){const s=`${e}:${i}`;this._byDepthAndTag.has(s)||this._byDepthAndTag.set(s,[]),this._byDepthAndTag.get(s).push(t)}else this._wildcardByDepth.has(e)||this._wildcardByDepth.set(e,[]),this._wildcardByDepth.get(e).push(t);return this}addAll(t){for(const e of t)this.add(e);return this}has(t){return this._patterns.has(t.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(t){return null!==this.findMatch(t)}findMatch(t){const e=t.getDepth(),s=`${e}:${t.getCurrentTag()}`,i=this._byDepthAndTag.get(s);if(i)for(let e=0;e {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Expression - Parses and stores a tag pattern expression\n * \n * Patterns are parsed once and stored in an optimized structure for fast matching.\n * \n * @example\n * const expr = new Expression(\"root.users.user\");\n * const expr2 = new Expression(\"..user[id]:first\");\n * const expr3 = new Expression(\"root/users/user\", { separator: '/' });\n */\nexport default class Expression {\n /**\n * Create a new Expression\n * @param {string} pattern - Pattern string (e.g., \"root.users.user\", \"..user[id]\")\n * @param {Object} options - Configuration options\n * @param {string} options.separator - Path separator (default: '.')\n */\n constructor(pattern, options = {}, data) {\n this.pattern = pattern;\n this.separator = options.separator || '.';\n this.segments = this._parse(pattern);\n this.data = data;\n // Cache expensive checks for performance (O(1) instead of O(n))\n this._hasDeepWildcard = this.segments.some(seg => seg.type === 'deep-wildcard');\n this._hasAttributeCondition = this.segments.some(seg => seg.attrName !== undefined);\n this._hasPositionSelector = this.segments.some(seg => seg.position !== undefined);\n }\n\n /**\n * Parse pattern string into segments\n * @private\n * @param {string} pattern - Pattern to parse\n * @returns {Array} Array of segment objects\n */\n _parse(pattern) {\n const segments = [];\n\n // Split by separator but handle \"..\" specially\n let i = 0;\n let currentPart = '';\n\n while (i < pattern.length) {\n if (pattern[i] === this.separator) {\n // Check if next char is also separator (deep wildcard)\n if (i + 1 < pattern.length && pattern[i + 1] === this.separator) {\n // Flush current part if any\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n currentPart = '';\n }\n // Add deep wildcard\n segments.push({ type: 'deep-wildcard' });\n i += 2; // Skip both separators\n } else {\n // Regular separator\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n currentPart = '';\n i++;\n }\n } else {\n currentPart += pattern[i];\n i++;\n }\n }\n\n // Flush remaining part\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n\n return segments;\n }\n\n /**\n * Parse a single segment\n * @private\n * @param {string} part - Segment string (e.g., \"user\", \"ns::user\", \"user[id]\", \"ns::user:first\")\n * @returns {Object} Segment object\n */\n _parseSegment(part) {\n const segment = { type: 'tag' };\n\n // NEW NAMESPACE SYNTAX (v2.0):\n // ============================\n // Namespace uses DOUBLE colon (::)\n // Position uses SINGLE colon (:)\n // \n // Examples:\n // \"user\" → tag\n // \"user:first\" → tag + position\n // \"user[id]\" → tag + attribute\n // \"user[id]:first\" → tag + attribute + position\n // \"ns::user\" → namespace + tag\n // \"ns::user:first\" → namespace + tag + position\n // \"ns::user[id]\" → namespace + tag + attribute\n // \"ns::user[id]:first\" → namespace + tag + attribute + position\n // \"ns::first\" → namespace + tag named \"first\" (NO ambiguity!)\n //\n // This eliminates all ambiguity:\n // :: = namespace separator\n // : = position selector\n // [] = attributes\n\n // Step 1: Extract brackets [attr] or [attr=value]\n let bracketContent = null;\n let withoutBrackets = part;\n\n const bracketMatch = part.match(/^([^\\[]+)(\\[[^\\]]*\\])(.*)$/);\n if (bracketMatch) {\n withoutBrackets = bracketMatch[1] + bracketMatch[3];\n if (bracketMatch[2]) {\n const content = bracketMatch[2].slice(1, -1);\n if (content) {\n bracketContent = content;\n }\n }\n }\n\n // Step 2: Check for namespace (double colon ::)\n let namespace = undefined;\n let tagAndPosition = withoutBrackets;\n\n if (withoutBrackets.includes('::')) {\n const nsIndex = withoutBrackets.indexOf('::');\n namespace = withoutBrackets.substring(0, nsIndex).trim();\n tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim(); // Skip ::\n\n if (!namespace) {\n throw new Error(`Invalid namespace in pattern: ${part}`);\n }\n }\n\n // Step 3: Parse tag and position (single colon :)\n let tag = undefined;\n let positionMatch = null;\n\n if (tagAndPosition.includes(':')) {\n const colonIndex = tagAndPosition.lastIndexOf(':'); // Use last colon for position\n const tagPart = tagAndPosition.substring(0, colonIndex).trim();\n const posPart = tagAndPosition.substring(colonIndex + 1).trim();\n\n // Verify position is a valid keyword\n const isPositionKeyword = ['first', 'last', 'odd', 'even'].includes(posPart) ||\n /^nth\\(\\d+\\)$/.test(posPart);\n\n if (isPositionKeyword) {\n tag = tagPart;\n positionMatch = posPart;\n } else {\n // Not a valid position keyword, treat whole thing as tag\n tag = tagAndPosition;\n }\n } else {\n tag = tagAndPosition;\n }\n\n if (!tag) {\n throw new Error(`Invalid segment pattern: ${part}`);\n }\n\n segment.tag = tag;\n if (namespace) {\n segment.namespace = namespace;\n }\n\n // Step 4: Parse attributes\n if (bracketContent) {\n if (bracketContent.includes('=')) {\n const eqIndex = bracketContent.indexOf('=');\n segment.attrName = bracketContent.substring(0, eqIndex).trim();\n segment.attrValue = bracketContent.substring(eqIndex + 1).trim();\n } else {\n segment.attrName = bracketContent.trim();\n }\n }\n\n // Step 5: Parse position selector\n if (positionMatch) {\n const nthMatch = positionMatch.match(/^nth\\((\\d+)\\)$/);\n if (nthMatch) {\n segment.position = 'nth';\n segment.positionValue = parseInt(nthMatch[1], 10);\n } else {\n segment.position = positionMatch;\n }\n }\n\n return segment;\n }\n\n /**\n * Get the number of segments\n * @returns {number}\n */\n get length() {\n return this.segments.length;\n }\n\n /**\n * Check if expression contains deep wildcard\n * @returns {boolean}\n */\n hasDeepWildcard() {\n return this._hasDeepWildcard;\n }\n\n /**\n * Check if expression has attribute conditions\n * @returns {boolean}\n */\n hasAttributeCondition() {\n return this._hasAttributeCondition;\n }\n\n /**\n * Check if expression has position selectors\n * @returns {boolean}\n */\n hasPositionSelector() {\n return this._hasPositionSelector;\n }\n\n /**\n * Get string representation\n * @returns {string}\n */\n toString() {\n return this.pattern;\n }\n}","import ExpressionSet from \"./ExpressionSet.js\";\n\n/**\n * MatcherView - A lightweight read-only view over a Matcher's internal state.\n *\n * Created once by Matcher and reused across all callbacks. Holds a direct\n * reference to the parent Matcher so it always reflects current parser state\n * with zero copying or freezing overhead.\n *\n * Users receive this via {@link Matcher#readOnly} or directly from parser\n * callbacks. It exposes all query and matching methods but has no mutation\n * methods — misuse is caught at the TypeScript level rather than at runtime.\n *\n * @example\n * const matcher = new Matcher();\n * const view = matcher.readOnly();\n *\n * matcher.push(\"root\", {});\n * view.getCurrentTag(); // \"root\"\n * view.getDepth(); // 1\n */\nexport class MatcherView {\n /**\n * @param {Matcher} matcher - The parent Matcher instance to read from.\n */\n constructor(matcher) {\n this._matcher = matcher;\n }\n\n /**\n * Get the path separator used by the parent matcher.\n * @returns {string}\n */\n get separator() {\n return this._matcher.separator;\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return undefined;\n return path[path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return false;\n const current = path[path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this._matcher.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n return this._matcher.toString(separator, includeNamespace);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this._matcher.path.map(n => n.tag);\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n return this._matcher.matches(expression);\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this._matcher);\n }\n}\n\n/**\n * Matcher - Tracks current path in XML/JSON tree and matches against Expressions.\n *\n * The matcher maintains a stack of nodes representing the current path from root to\n * current tag. It only stores attribute values for the current (top) node to minimize\n * memory usage. Sibling tracking is used to auto-calculate position and counter.\n *\n * Use {@link Matcher#readOnly} to obtain a {@link MatcherView} safe to pass to\n * user callbacks — it always reflects current state with no Proxy overhead.\n *\n * @example\n * const matcher = new Matcher();\n * matcher.push(\"root\", {});\n * matcher.push(\"users\", {});\n * matcher.push(\"user\", { id: \"123\", type: \"admin\" });\n *\n * const expr = new Expression(\"root.users.user\");\n * matcher.matches(expr); // true\n */\nexport default class Matcher {\n /**\n * Create a new Matcher.\n * @param {Object} [options={}]\n * @param {string} [options.separator='.'] - Default path separator\n */\n constructor(options = {}) {\n this.separator = options.separator || '.';\n this.path = [];\n this.siblingStacks = [];\n // Each path node: { tag, values, position, counter, namespace? }\n // values only present for current (last) node\n // Each siblingStacks entry: Map tracking occurrences at each level\n this._pathStringCache = null;\n this._view = new MatcherView(this);\n }\n\n /**\n * Push a new tag onto the path.\n * @param {string} tagName\n * @param {Object|null} [attrValues=null]\n * @param {string|null} [namespace=null]\n */\n push(tagName, attrValues = null, namespace = null) {\n this._pathStringCache = null;\n\n // Remove values from previous current node (now becoming ancestor)\n if (this.path.length > 0) {\n this.path[this.path.length - 1].values = undefined;\n }\n\n // Get or create sibling tracking for current level\n const currentLevel = this.path.length;\n if (!this.siblingStacks[currentLevel]) {\n this.siblingStacks[currentLevel] = new Map();\n }\n\n const siblings = this.siblingStacks[currentLevel];\n\n // Create a unique key for sibling tracking that includes namespace\n const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;\n\n // Calculate counter (how many times this tag appeared at this level)\n const counter = siblings.get(siblingKey) || 0;\n\n // Calculate position (total children at this level so far)\n let position = 0;\n for (const count of siblings.values()) {\n position += count;\n }\n\n // Update sibling count for this tag\n siblings.set(siblingKey, counter + 1);\n\n // Create new node\n const node = {\n tag: tagName,\n position: position,\n counter: counter\n };\n\n if (namespace !== null && namespace !== undefined) {\n node.namespace = namespace;\n }\n\n if (attrValues !== null && attrValues !== undefined) {\n node.values = attrValues;\n }\n\n this.path.push(node);\n }\n\n /**\n * Pop the last tag from the path.\n * @returns {Object|undefined} The popped node\n */\n pop() {\n if (this.path.length === 0) return undefined;\n this._pathStringCache = null;\n\n const node = this.path.pop();\n\n if (this.siblingStacks.length > this.path.length + 1) {\n this.siblingStacks.length = this.path.length + 1;\n }\n\n return node;\n }\n\n /**\n * Update current node's attribute values.\n * Useful when attributes are parsed after push.\n * @param {Object} attrValues\n */\n updateCurrent(attrValues) {\n if (this.path.length > 0) {\n const current = this.path[this.path.length - 1];\n if (attrValues !== null && attrValues !== undefined) {\n current.values = attrValues;\n }\n }\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n return this.path.length > 0 ? this.path[this.path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n return this.path.length > 0 ? this.path[this.path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n if (this.path.length === 0) return undefined;\n return this.path[this.path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n if (this.path.length === 0) return false;\n const current = this.path[this.path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n const sep = separator || this.separator;\n const isDefault = (sep === this.separator && includeNamespace === true);\n\n if (isDefault) {\n if (this._pathStringCache !== null) {\n return this._pathStringCache;\n }\n const result = this.path.map(n =>\n (n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n this._pathStringCache = result;\n return result;\n }\n\n return this.path.map(n =>\n (includeNamespace && n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this.path.map(n => n.tag);\n }\n\n /**\n * Reset the path to empty.\n */\n reset() {\n this._pathStringCache = null;\n this.path = [];\n this.siblingStacks = [];\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n const segments = expression.segments;\n\n if (segments.length === 0) {\n return false;\n }\n\n if (expression.hasDeepWildcard()) {\n return this._matchWithDeepWildcard(segments);\n }\n\n return this._matchSimple(segments);\n }\n\n /**\n * @private\n */\n _matchSimple(segments) {\n if (this.path.length !== segments.length) {\n return false;\n }\n\n for (let i = 0; i < segments.length; i++) {\n if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * @private\n */\n _matchWithDeepWildcard(segments) {\n let pathIdx = this.path.length - 1;\n let segIdx = segments.length - 1;\n\n while (segIdx >= 0 && pathIdx >= 0) {\n const segment = segments[segIdx];\n\n if (segment.type === 'deep-wildcard') {\n segIdx--;\n\n if (segIdx < 0) {\n return true;\n }\n\n const nextSeg = segments[segIdx];\n let found = false;\n\n for (let i = pathIdx; i >= 0; i--) {\n if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) {\n pathIdx = i - 1;\n segIdx--;\n found = true;\n break;\n }\n }\n\n if (!found) {\n return false;\n }\n } else {\n if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) {\n return false;\n }\n pathIdx--;\n segIdx--;\n }\n }\n\n return segIdx < 0;\n }\n\n /**\n * @private\n */\n _matchSegment(segment, node, isCurrentNode) {\n if (segment.tag !== '*' && segment.tag !== node.tag) {\n return false;\n }\n\n if (segment.namespace !== undefined) {\n if (segment.namespace !== '*' && segment.namespace !== node.namespace) {\n return false;\n }\n }\n\n if (segment.attrName !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n if (!node.values || !(segment.attrName in node.values)) {\n return false;\n }\n\n if (segment.attrValue !== undefined) {\n if (String(node.values[segment.attrName]) !== String(segment.attrValue)) {\n return false;\n }\n }\n }\n\n if (segment.position !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n const counter = node.counter ?? 0;\n\n if (segment.position === 'first' && counter !== 0) {\n return false;\n } else if (segment.position === 'odd' && counter % 2 !== 1) {\n return false;\n } else if (segment.position === 'even' && counter % 2 !== 0) {\n return false;\n } else if (segment.position === 'nth' && counter !== segment.positionValue) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this);\n }\n\n /**\n * Create a snapshot of current state.\n * @returns {Object}\n */\n snapshot() {\n return {\n path: this.path.map(node => ({ ...node })),\n siblingStacks: this.siblingStacks.map(map => new Map(map))\n };\n }\n\n /**\n * Restore state from snapshot.\n * @param {Object} snapshot\n */\n restore(snapshot) {\n this._pathStringCache = null;\n this.path = snapshot.path.map(node => ({ ...node }));\n this.siblingStacks = snapshot.siblingStacks.map(map => new Map(map));\n }\n\n /**\n * Return the read-only {@link MatcherView} for this matcher.\n *\n * The same instance is returned on every call — no allocation occurs.\n * It always reflects the current parser state and is safe to pass to\n * user callbacks without risk of accidental mutation.\n *\n * @returns {MatcherView}\n *\n * @example\n * const view = matcher.readOnly();\n * // pass view to callbacks — it stays in sync automatically\n * view.matches(expr); // ✓\n * view.getCurrentTag(); // ✓\n * // view.push(...) // ✗ method does not exist — caught by TypeScript\n */\n readOnly() {\n return this._view;\n }\n}","/**\n * ExpressionSet - An indexed collection of Expressions for efficient bulk matching\n *\n * Instead of iterating all expressions on every tag, ExpressionSet pre-indexes\n * them at insertion time by depth and terminal tag name. At match time, only\n * the relevant bucket is evaluated — typically reducing checks from O(E) to O(1)\n * lookup plus O(small bucket) matches.\n *\n * Three buckets are maintained:\n * - `_byDepthAndTag` — exact depth + exact tag name (tightest, used first)\n * - `_wildcardByDepth` — exact depth + wildcard tag `*` (depth-matched only)\n * - `_deepWildcards` — expressions containing `..` (cannot be depth-indexed)\n *\n * @example\n * import { Expression, ExpressionSet } from 'fast-xml-tagger';\n *\n * // Build once at config time\n * const stopNodes = new ExpressionSet();\n * stopNodes.add(new Expression('root.users.user'));\n * stopNodes.add(new Expression('root.config.setting'));\n * stopNodes.add(new Expression('..script'));\n *\n * // Query on every tag — hot path\n * if (stopNodes.matchesAny(matcher)) { ... }\n */\nexport default class ExpressionSet {\n constructor() {\n /** @type {Map} depth:tag → expressions */\n this._byDepthAndTag = new Map();\n\n /** @type {Map} depth → wildcard-tag expressions */\n this._wildcardByDepth = new Map();\n\n /** @type {import('./Expression.js').default[]} expressions containing deep wildcard (..) */\n this._deepWildcards = [];\n\n /** @type {Set} pattern strings already added — used for deduplication */\n this._patterns = new Set();\n\n /** @type {boolean} whether the set is sealed against further additions */\n this._sealed = false;\n }\n\n /**\n * Add an Expression to the set.\n * Duplicate patterns (same pattern string) are silently ignored.\n *\n * @param {import('./Expression.js').default} expression - A pre-constructed Expression instance\n * @returns {this} for chaining\n * @throws {TypeError} if called after seal()\n *\n * @example\n * set.add(new Expression('root.users.user'));\n * set.add(new Expression('..script'));\n */\n add(expression) {\n if (this._sealed) {\n throw new TypeError(\n 'ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.'\n );\n }\n\n // Deduplicate by pattern string\n if (this._patterns.has(expression.pattern)) return this;\n this._patterns.add(expression.pattern);\n\n if (expression.hasDeepWildcard()) {\n this._deepWildcards.push(expression);\n return this;\n }\n\n const depth = expression.length;\n const lastSeg = expression.segments[expression.segments.length - 1];\n const tag = lastSeg?.tag;\n\n if (!tag || tag === '*') {\n // Can index by depth but not by tag\n if (!this._wildcardByDepth.has(depth)) this._wildcardByDepth.set(depth, []);\n this._wildcardByDepth.get(depth).push(expression);\n } else {\n // Tightest bucket: depth + tag\n const key = `${depth}:${tag}`;\n if (!this._byDepthAndTag.has(key)) this._byDepthAndTag.set(key, []);\n this._byDepthAndTag.get(key).push(expression);\n }\n\n return this;\n }\n\n /**\n * Add multiple expressions at once.\n *\n * @param {import('./Expression.js').default[]} expressions - Array of Expression instances\n * @returns {this} for chaining\n *\n * @example\n * set.addAll([\n * new Expression('root.users.user'),\n * new Expression('root.config.setting'),\n * ]);\n */\n addAll(expressions) {\n for (const expr of expressions) this.add(expr);\n return this;\n }\n\n /**\n * Check whether a pattern string is already present in the set.\n *\n * @param {import('./Expression.js').default} expression\n * @returns {boolean}\n */\n has(expression) {\n return this._patterns.has(expression.pattern);\n }\n\n /**\n * Number of expressions in the set.\n * @type {number}\n */\n get size() {\n return this._patterns.size;\n }\n\n /**\n * Seal the set against further modifications.\n * Useful to prevent accidental mutations after config is built.\n * Calling add() or addAll() on a sealed set throws a TypeError.\n *\n * @returns {this}\n */\n seal() {\n this._sealed = true;\n return this;\n }\n\n /**\n * Whether the set has been sealed.\n * @type {boolean}\n */\n get isSealed() {\n return this._sealed;\n }\n\n /**\n * Test whether the matcher's current path matches any expression in the set.\n *\n * Evaluation order (cheapest → most expensive):\n * 1. Exact depth + tag bucket — O(1) lookup, typically 0–2 expressions\n * 2. Depth-only wildcard bucket — O(1) lookup, rare\n * 3. Deep-wildcard list — always checked, but usually small\n *\n * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)\n * @returns {boolean} true if any expression matches the current path\n *\n * @example\n * if (stopNodes.matchesAny(matcher)) {\n * // handle stop node\n * }\n */\n matchesAny(matcher) {\n return this.findMatch(matcher) !== null;\n }\n /**\n * Find and return the first Expression that matches the matcher's current path.\n *\n * Uses the same evaluation order as matchesAny (cheapest → most expensive):\n * 1. Exact depth + tag bucket\n * 2. Depth-only wildcard bucket\n * 3. Deep-wildcard list\n *\n * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)\n * @returns {import('./Expression.js').default | null} the first matching Expression, or null\n *\n * @example\n * const expr = stopNodes.findMatch(matcher);\n * if (expr) {\n * // access expr.config, expr.pattern, etc.\n * }\n */\n findMatch(matcher) {\n const depth = matcher.getDepth();\n const tag = matcher.getCurrentTag();\n\n // 1. Tightest bucket — most expressions live here\n const exactKey = `${depth}:${tag}`;\n const exactBucket = this._byDepthAndTag.get(exactKey);\n if (exactBucket) {\n for (let i = 0; i < exactBucket.length; i++) {\n if (matcher.matches(exactBucket[i])) return exactBucket[i];\n }\n }\n\n // 2. Depth-matched wildcard-tag expressions\n const wildcardBucket = this._wildcardByDepth.get(depth);\n if (wildcardBucket) {\n for (let i = 0; i < wildcardBucket.length; i++) {\n if (matcher.matches(wildcardBucket[i])) return wildcardBucket[i];\n }\n }\n\n // 3. Deep wildcards — cannot be pre-filtered by depth or tag\n for (let i = 0; i < this._deepWildcards.length; i++) {\n if (matcher.matches(this._deepWildcards[i])) return this._deepWildcards[i];\n }\n\n return null;\n }\n}\n","/**\n * fast-xml-tagger - XML/JSON path matching library\n * \n * Provides efficient path tracking and pattern matching for XML/JSON parsers.\n * \n * @example\n * import { Expression, Matcher } from 'fast-xml-tagger';\n * \n * // Create expression (parse once)\n * const expr = new Expression(\"root.users.user[id]\");\n * \n * // Create matcher (track path)\n * const matcher = new Matcher();\n * matcher.push(\"root\", [], {}, 0);\n * matcher.push(\"users\", [], {}, 0);\n * matcher.push(\"user\", [\"id\", \"type\"], { id: \"123\", type: \"admin\" }, 0);\n * \n * // Match\n * if (matcher.matches(expr)) {\n * console.log(\"Match found!\");\n * }\n */\n\nimport Expression from './Expression.js';\nimport Matcher from './Matcher.js';\nimport ExpressionSet from './ExpressionSet.js';\n\nexport { Expression, Matcher, ExpressionSet };\nexport default { Expression, Matcher, ExpressionSet };\n"],"names":["root","factory","exports","module","define","amd","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","Expression","constructor","pattern","options","data","separator","segments","_parse","_hasDeepWildcard","some","seg","type","_hasAttributeCondition","undefined","attrName","_hasPositionSelector","position","i","currentPart","length","trim","push","_parseSegment","part","segment","bracketContent","withoutBrackets","bracketMatch","match","content","slice","namespace","tag","tagAndPosition","includes","nsIndex","indexOf","substring","Error","positionMatch","colonIndex","lastIndexOf","tagPart","posPart","test","eqIndex","attrValue","nthMatch","positionValue","parseInt","hasDeepWildcard","hasAttributeCondition","hasPositionSelector","toString","MatcherView","matcher","_matcher","getCurrentTag","path","getCurrentNamespace","getAttrValue","values","hasAttr","current","getPosition","getCounter","counter","getIndex","getDepth","includeNamespace","toArray","map","n","matches","expression","matchesAny","exprSet","Matcher","siblingStacks","_pathStringCache","_view","tagName","attrValues","currentLevel","Map","siblings","siblingKey","count","set","node","pop","updateCurrent","sep","result","join","reset","_matchWithDeepWildcard","_matchSimple","_matchSegment","pathIdx","segIdx","nextSeg","found","isCurrentNode","String","snapshot","restore","readOnly","ExpressionSet","_byDepthAndTag","_wildcardByDepth","_deepWildcards","_patterns","Set","_sealed","add","TypeError","has","depth","lastSeg","addAll","expressions","expr","size","seal","isSealed","findMatch","exactKey","exactBucket","wildcardBucket"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/path-expression-matcher/package.json b/node_modules/path-expression-matcher/package.json new file mode 100644 index 0000000..a54cead --- /dev/null +++ b/node_modules/path-expression-matcher/package.json @@ -0,0 +1,78 @@ +{ + "name": "path-expression-matcher", + "version": "1.5.0", + "description": "Efficient path tracking and pattern matching for XML/JSON parsers", + "main": "./lib/pem.cjs", + "type": "module", + "sideEffects": false, + "module": "./src/index.js", + "types": "./src/index.d.ts", + "exports": { + ".": { + "import": { + "types": "./src/index.d.ts", + "default": "./src/index.js" + }, + "require": { + "types": "./lib/pem.d.cts", + "default": "./lib/pem.cjs" + } + } + }, + "scripts": { + "test": "c8 --reporter=lcov --reporter=text node test/*test.js", + "bundle": "webpack --config webpack.cjs.config.js" + }, + "keywords": [ + "xml", + "json", + "yaml", + "path", + "matcher", + "pattern", + "xpath", + "selector", + "parser", + "fast-xml-parser", + "fast-xml-builder" + ], + "author": "Amit Gupta (https://solothought.com)", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/NaturalIntelligence/path-expression-matcher" + }, + "bugs": { + "url": "https://github.com/NaturalIntelligence/path-expression-matcher/issues" + }, + "homepage": "https://github.com/NaturalIntelligence/path-expression-matcher#readme", + "engines": { + "node": ">=14.0.0" + }, + "files": [ + "lib", + "src/", + "README.md", + "LICENSE" + ], + "devDependencies": { + "@babel/core": "^7.13.10", + "@babel/plugin-transform-runtime": "^7.13.10", + "@babel/preset-env": "^7.13.10", + "@babel/register": "^7.13.8", + "@types/node": "20", + "babel-loader": "^8.2.2", + "c8": "^10.1.3", + "eslint": "^8.3.0", + "prettier": "^3.5.1", + "typescript": "5", + "webpack": "^5.64.4", + "webpack-cli": "^4.9.1" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ] +} \ No newline at end of file diff --git a/node_modules/path-expression-matcher/src/Expression.js b/node_modules/path-expression-matcher/src/Expression.js new file mode 100644 index 0000000..0fbcea3 --- /dev/null +++ b/node_modules/path-expression-matcher/src/Expression.js @@ -0,0 +1,232 @@ +/** + * Expression - Parses and stores a tag pattern expression + * + * Patterns are parsed once and stored in an optimized structure for fast matching. + * + * @example + * const expr = new Expression("root.users.user"); + * const expr2 = new Expression("..user[id]:first"); + * const expr3 = new Expression("root/users/user", { separator: '/' }); + */ +export default class Expression { + /** + * Create a new Expression + * @param {string} pattern - Pattern string (e.g., "root.users.user", "..user[id]") + * @param {Object} options - Configuration options + * @param {string} options.separator - Path separator (default: '.') + */ + constructor(pattern, options = {}, data) { + this.pattern = pattern; + this.separator = options.separator || '.'; + this.segments = this._parse(pattern); + this.data = data; + // Cache expensive checks for performance (O(1) instead of O(n)) + this._hasDeepWildcard = this.segments.some(seg => seg.type === 'deep-wildcard'); + this._hasAttributeCondition = this.segments.some(seg => seg.attrName !== undefined); + this._hasPositionSelector = this.segments.some(seg => seg.position !== undefined); + } + + /** + * Parse pattern string into segments + * @private + * @param {string} pattern - Pattern to parse + * @returns {Array} Array of segment objects + */ + _parse(pattern) { + const segments = []; + + // Split by separator but handle ".." specially + let i = 0; + let currentPart = ''; + + while (i < pattern.length) { + if (pattern[i] === this.separator) { + // Check if next char is also separator (deep wildcard) + if (i + 1 < pattern.length && pattern[i + 1] === this.separator) { + // Flush current part if any + if (currentPart.trim()) { + segments.push(this._parseSegment(currentPart.trim())); + currentPart = ''; + } + // Add deep wildcard + segments.push({ type: 'deep-wildcard' }); + i += 2; // Skip both separators + } else { + // Regular separator + if (currentPart.trim()) { + segments.push(this._parseSegment(currentPart.trim())); + } + currentPart = ''; + i++; + } + } else { + currentPart += pattern[i]; + i++; + } + } + + // Flush remaining part + if (currentPart.trim()) { + segments.push(this._parseSegment(currentPart.trim())); + } + + return segments; + } + + /** + * Parse a single segment + * @private + * @param {string} part - Segment string (e.g., "user", "ns::user", "user[id]", "ns::user:first") + * @returns {Object} Segment object + */ + _parseSegment(part) { + const segment = { type: 'tag' }; + + // NEW NAMESPACE SYNTAX (v2.0): + // ============================ + // Namespace uses DOUBLE colon (::) + // Position uses SINGLE colon (:) + // + // Examples: + // "user" → tag + // "user:first" → tag + position + // "user[id]" → tag + attribute + // "user[id]:first" → tag + attribute + position + // "ns::user" → namespace + tag + // "ns::user:first" → namespace + tag + position + // "ns::user[id]" → namespace + tag + attribute + // "ns::user[id]:first" → namespace + tag + attribute + position + // "ns::first" → namespace + tag named "first" (NO ambiguity!) + // + // This eliminates all ambiguity: + // :: = namespace separator + // : = position selector + // [] = attributes + + // Step 1: Extract brackets [attr] or [attr=value] + let bracketContent = null; + let withoutBrackets = part; + + const bracketMatch = part.match(/^([^\[]+)(\[[^\]]*\])(.*)$/); + if (bracketMatch) { + withoutBrackets = bracketMatch[1] + bracketMatch[3]; + if (bracketMatch[2]) { + const content = bracketMatch[2].slice(1, -1); + if (content) { + bracketContent = content; + } + } + } + + // Step 2: Check for namespace (double colon ::) + let namespace = undefined; + let tagAndPosition = withoutBrackets; + + if (withoutBrackets.includes('::')) { + const nsIndex = withoutBrackets.indexOf('::'); + namespace = withoutBrackets.substring(0, nsIndex).trim(); + tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim(); // Skip :: + + if (!namespace) { + throw new Error(`Invalid namespace in pattern: ${part}`); + } + } + + // Step 3: Parse tag and position (single colon :) + let tag = undefined; + let positionMatch = null; + + if (tagAndPosition.includes(':')) { + const colonIndex = tagAndPosition.lastIndexOf(':'); // Use last colon for position + const tagPart = tagAndPosition.substring(0, colonIndex).trim(); + const posPart = tagAndPosition.substring(colonIndex + 1).trim(); + + // Verify position is a valid keyword + const isPositionKeyword = ['first', 'last', 'odd', 'even'].includes(posPart) || + /^nth\(\d+\)$/.test(posPart); + + if (isPositionKeyword) { + tag = tagPart; + positionMatch = posPart; + } else { + // Not a valid position keyword, treat whole thing as tag + tag = tagAndPosition; + } + } else { + tag = tagAndPosition; + } + + if (!tag) { + throw new Error(`Invalid segment pattern: ${part}`); + } + + segment.tag = tag; + if (namespace) { + segment.namespace = namespace; + } + + // Step 4: Parse attributes + if (bracketContent) { + if (bracketContent.includes('=')) { + const eqIndex = bracketContent.indexOf('='); + segment.attrName = bracketContent.substring(0, eqIndex).trim(); + segment.attrValue = bracketContent.substring(eqIndex + 1).trim(); + } else { + segment.attrName = bracketContent.trim(); + } + } + + // Step 5: Parse position selector + if (positionMatch) { + const nthMatch = positionMatch.match(/^nth\((\d+)\)$/); + if (nthMatch) { + segment.position = 'nth'; + segment.positionValue = parseInt(nthMatch[1], 10); + } else { + segment.position = positionMatch; + } + } + + return segment; + } + + /** + * Get the number of segments + * @returns {number} + */ + get length() { + return this.segments.length; + } + + /** + * Check if expression contains deep wildcard + * @returns {boolean} + */ + hasDeepWildcard() { + return this._hasDeepWildcard; + } + + /** + * Check if expression has attribute conditions + * @returns {boolean} + */ + hasAttributeCondition() { + return this._hasAttributeCondition; + } + + /** + * Check if expression has position selectors + * @returns {boolean} + */ + hasPositionSelector() { + return this._hasPositionSelector; + } + + /** + * Get string representation + * @returns {string} + */ + toString() { + return this.pattern; + } +} \ No newline at end of file diff --git a/node_modules/path-expression-matcher/src/ExpressionSet.js b/node_modules/path-expression-matcher/src/ExpressionSet.js new file mode 100644 index 0000000..51b8888 --- /dev/null +++ b/node_modules/path-expression-matcher/src/ExpressionSet.js @@ -0,0 +1,209 @@ +/** + * ExpressionSet - An indexed collection of Expressions for efficient bulk matching + * + * Instead of iterating all expressions on every tag, ExpressionSet pre-indexes + * them at insertion time by depth and terminal tag name. At match time, only + * the relevant bucket is evaluated — typically reducing checks from O(E) to O(1) + * lookup plus O(small bucket) matches. + * + * Three buckets are maintained: + * - `_byDepthAndTag` — exact depth + exact tag name (tightest, used first) + * - `_wildcardByDepth` — exact depth + wildcard tag `*` (depth-matched only) + * - `_deepWildcards` — expressions containing `..` (cannot be depth-indexed) + * + * @example + * import { Expression, ExpressionSet } from 'fast-xml-tagger'; + * + * // Build once at config time + * const stopNodes = new ExpressionSet(); + * stopNodes.add(new Expression('root.users.user')); + * stopNodes.add(new Expression('root.config.setting')); + * stopNodes.add(new Expression('..script')); + * + * // Query on every tag — hot path + * if (stopNodes.matchesAny(matcher)) { ... } + */ +export default class ExpressionSet { + constructor() { + /** @type {Map} depth:tag → expressions */ + this._byDepthAndTag = new Map(); + + /** @type {Map} depth → wildcard-tag expressions */ + this._wildcardByDepth = new Map(); + + /** @type {import('./Expression.js').default[]} expressions containing deep wildcard (..) */ + this._deepWildcards = []; + + /** @type {Set} pattern strings already added — used for deduplication */ + this._patterns = new Set(); + + /** @type {boolean} whether the set is sealed against further additions */ + this._sealed = false; + } + + /** + * Add an Expression to the set. + * Duplicate patterns (same pattern string) are silently ignored. + * + * @param {import('./Expression.js').default} expression - A pre-constructed Expression instance + * @returns {this} for chaining + * @throws {TypeError} if called after seal() + * + * @example + * set.add(new Expression('root.users.user')); + * set.add(new Expression('..script')); + */ + add(expression) { + if (this._sealed) { + throw new TypeError( + 'ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.' + ); + } + + // Deduplicate by pattern string + if (this._patterns.has(expression.pattern)) return this; + this._patterns.add(expression.pattern); + + if (expression.hasDeepWildcard()) { + this._deepWildcards.push(expression); + return this; + } + + const depth = expression.length; + const lastSeg = expression.segments[expression.segments.length - 1]; + const tag = lastSeg?.tag; + + if (!tag || tag === '*') { + // Can index by depth but not by tag + if (!this._wildcardByDepth.has(depth)) this._wildcardByDepth.set(depth, []); + this._wildcardByDepth.get(depth).push(expression); + } else { + // Tightest bucket: depth + tag + const key = `${depth}:${tag}`; + if (!this._byDepthAndTag.has(key)) this._byDepthAndTag.set(key, []); + this._byDepthAndTag.get(key).push(expression); + } + + return this; + } + + /** + * Add multiple expressions at once. + * + * @param {import('./Expression.js').default[]} expressions - Array of Expression instances + * @returns {this} for chaining + * + * @example + * set.addAll([ + * new Expression('root.users.user'), + * new Expression('root.config.setting'), + * ]); + */ + addAll(expressions) { + for (const expr of expressions) this.add(expr); + return this; + } + + /** + * Check whether a pattern string is already present in the set. + * + * @param {import('./Expression.js').default} expression + * @returns {boolean} + */ + has(expression) { + return this._patterns.has(expression.pattern); + } + + /** + * Number of expressions in the set. + * @type {number} + */ + get size() { + return this._patterns.size; + } + + /** + * Seal the set against further modifications. + * Useful to prevent accidental mutations after config is built. + * Calling add() or addAll() on a sealed set throws a TypeError. + * + * @returns {this} + */ + seal() { + this._sealed = true; + return this; + } + + /** + * Whether the set has been sealed. + * @type {boolean} + */ + get isSealed() { + return this._sealed; + } + + /** + * Test whether the matcher's current path matches any expression in the set. + * + * Evaluation order (cheapest → most expensive): + * 1. Exact depth + tag bucket — O(1) lookup, typically 0–2 expressions + * 2. Depth-only wildcard bucket — O(1) lookup, rare + * 3. Deep-wildcard list — always checked, but usually small + * + * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view) + * @returns {boolean} true if any expression matches the current path + * + * @example + * if (stopNodes.matchesAny(matcher)) { + * // handle stop node + * } + */ + matchesAny(matcher) { + return this.findMatch(matcher) !== null; + } + /** + * Find and return the first Expression that matches the matcher's current path. + * + * Uses the same evaluation order as matchesAny (cheapest → most expensive): + * 1. Exact depth + tag bucket + * 2. Depth-only wildcard bucket + * 3. Deep-wildcard list + * + * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view) + * @returns {import('./Expression.js').default | null} the first matching Expression, or null + * + * @example + * const expr = stopNodes.findMatch(matcher); + * if (expr) { + * // access expr.config, expr.pattern, etc. + * } + */ + findMatch(matcher) { + const depth = matcher.getDepth(); + const tag = matcher.getCurrentTag(); + + // 1. Tightest bucket — most expressions live here + const exactKey = `${depth}:${tag}`; + const exactBucket = this._byDepthAndTag.get(exactKey); + if (exactBucket) { + for (let i = 0; i < exactBucket.length; i++) { + if (matcher.matches(exactBucket[i])) return exactBucket[i]; + } + } + + // 2. Depth-matched wildcard-tag expressions + const wildcardBucket = this._wildcardByDepth.get(depth); + if (wildcardBucket) { + for (let i = 0; i < wildcardBucket.length; i++) { + if (matcher.matches(wildcardBucket[i])) return wildcardBucket[i]; + } + } + + // 3. Deep wildcards — cannot be pre-filtered by depth or tag + for (let i = 0; i < this._deepWildcards.length; i++) { + if (matcher.matches(this._deepWildcards[i])) return this._deepWildcards[i]; + } + + return null; + } +} diff --git a/node_modules/path-expression-matcher/src/Matcher.js b/node_modules/path-expression-matcher/src/Matcher.js new file mode 100644 index 0000000..cbb8fff --- /dev/null +++ b/node_modules/path-expression-matcher/src/Matcher.js @@ -0,0 +1,570 @@ +import ExpressionSet from "./ExpressionSet.js"; + +/** + * MatcherView - A lightweight read-only view over a Matcher's internal state. + * + * Created once by Matcher and reused across all callbacks. Holds a direct + * reference to the parent Matcher so it always reflects current parser state + * with zero copying or freezing overhead. + * + * Users receive this via {@link Matcher#readOnly} or directly from parser + * callbacks. It exposes all query and matching methods but has no mutation + * methods — misuse is caught at the TypeScript level rather than at runtime. + * + * @example + * const matcher = new Matcher(); + * const view = matcher.readOnly(); + * + * matcher.push("root", {}); + * view.getCurrentTag(); // "root" + * view.getDepth(); // 1 + */ +export class MatcherView { + /** + * @param {Matcher} matcher - The parent Matcher instance to read from. + */ + constructor(matcher) { + this._matcher = matcher; + } + + /** + * Get the path separator used by the parent matcher. + * @returns {string} + */ + get separator() { + return this._matcher.separator; + } + + /** + * Get current tag name. + * @returns {string|undefined} + */ + getCurrentTag() { + const path = this._matcher.path; + return path.length > 0 ? path[path.length - 1].tag : undefined; + } + + /** + * Get current namespace. + * @returns {string|undefined} + */ + getCurrentNamespace() { + const path = this._matcher.path; + return path.length > 0 ? path[path.length - 1].namespace : undefined; + } + + /** + * Get current node's attribute value. + * @param {string} attrName + * @returns {*} + */ + getAttrValue(attrName) { + const path = this._matcher.path; + if (path.length === 0) return undefined; + return path[path.length - 1].values?.[attrName]; + } + + /** + * Check if current node has an attribute. + * @param {string} attrName + * @returns {boolean} + */ + hasAttr(attrName) { + const path = this._matcher.path; + if (path.length === 0) return false; + const current = path[path.length - 1]; + return current.values !== undefined && attrName in current.values; + } + + /** + * Get current node's sibling position (child index in parent). + * @returns {number} + */ + getPosition() { + const path = this._matcher.path; + if (path.length === 0) return -1; + return path[path.length - 1].position ?? 0; + } + + /** + * Get current node's repeat counter (occurrence count of this tag name). + * @returns {number} + */ + getCounter() { + const path = this._matcher.path; + if (path.length === 0) return -1; + return path[path.length - 1].counter ?? 0; + } + + /** + * Get current node's sibling index (alias for getPosition). + * @returns {number} + * @deprecated Use getPosition() or getCounter() instead + */ + getIndex() { + return this.getPosition(); + } + + /** + * Get current path depth. + * @returns {number} + */ + getDepth() { + return this._matcher.path.length; + } + + /** + * Get path as string. + * @param {string} [separator] - Optional separator (uses default if not provided) + * @param {boolean} [includeNamespace=true] + * @returns {string} + */ + toString(separator, includeNamespace = true) { + return this._matcher.toString(separator, includeNamespace); + } + + /** + * Get path as array of tag names. + * @returns {string[]} + */ + toArray() { + return this._matcher.path.map(n => n.tag); + } + + /** + * Match current path against an Expression. + * @param {Expression} expression + * @returns {boolean} + */ + matches(expression) { + return this._matcher.matches(expression); + } + + /** + * Match any expression in the given set against the current path. + * @param {ExpressionSet} exprSet + * @returns {boolean} + */ + matchesAny(exprSet) { + return exprSet.matchesAny(this._matcher); + } +} + +/** + * Matcher - Tracks current path in XML/JSON tree and matches against Expressions. + * + * The matcher maintains a stack of nodes representing the current path from root to + * current tag. It only stores attribute values for the current (top) node to minimize + * memory usage. Sibling tracking is used to auto-calculate position and counter. + * + * Use {@link Matcher#readOnly} to obtain a {@link MatcherView} safe to pass to + * user callbacks — it always reflects current state with no Proxy overhead. + * + * @example + * const matcher = new Matcher(); + * matcher.push("root", {}); + * matcher.push("users", {}); + * matcher.push("user", { id: "123", type: "admin" }); + * + * const expr = new Expression("root.users.user"); + * matcher.matches(expr); // true + */ +export default class Matcher { + /** + * Create a new Matcher. + * @param {Object} [options={}] + * @param {string} [options.separator='.'] - Default path separator + */ + constructor(options = {}) { + this.separator = options.separator || '.'; + this.path = []; + this.siblingStacks = []; + // Each path node: { tag, values, position, counter, namespace? } + // values only present for current (last) node + // Each siblingStacks entry: Map tracking occurrences at each level + this._pathStringCache = null; + this._view = new MatcherView(this); + } + + /** + * Push a new tag onto the path. + * @param {string} tagName + * @param {Object|null} [attrValues=null] + * @param {string|null} [namespace=null] + */ + push(tagName, attrValues = null, namespace = null) { + this._pathStringCache = null; + + // Remove values from previous current node (now becoming ancestor) + if (this.path.length > 0) { + this.path[this.path.length - 1].values = undefined; + } + + // Get or create sibling tracking for current level + const currentLevel = this.path.length; + if (!this.siblingStacks[currentLevel]) { + this.siblingStacks[currentLevel] = new Map(); + } + + const siblings = this.siblingStacks[currentLevel]; + + // Create a unique key for sibling tracking that includes namespace + const siblingKey = namespace ? `${namespace}:${tagName}` : tagName; + + // Calculate counter (how many times this tag appeared at this level) + const counter = siblings.get(siblingKey) || 0; + + // Calculate position (total children at this level so far) + let position = 0; + for (const count of siblings.values()) { + position += count; + } + + // Update sibling count for this tag + siblings.set(siblingKey, counter + 1); + + // Create new node + const node = { + tag: tagName, + position: position, + counter: counter + }; + + if (namespace !== null && namespace !== undefined) { + node.namespace = namespace; + } + + if (attrValues !== null && attrValues !== undefined) { + node.values = attrValues; + } + + this.path.push(node); + } + + /** + * Pop the last tag from the path. + * @returns {Object|undefined} The popped node + */ + pop() { + if (this.path.length === 0) return undefined; + this._pathStringCache = null; + + const node = this.path.pop(); + + if (this.siblingStacks.length > this.path.length + 1) { + this.siblingStacks.length = this.path.length + 1; + } + + return node; + } + + /** + * Update current node's attribute values. + * Useful when attributes are parsed after push. + * @param {Object} attrValues + */ + updateCurrent(attrValues) { + if (this.path.length > 0) { + const current = this.path[this.path.length - 1]; + if (attrValues !== null && attrValues !== undefined) { + current.values = attrValues; + } + } + } + + /** + * Get current tag name. + * @returns {string|undefined} + */ + getCurrentTag() { + return this.path.length > 0 ? this.path[this.path.length - 1].tag : undefined; + } + + /** + * Get current namespace. + * @returns {string|undefined} + */ + getCurrentNamespace() { + return this.path.length > 0 ? this.path[this.path.length - 1].namespace : undefined; + } + + /** + * Get current node's attribute value. + * @param {string} attrName + * @returns {*} + */ + getAttrValue(attrName) { + if (this.path.length === 0) return undefined; + return this.path[this.path.length - 1].values?.[attrName]; + } + + /** + * Check if current node has an attribute. + * @param {string} attrName + * @returns {boolean} + */ + hasAttr(attrName) { + if (this.path.length === 0) return false; + const current = this.path[this.path.length - 1]; + return current.values !== undefined && attrName in current.values; + } + + /** + * Get current node's sibling position (child index in parent). + * @returns {number} + */ + getPosition() { + if (this.path.length === 0) return -1; + return this.path[this.path.length - 1].position ?? 0; + } + + /** + * Get current node's repeat counter (occurrence count of this tag name). + * @returns {number} + */ + getCounter() { + if (this.path.length === 0) return -1; + return this.path[this.path.length - 1].counter ?? 0; + } + + /** + * Get current node's sibling index (alias for getPosition). + * @returns {number} + * @deprecated Use getPosition() or getCounter() instead + */ + getIndex() { + return this.getPosition(); + } + + /** + * Get current path depth. + * @returns {number} + */ + getDepth() { + return this.path.length; + } + + /** + * Get path as string. + * @param {string} [separator] - Optional separator (uses default if not provided) + * @param {boolean} [includeNamespace=true] + * @returns {string} + */ + toString(separator, includeNamespace = true) { + const sep = separator || this.separator; + const isDefault = (sep === this.separator && includeNamespace === true); + + if (isDefault) { + if (this._pathStringCache !== null) { + return this._pathStringCache; + } + const result = this.path.map(n => + (n.namespace) ? `${n.namespace}:${n.tag}` : n.tag + ).join(sep); + this._pathStringCache = result; + return result; + } + + return this.path.map(n => + (includeNamespace && n.namespace) ? `${n.namespace}:${n.tag}` : n.tag + ).join(sep); + } + + /** + * Get path as array of tag names. + * @returns {string[]} + */ + toArray() { + return this.path.map(n => n.tag); + } + + /** + * Reset the path to empty. + */ + reset() { + this._pathStringCache = null; + this.path = []; + this.siblingStacks = []; + } + + /** + * Match current path against an Expression. + * @param {Expression} expression + * @returns {boolean} + */ + matches(expression) { + const segments = expression.segments; + + if (segments.length === 0) { + return false; + } + + if (expression.hasDeepWildcard()) { + return this._matchWithDeepWildcard(segments); + } + + return this._matchSimple(segments); + } + + /** + * @private + */ + _matchSimple(segments) { + if (this.path.length !== segments.length) { + return false; + } + + for (let i = 0; i < segments.length; i++) { + if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) { + return false; + } + } + + return true; + } + + /** + * @private + */ + _matchWithDeepWildcard(segments) { + let pathIdx = this.path.length - 1; + let segIdx = segments.length - 1; + + while (segIdx >= 0 && pathIdx >= 0) { + const segment = segments[segIdx]; + + if (segment.type === 'deep-wildcard') { + segIdx--; + + if (segIdx < 0) { + return true; + } + + const nextSeg = segments[segIdx]; + let found = false; + + for (let i = pathIdx; i >= 0; i--) { + if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) { + pathIdx = i - 1; + segIdx--; + found = true; + break; + } + } + + if (!found) { + return false; + } + } else { + if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) { + return false; + } + pathIdx--; + segIdx--; + } + } + + return segIdx < 0; + } + + /** + * @private + */ + _matchSegment(segment, node, isCurrentNode) { + if (segment.tag !== '*' && segment.tag !== node.tag) { + return false; + } + + if (segment.namespace !== undefined) { + if (segment.namespace !== '*' && segment.namespace !== node.namespace) { + return false; + } + } + + if (segment.attrName !== undefined) { + if (!isCurrentNode) { + return false; + } + + if (!node.values || !(segment.attrName in node.values)) { + return false; + } + + if (segment.attrValue !== undefined) { + if (String(node.values[segment.attrName]) !== String(segment.attrValue)) { + return false; + } + } + } + + if (segment.position !== undefined) { + if (!isCurrentNode) { + return false; + } + + const counter = node.counter ?? 0; + + if (segment.position === 'first' && counter !== 0) { + return false; + } else if (segment.position === 'odd' && counter % 2 !== 1) { + return false; + } else if (segment.position === 'even' && counter % 2 !== 0) { + return false; + } else if (segment.position === 'nth' && counter !== segment.positionValue) { + return false; + } + } + + return true; + } + + /** + * Match any expression in the given set against the current path. + * @param {ExpressionSet} exprSet + * @returns {boolean} + */ + matchesAny(exprSet) { + return exprSet.matchesAny(this); + } + + /** + * Create a snapshot of current state. + * @returns {Object} + */ + snapshot() { + return { + path: this.path.map(node => ({ ...node })), + siblingStacks: this.siblingStacks.map(map => new Map(map)) + }; + } + + /** + * Restore state from snapshot. + * @param {Object} snapshot + */ + restore(snapshot) { + this._pathStringCache = null; + this.path = snapshot.path.map(node => ({ ...node })); + this.siblingStacks = snapshot.siblingStacks.map(map => new Map(map)); + } + + /** + * Return the read-only {@link MatcherView} for this matcher. + * + * The same instance is returned on every call — no allocation occurs. + * It always reflects the current parser state and is safe to pass to + * user callbacks without risk of accidental mutation. + * + * @returns {MatcherView} + * + * @example + * const view = matcher.readOnly(); + * // pass view to callbacks — it stays in sync automatically + * view.matches(expr); // ✓ + * view.getCurrentTag(); // ✓ + * // view.push(...) // ✗ method does not exist — caught by TypeScript + */ + readOnly() { + return this._view; + } +} \ No newline at end of file diff --git a/node_modules/path-expression-matcher/src/index.d.ts b/node_modules/path-expression-matcher/src/index.d.ts new file mode 100644 index 0000000..18cd2d0 --- /dev/null +++ b/node_modules/path-expression-matcher/src/index.d.ts @@ -0,0 +1,523 @@ +/** + * TypeScript definitions for path-expression-matcher + * + * Provides efficient path tracking and pattern matching for XML/JSON parsers. + */ + +/** + * Options for creating an Expression + */ +export interface ExpressionOptions { + /** + * Path separator character + * @default '.' + */ + separator?: string; +} + +/** + * Parsed segment from an expression pattern + */ +export interface Segment { + /** + * Type of segment + */ + type: 'tag' | 'deep-wildcard'; + + /** + * Tag name (e.g., "user", "*" for wildcard) + * Only present when type is 'tag' + */ + tag?: string; + + /** + * Namespace prefix (e.g., "ns" in "ns::user") + * Only present when namespace is specified + */ + namespace?: string; + + /** + * Attribute name to match (e.g., "id" in "user[id]") + * Only present when attribute condition exists + */ + attrName?: string; + + /** + * Attribute value to match (e.g., "123" in "user[id=123]") + * Only present when attribute value is specified + */ + attrValue?: string; + + /** + * Position selector type + * Only present when position selector exists + */ + position?: 'first' | 'last' | 'odd' | 'even' | 'nth'; + + /** + * Numeric value for nth() selector + * Only present when position is 'nth' + */ + positionValue?: number; +} + +/** + * Expression - Parses and stores a tag pattern expression + * + * Patterns are parsed once and stored in an optimized structure for fast matching. + * + * @example + * ```typescript + * const expr = new Expression("root.users.user"); + * const expr2 = new Expression("..user[id]:first"); + * const expr3 = new Expression("root/users/user", { separator: '/' }); + * ``` + * + * Pattern Syntax: + * - `root.users.user` - Match exact path + * - `..user` - Match "user" at any depth (deep wildcard) + * - `user[id]` - Match user tag with "id" attribute + * - `user[id=123]` - Match user tag where id="123" + * - `user:first` - Match first occurrence of user tag + * - `ns::user` - Match user tag with namespace "ns" + * - `ns::user[id]:first` - Combine namespace, attribute, and position + */ +export class Expression { + /** + * Original pattern string + */ + readonly pattern: string; + + /** + * Path separator character + */ + readonly separator: string; + + /** + * Parsed segments + */ + readonly segments: Segment[]; + + /** + * Create a new Expression + * @param pattern - Pattern string (e.g., "root.users.user", "..user[id]") + * @param options - Configuration options + */ + constructor(pattern: string, options?: ExpressionOptions); + + /** + * Get the number of segments + */ + get length(): number; + + /** + * Check if expression contains deep wildcard (..) + */ + hasDeepWildcard(): boolean; + + /** + * Check if expression has attribute conditions + */ + hasAttributeCondition(): boolean; + + /** + * Check if expression has position selectors + */ + hasPositionSelector(): boolean; + + /** + * Get string representation + */ + toString(): string; +} + +/** + * Options for creating a Matcher + */ +export interface MatcherOptions { + /** + * Default path separator + * @default '.' + */ + separator?: string; +} + +/** + * Internal node structure in the path stack + */ +export interface PathNode { + /** + * Tag name + */ + tag: string; + + /** + * Namespace (if present) + */ + namespace?: string; + + /** + * Position in sibling list (child index in parent) + */ + position: number; + + /** + * Counter (occurrence count of this tag name) + */ + counter: number; + + /** + * Attribute key-value pairs + * Only present for the current (last) node in path + */ + values?: Record; +} + +/** + * Snapshot of matcher state + */ +export interface MatcherSnapshot { + /** + * Copy of the path stack + */ + path: PathNode[]; + + /** + * Copy of sibling tracking maps + */ + siblingStacks: Map[]; +} + +/** + * MatcherView - A lightweight read-only view over a {@link Matcher} instance. + * + * Created once by {@link Matcher} and reused across all callbacks — no allocation + * on every invocation. Holds a direct reference to the parent Matcher's internal + * state so it always reflects the current parser position with zero copying or + * freezing overhead. + * + * Mutation methods (`push`, `pop`, `reset`, `updateCurrent`, `restore`) are simply + * absent from this class, so misuse is caught at compile time by TypeScript rather + * than at runtime. + * + * Obtain via {@link Matcher#readOnly} — the same instance is returned every time. + * + * @example + * ```typescript + * const matcher = new Matcher(); + * const view: MatcherView = matcher.readOnly(); + * + * matcher.push("root", {}); + * matcher.push("users", {}); + * matcher.push("user", { id: "123" }); + * + * view.matches(expr); // ✓ true + * view.getCurrentTag(); // ✓ "user" + * view.getDepth(); // ✓ 3 + * // view.push(...) // ✗ Property 'push' does not exist on type 'MatcherView' + * ``` + */ +export class MatcherView { + /** + * Default path separator (read-only, delegates to parent Matcher) + */ + readonly separator: string; + + getCurrentTag(): string | undefined; + getCurrentNamespace(): string | undefined; + getAttrValue(attrName: string): any; + hasAttr(attrName: string): boolean; + getPosition(): number; + getCounter(): number; + /** @deprecated Use getPosition() or getCounter() instead */ + getIndex(): number; + getDepth(): number; + toString(separator?: string, includeNamespace?: boolean): string; + toArray(): string[]; + matches(expression: Expression): boolean; + matchesAny(exprSet: ExpressionSet): boolean; +} + +/** + * @deprecated Use {@link MatcherView} instead. + * Alias kept for backward compatibility with code that references `ReadOnlyMatcher`. + */ +export type ReadOnlyMatcher = MatcherView; + +/** + * Matcher - Tracks current path in XML/JSON tree and matches against Expressions. + * + * The matcher maintains a stack of nodes representing the current path from root to + * current tag. It only stores attribute values for the current (top) node to minimize + * memory usage. + * + * Use {@link Matcher#readOnly} to obtain a {@link MatcherView} safe to pass to + * user callbacks — the same instance is reused on every call with no allocation overhead. + * + * @example + * ```typescript + * const matcher = new Matcher(); + * matcher.push("root", {}); + * matcher.push("users", {}); + * matcher.push("user", { id: "123", type: "admin" }); + * + * const expr = new Expression("root.users.user"); + * matcher.matches(expr); // true + * + * matcher.pop(); + * matcher.matches(expr); // false + * ``` + */ +export class Matcher { + /** + * Default path separator + */ + readonly separator: string; + + /** + * Create a new Matcher + * @param options - Configuration options + */ + constructor(options?: MatcherOptions); + + /** + * Push a new tag onto the path. + * @param tagName - Name of the tag + * @param attrValues - Attribute key-value pairs for current node (optional) + * @param namespace - Namespace for the tag (optional) + * + * @example + * ```typescript + * matcher.push("user", { id: "123", type: "admin" }); + * matcher.push("user", { id: "456" }, "ns"); + * matcher.push("container", null); + * ``` + */ + push(tagName: string, attrValues?: Record | null, namespace?: string | null): void; + + /** + * Pop the last tag from the path. + * @returns The popped node or undefined if path is empty + */ + pop(): PathNode | undefined; + + /** + * Update current node's attribute values. + * Useful when attributes are parsed after push. + * @param attrValues - Attribute values + */ + updateCurrent(attrValues: Record): void; + + /** + * Reset the path to empty. + */ + reset(): void; + + /** + * Create a snapshot of current state. + * @returns State snapshot that can be restored later + */ + snapshot(): MatcherSnapshot; + + /** + * Restore state from snapshot. + * @param snapshot - State snapshot from previous snapshot() call + */ + restore(snapshot: MatcherSnapshot): void; + + getCurrentTag(): string | undefined; + getCurrentNamespace(): string | undefined; + getAttrValue(attrName: string): any; + hasAttr(attrName: string): boolean; + getPosition(): number; + getCounter(): number; + /** @deprecated Use getPosition() or getCounter() instead */ + getIndex(): number; + getDepth(): number; + toString(separator?: string, includeNamespace?: boolean): string; + toArray(): string[]; + matches(expression: Expression): boolean; + matchesAny(exprSet: ExpressionSet): boolean; + + /** + * Return the read-only {@link MatcherView} for this matcher. + * + * The same instance is returned on every call — no allocation occurs. + * Pass this to user callbacks; it always reflects current parser state. + * + * @example + * ```typescript + * const view = matcher.readOnly(); + * // same reference every time — safe to cache + * view === matcher.readOnly(); // true + * ``` + */ + readOnly(): MatcherView; +} + +/** + * ExpressionSet - An indexed collection of Expressions for efficient bulk matching + * + * Pre-indexes expressions at insertion time by depth and terminal tag name so + * that `matchesAny()` performs an O(1) bucket lookup rather than a full O(E) + * linear scan on every tag. + * + * Three internal buckets are maintained automatically: + * - **exact** — expressions with a fixed depth and a concrete terminal tag + * - **depth-wildcard** — fixed depth but terminal tag is `*` + * - **deep-wildcard** — expressions containing `..` (cannot be depth-indexed) + * + * @example + * ```typescript + * import { Expression, ExpressionSet, Matcher } from 'fast-xml-tagger'; + * + * // Build once at config time + * const stopNodes = new ExpressionSet(); + * stopNodes + * .add(new Expression('root.users.user')) + * .add(new Expression('root.config.*')) + * .add(new Expression('..script')) + * .seal(); // prevent accidental mutation during parsing + * + * // Query on every tag — hot path + * if (stopNodes.matchesAny(matcher)) { + * // handle stop node + * } + * ``` + */ +export class ExpressionSet { + /** + * Create an empty ExpressionSet. + */ + constructor(); + + /** + * Number of expressions currently in the set. + */ + readonly size: number; + + /** + * Whether the set has been sealed against further modifications. + */ + readonly isSealed: boolean; + + /** + * Add a single Expression to the set. + * + * Duplicate patterns (same `expression.pattern` string) are silently ignored. + * + * @param expression - A pre-constructed Expression instance + * @returns `this` — for chaining + * @throws {TypeError} if the set has been sealed + * + * @example + * ```typescript + * set.add(new Expression('root.users.user')); + * set.add(new Expression('..script')); + * ``` + */ + add(expression: Expression): this; + + /** + * Add multiple expressions at once. + * + * @param expressions - Array of Expression instances + * @returns `this` — for chaining + * @throws {TypeError} if the set has been sealed + * + * @example + * ```typescript + * set.addAll([ + * new Expression('root.users.user'), + * new Expression('root.config.setting'), + * ]); + * ``` + */ + addAll(expressions: Expression[]): this; + + /** + * Check whether an Expression with the same pattern is already present. + * + * @param expression - Expression to look up + * @returns `true` if the pattern was already added + */ + has(expression: Expression): boolean; + + /** + * Seal the set against further modifications. + * + * After calling `seal()`, any call to `add()` or `addAll()` will throw a + * `TypeError`. This is useful to prevent accidental mutation once the config + * has been fully built and parsing has started. + * + * @returns `this` — for chaining + * + * @example + * ```typescript + * const stopNodes = new ExpressionSet(); + * stopNodes.addAll(patterns.map(p => new Expression(p))).seal(); + * + * // Later — safe: reads are still allowed + * stopNodes.matchesAny(matcher); + * + * // Later — throws TypeError: ExpressionSet is sealed + * stopNodes.add(new Expression('root.extra')); + * ``` + */ + seal(): this; + + /** + * Test whether the matcher's current path matches **any** expression in the set. + * + * Uses the pre-built index to evaluate only the relevant bucket(s): + * 1. Exact depth + tag — O(1) lookup + * 2. Depth-matched wildcard tag — O(1) lookup + * 3. Deep-wildcard expressions — always scanned (typically a small list) + * + * @param matcher - A `Matcher` instance or a `ReadOnlyMatcher` view + * @returns `true` if at least one expression matches the current path + * + * @example + * ```typescript + * // Replaces: + * // for (const expr of stopNodeExpressions) { + * // if (matcher.matches(expr)) return true; + * // } + * + * if (stopNodes.matchesAny(matcher)) { + * // current tag is a stop node + * } + * ``` + */ + matchesAny(matcher: Matcher | MatcherView): boolean; + + /** + * Find the first expression in the set that matches the matcher's current path. + * + * Uses the pre-built index to evaluate only the relevant bucket(s): + * 1. Exact depth + tag — O(1) lookup + * 2. Depth-matched wildcard tag — O(1) lookup + * 3. Deep-wildcard expressions — always scanned (typically a small list) + * + * @param matcher - A `Matcher` instance or a `ReadOnlyMatcher` view + * @returns Expression if at least one expression matches the current path + * + * @example + * ```typescript + * const node = stopNodes.findMatch(matcher); + * ``` + */ + findMatch(matcher: Matcher | MatcherView): Expression; +} + +/** + * Default export containing Expression, Matcher, and ExpressionSet + */ +declare const _default: { + Expression: typeof Expression; + Matcher: typeof Matcher; + MatcherView: typeof MatcherView; + ExpressionSet: typeof ExpressionSet; +}; + +export default _default; \ No newline at end of file diff --git a/node_modules/path-expression-matcher/src/index.js b/node_modules/path-expression-matcher/src/index.js new file mode 100644 index 0000000..acea0dc --- /dev/null +++ b/node_modules/path-expression-matcher/src/index.js @@ -0,0 +1,29 @@ +/** + * fast-xml-tagger - XML/JSON path matching library + * + * Provides efficient path tracking and pattern matching for XML/JSON parsers. + * + * @example + * import { Expression, Matcher } from 'fast-xml-tagger'; + * + * // Create expression (parse once) + * const expr = new Expression("root.users.user[id]"); + * + * // Create matcher (track path) + * const matcher = new Matcher(); + * matcher.push("root", [], {}, 0); + * matcher.push("users", [], {}, 0); + * matcher.push("user", ["id", "type"], { id: "123", type: "admin" }, 0); + * + * // Match + * if (matcher.matches(expr)) { + * console.log("Match found!"); + * } + */ + +import Expression from './Expression.js'; +import Matcher from './Matcher.js'; +import ExpressionSet from './ExpressionSet.js'; + +export { Expression, Matcher, ExpressionSet }; +export default { Expression, Matcher, ExpressionSet }; diff --git a/node_modules/query-string/index.d.ts b/node_modules/query-string/index.d.ts new file mode 100644 index 0000000..59de603 --- /dev/null +++ b/node_modules/query-string/index.d.ts @@ -0,0 +1,563 @@ +export interface ParseOptions { + /** + Decode the keys and values. URI components are decoded with [`decode-uri-component`](https://github.com/SamVerschueren/decode-uri-component). + + @default true + */ + readonly decode?: boolean; + + /** + @default 'none' + + - `bracket`: Parse arrays with bracket representation: + + ``` + import queryString = require('query-string'); + + queryString.parse('foo[]=1&foo[]=2&foo[]=3', {arrayFormat: 'bracket'}); + //=> {foo: ['1', '2', '3']} + ``` + + - `index`: Parse arrays with index representation: + + ``` + import queryString = require('query-string'); + + queryString.parse('foo[0]=1&foo[1]=2&foo[3]=3', {arrayFormat: 'index'}); + //=> {foo: ['1', '2', '3']} + ``` + + - `comma`: Parse arrays with elements separated by comma: + + ``` + import queryString = require('query-string'); + + queryString.parse('foo=1,2,3', {arrayFormat: 'comma'}); + //=> {foo: ['1', '2', '3']} + ``` + + - `separator`: Parse arrays with elements separated by a custom character: + + ``` + import queryString = require('query-string'); + + queryString.parse('foo=1|2|3', {arrayFormat: 'separator', arrayFormatSeparator: '|'}); + //=> {foo: ['1', '2', '3']} + ``` + + - `bracket-separator`: Parse arrays (that are explicitly marked with brackets) with elements separated by a custom character: + + ``` + import queryString = require('query-string'); + + queryString.parse('foo[]', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); + //=> {foo: []} + + queryString.parse('foo[]=', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); + //=> {foo: ['']} + + queryString.parse('foo[]=1', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); + //=> {foo: ['1']} + + queryString.parse('foo[]=1|2|3', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); + //=> {foo: ['1', '2', '3']} + + queryString.parse('foo[]=1||3|||6', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); + //=> {foo: ['1', '', 3, '', '', '6']} + + queryString.parse('foo[]=1|2|3&bar=fluffy&baz[]=4', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); + //=> {foo: ['1', '2', '3'], bar: 'fluffy', baz:['4']} + ``` + + - `colon-list-separator`: Parse arrays with parameter names that are explicitly marked with `:list`: + + ``` + import queryString = require('query-string'); + + queryString.parse('foo:list=one&foo:list=two', {arrayFormat: 'colon-list-separator'}); + //=> {foo: ['one', 'two']} + ``` + + - `none`: Parse arrays with elements using duplicate keys: + + ``` + import queryString = require('query-string'); + + queryString.parse('foo=1&foo=2&foo=3'); + //=> {foo: ['1', '2', '3']} + ``` + */ + readonly arrayFormat?: 'bracket' | 'index' | 'comma' | 'separator' | 'bracket-separator' | 'colon-list-separator' | 'none'; + + /** + The character used to separate array elements when using `{arrayFormat: 'separator'}`. + + @default , + */ + readonly arrayFormatSeparator?: string; + + /** + Supports both `Function` as a custom sorting function or `false` to disable sorting. + + If omitted, keys are sorted using `Array#sort`, which means, converting them to strings and comparing strings in Unicode code point order. + + @default true + + @example + ``` + import queryString = require('query-string'); + + const order = ['c', 'a', 'b']; + + queryString.parse('?a=one&b=two&c=three', { + sort: (itemLeft, itemRight) => order.indexOf(itemLeft) - order.indexOf(itemRight) + }); + //=> {c: 'three', a: 'one', b: 'two'} + ``` + + @example + ``` + import queryString = require('query-string'); + + queryString.parse('?a=one&c=three&b=two', {sort: false}); + //=> {a: 'one', c: 'three', b: 'two'} + ``` + */ + readonly sort?: ((itemLeft: string, itemRight: string) => number) | false; + + /** + Parse the value as a number type instead of string type if it's a number. + + @default false + + @example + ``` + import queryString = require('query-string'); + + queryString.parse('foo=1', {parseNumbers: true}); + //=> {foo: 1} + ``` + */ + readonly parseNumbers?: boolean; + + /** + Parse the value as a boolean type instead of string type if it's a boolean. + + @default false + + @example + ``` + import queryString = require('query-string'); + + queryString.parse('foo=true', {parseBooleans: true}); + //=> {foo: true} + ``` + */ + readonly parseBooleans?: boolean; + + /** + Parse the fragment identifier from the URL and add it to result object. + + @default false + + @example + ``` + import queryString = require('query-string'); + + queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true}); + //=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'} + ``` + */ + readonly parseFragmentIdentifier?: boolean; +} + +export interface ParsedQuery { + [key: string]: T | null | Array; +} + +/** +Parse a query string into an object. Leading `?` or `#` are ignored, so you can pass `location.search` or `location.hash` directly. + +The returned object is created with [`Object.create(null)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) and thus does not have a `prototype`. + +@param query - The query string to parse. +*/ +export function parse(query: string, options: {parseBooleans: true, parseNumbers: true} & ParseOptions): ParsedQuery; +export function parse(query: string, options: {parseBooleans: true} & ParseOptions): ParsedQuery; +export function parse(query: string, options: {parseNumbers: true} & ParseOptions): ParsedQuery; +export function parse(query: string, options?: ParseOptions): ParsedQuery; + +export interface ParsedUrl { + readonly url: string; + readonly query: ParsedQuery; + + /** + The fragment identifier of the URL. + + Present when the `parseFragmentIdentifier` option is `true`. + */ + readonly fragmentIdentifier?: string; +} + +/** +Extract the URL and the query string as an object. + +If the `parseFragmentIdentifier` option is `true`, the object will also contain a `fragmentIdentifier` property. + +@param url - The URL to parse. + +@example +``` +import queryString = require('query-string'); + +queryString.parseUrl('https://foo.bar?foo=bar'); +//=> {url: 'https://foo.bar', query: {foo: 'bar'}} + +queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true}); +//=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'} +``` +*/ +export function parseUrl(url: string, options?: ParseOptions): ParsedUrl; + +export interface StringifyOptions { + /** + Strictly encode URI components with [`strict-uri-encode`](https://github.com/kevva/strict-uri-encode). It uses [`encodeURIComponent`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) if set to `false`. You probably [don't care](https://github.com/sindresorhus/query-string/issues/42) about this option. + + @default true + */ + readonly strict?: boolean; + + /** + [URL encode](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) the keys and values. + + @default true + */ + readonly encode?: boolean; + + /** + @default 'none' + + - `bracket`: Serialize arrays using bracket representation: + + ``` + import queryString = require('query-string'); + + queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket'}); + //=> 'foo[]=1&foo[]=2&foo[]=3' + ``` + + - `index`: Serialize arrays using index representation: + + ``` + import queryString = require('query-string'); + + queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'index'}); + //=> 'foo[0]=1&foo[1]=2&foo[2]=3' + ``` + + - `comma`: Serialize arrays by separating elements with comma: + + ``` + import queryString = require('query-string'); + + queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'comma'}); + //=> 'foo=1,2,3' + + queryString.stringify({foo: [1, null, '']}, {arrayFormat: 'comma'}); + //=> 'foo=1,,' + // Note that typing information for null values is lost + // and `.parse('foo=1,,')` would return `{foo: [1, '', '']}`. + ``` + + - `separator`: Serialize arrays by separating elements with character: + + ``` + import queryString = require('query-string'); + + queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'separator', arrayFormatSeparator: '|'}); + //=> 'foo=1|2|3' + ``` + + - `bracket-separator`: Serialize arrays by explicitly post-fixing array names with brackets and separating elements with a custom character: + + ``` + import queryString = require('query-string'); + + queryString.stringify({foo: []}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); + //=> 'foo[]' + + queryString.stringify({foo: ['']}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); + //=> 'foo[]=' + + queryString.stringify({foo: [1]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); + //=> 'foo[]=1' + + queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); + //=> 'foo[]=1|2|3' + + queryString.stringify({foo: [1, '', 3, null, null, 6]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); + //=> 'foo[]=1||3|||6' + + queryString.stringify({foo: [1, '', 3, null, null, 6]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|', skipNull: true}); + //=> 'foo[]=1||3|6' + + queryString.stringify({foo: [1, 2, 3], bar: 'fluffy', baz: [4]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); + //=> 'foo[]=1|2|3&bar=fluffy&baz[]=4' + ``` + + - `colon-list-separator`: Serialize arrays with parameter names that are explicitly marked with `:list`: + + ```js + import queryString = require('query-string'); + + queryString.stringify({foo: ['one', 'two']}, {arrayFormat: 'colon-list-separator'}); + //=> 'foo:list=one&foo:list=two' + ``` + + - `none`: Serialize arrays by using duplicate keys: + + ``` + import queryString = require('query-string'); + + queryString.stringify({foo: [1, 2, 3]}); + //=> 'foo=1&foo=2&foo=3' + ``` + */ + readonly arrayFormat?: 'bracket' | 'index' | 'comma' | 'separator' | 'bracket-separator' | 'colon-list-separator' | 'none'; + + /** + The character used to separate array elements when using `{arrayFormat: 'separator'}`. + + @default , + */ + readonly arrayFormatSeparator?: string; + + /** + Supports both `Function` as a custom sorting function or `false` to disable sorting. + + If omitted, keys are sorted using `Array#sort`, which means, converting them to strings and comparing strings in Unicode code point order. + + @default true + + @example + ``` + import queryString = require('query-string'); + + const order = ['c', 'a', 'b']; + + queryString.stringify({a: 1, b: 2, c: 3}, { + sort: (itemLeft, itemRight) => order.indexOf(itemLeft) - order.indexOf(itemRight) + }); + //=> 'c=3&a=1&b=2' + ``` + + @example + ``` + import queryString = require('query-string'); + + queryString.stringify({b: 1, c: 2, a: 3}, {sort: false}); + //=> 'b=1&c=2&a=3' + ``` + */ + readonly sort?: ((itemLeft: string, itemRight: string) => number) | false; + + /** + Skip keys with `null` as the value. + + Note that keys with `undefined` as the value are always skipped. + + @default false + + @example + ``` + import queryString = require('query-string'); + + queryString.stringify({a: 1, b: undefined, c: null, d: 4}, { + skipNull: true + }); + //=> 'a=1&d=4' + + queryString.stringify({a: undefined, b: null}, { + skipNull: true + }); + //=> '' + ``` + */ + readonly skipNull?: boolean; + + /** + Skip keys with an empty string as the value. + + @default false + + @example + ``` + import queryString = require('query-string'); + + queryString.stringify({a: 1, b: '', c: '', d: 4}, { + skipEmptyString: true + }); + //=> 'a=1&d=4' + ``` + + @example + ``` + import queryString = require('query-string'); + + queryString.stringify({a: '', b: ''}, { + skipEmptyString: true + }); + //=> '' + ``` + */ + readonly skipEmptyString?: boolean; +} + +export type Stringifiable = string | boolean | number | null | undefined; + +export type StringifiableRecord = Record< + string, + Stringifiable | readonly Stringifiable[] +>; + +/** +Stringify an object into a query string and sort the keys. +*/ +export function stringify( + // TODO: Use the below instead when the following TS issues are fixed: + // - https://github.com/microsoft/TypeScript/issues/15300 + // - https://github.com/microsoft/TypeScript/issues/42021 + // Context: https://github.com/sindresorhus/query-string/issues/298 + // object: StringifiableRecord, + object: Record, + options?: StringifyOptions +): string; + +/** +Extract a query string from a URL that can be passed into `.parse()`. + +Note: This behaviour can be changed with the `skipNull` option. +*/ +export function extract(url: string): string; + +export interface UrlObject { + readonly url: string; + + /** + Overrides queries in the `url` property. + */ + readonly query?: StringifiableRecord; + + /** + Overrides the fragment identifier in the `url` property. + */ + readonly fragmentIdentifier?: string; +} + +/** +Stringify an object into a URL with a query string and sorting the keys. The inverse of [`.parseUrl()`](https://github.com/sindresorhus/query-string#parseurlstring-options) + +Query items in the `query` property overrides queries in the `url` property. + +The `fragmentIdentifier` property overrides the fragment identifier in the `url` property. + +@example +``` +queryString.stringifyUrl({url: 'https://foo.bar', query: {foo: 'bar'}}); +//=> 'https://foo.bar?foo=bar' + +queryString.stringifyUrl({url: 'https://foo.bar?foo=baz', query: {foo: 'bar'}}); +//=> 'https://foo.bar?foo=bar' + +queryString.stringifyUrl({ + url: 'https://foo.bar', + query: { + top: 'foo' + }, + fragmentIdentifier: 'bar' +}); +//=> 'https://foo.bar?top=foo#bar' +``` +*/ +export function stringifyUrl( + object: UrlObject, + options?: StringifyOptions +): string; + +/** +Pick query parameters from a URL. + +@param url - The URL containing the query parameters to pick. +@param keys - The names of the query parameters to keep. All other query parameters will be removed from the URL. +@param filter - A filter predicate that will be provided the name of each query parameter and its value. The `parseNumbers` and `parseBooleans` options also affect `value`. + +@returns The URL with the picked query parameters. + +@example +``` +queryString.pick('https://foo.bar?foo=1&bar=2#hello', ['foo']); +//=> 'https://foo.bar?foo=1#hello' + +queryString.pick('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true}); +//=> 'https://foo.bar?bar=2#hello' +``` +*/ +export function pick( + url: string, + keys: readonly string[], + options?: ParseOptions & StringifyOptions +): string +export function pick( + url: string, + filter: (key: string, value: string | boolean | number) => boolean, + options?: {parseBooleans: true, parseNumbers: true} & ParseOptions & StringifyOptions +): string +export function pick( + url: string, + filter: (key: string, value: string | boolean) => boolean, + options?: {parseBooleans: true} & ParseOptions & StringifyOptions +): string +export function pick( + url: string, + filter: (key: string, value: string | number) => boolean, + options?: {parseNumbers: true} & ParseOptions & StringifyOptions +): string + +/** +Exclude query parameters from a URL. Like `.pick()` but reversed. + +@param url - The URL containing the query parameters to exclude. +@param keys - The names of the query parameters to remove. All other query parameters will remain in the URL. +@param filter - A filter predicate that will be provided the name of each query parameter and its value. The `parseNumbers` and `parseBooleans` options also affect `value`. + +@returns The URL without the excluded the query parameters. + +@example +``` +queryString.exclude('https://foo.bar?foo=1&bar=2#hello', ['foo']); +//=> 'https://foo.bar?bar=2#hello' + +queryString.exclude('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true}); +//=> 'https://foo.bar?foo=1#hello' +``` +*/ +export function exclude( + url: string, + keys: readonly string[], + options?: ParseOptions & StringifyOptions +): string +export function exclude( + url: string, + filter: (key: string, value: string | boolean | number) => boolean, + options?: {parseBooleans: true, parseNumbers: true} & ParseOptions & StringifyOptions +): string +export function exclude( + url: string, + filter: (key: string, value: string | boolean) => boolean, + options?: {parseBooleans: true} & ParseOptions & StringifyOptions +): string +export function exclude( + url: string, + filter: (key: string, value: string | number) => boolean, + options?: {parseNumbers: true} & ParseOptions & StringifyOptions +): string diff --git a/node_modules/query-string/index.js b/node_modules/query-string/index.js new file mode 100644 index 0000000..d45e67d --- /dev/null +++ b/node_modules/query-string/index.js @@ -0,0 +1,482 @@ +'use strict'; +const strictUriEncode = require('strict-uri-encode'); +const decodeComponent = require('decode-uri-component'); +const splitOnFirst = require('split-on-first'); +const filterObject = require('filter-obj'); + +const isNullOrUndefined = value => value === null || value === undefined; + +const encodeFragmentIdentifier = Symbol('encodeFragmentIdentifier'); + +function encoderForArrayFormat(options) { + switch (options.arrayFormat) { + case 'index': + return key => (result, value) => { + const index = result.length; + + if ( + value === undefined || + (options.skipNull && value === null) || + (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [...result, [encode(key, options), '[', index, ']'].join('')]; + } + + return [ + ...result, + [encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join('') + ]; + }; + + case 'bracket': + return key => (result, value) => { + if ( + value === undefined || + (options.skipNull && value === null) || + (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [...result, [encode(key, options), '[]'].join('')]; + } + + return [...result, [encode(key, options), '[]=', encode(value, options)].join('')]; + }; + + case 'colon-list-separator': + return key => (result, value) => { + if ( + value === undefined || + (options.skipNull && value === null) || + (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [...result, [encode(key, options), ':list='].join('')]; + } + + return [...result, [encode(key, options), ':list=', encode(value, options)].join('')]; + }; + + case 'comma': + case 'separator': + case 'bracket-separator': { + const keyValueSep = options.arrayFormat === 'bracket-separator' ? + '[]=' : + '='; + + return key => (result, value) => { + if ( + value === undefined || + (options.skipNull && value === null) || + (options.skipEmptyString && value === '') + ) { + return result; + } + + // Translate null to an empty string so that it doesn't serialize as 'null' + value = value === null ? '' : value; + + if (result.length === 0) { + return [[encode(key, options), keyValueSep, encode(value, options)].join('')]; + } + + return [[result, encode(value, options)].join(options.arrayFormatSeparator)]; + }; + } + + default: + return key => (result, value) => { + if ( + value === undefined || + (options.skipNull && value === null) || + (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [...result, encode(key, options)]; + } + + return [...result, [encode(key, options), '=', encode(value, options)].join('')]; + }; + } +} + +function parserForArrayFormat(options) { + let result; + + switch (options.arrayFormat) { + case 'index': + return (key, value, accumulator) => { + result = /\[(\d*)\]$/.exec(key); + + key = key.replace(/\[\d*\]$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = {}; + } + + accumulator[key][result[1]] = value; + }; + + case 'bracket': + return (key, value, accumulator) => { + result = /(\[\])$/.exec(key); + key = key.replace(/\[\]$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = [value]; + return; + } + + accumulator[key] = [].concat(accumulator[key], value); + }; + + case 'colon-list-separator': + return (key, value, accumulator) => { + result = /(:list)$/.exec(key); + key = key.replace(/:list$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = [value]; + return; + } + + accumulator[key] = [].concat(accumulator[key], value); + }; + + case 'comma': + case 'separator': + return (key, value, accumulator) => { + const isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator); + const isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator)); + value = isEncodedArray ? decode(value, options) : value; + const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : value === null ? value : decode(value, options); + accumulator[key] = newValue; + }; + + case 'bracket-separator': + return (key, value, accumulator) => { + const isArray = /(\[\])$/.test(key); + key = key.replace(/\[\]$/, ''); + + if (!isArray) { + accumulator[key] = value ? decode(value, options) : value; + return; + } + + const arrayValue = value === null ? + [] : + value.split(options.arrayFormatSeparator).map(item => decode(item, options)); + + if (accumulator[key] === undefined) { + accumulator[key] = arrayValue; + return; + } + + accumulator[key] = [].concat(accumulator[key], arrayValue); + }; + + default: + return (key, value, accumulator) => { + if (accumulator[key] === undefined) { + accumulator[key] = value; + return; + } + + accumulator[key] = [].concat(accumulator[key], value); + }; + } +} + +function validateArrayFormatSeparator(value) { + if (typeof value !== 'string' || value.length !== 1) { + throw new TypeError('arrayFormatSeparator must be single character string'); + } +} + +function encode(value, options) { + if (options.encode) { + return options.strict ? strictUriEncode(value) : encodeURIComponent(value); + } + + return value; +} + +function decode(value, options) { + if (options.decode) { + return decodeComponent(value); + } + + return value; +} + +function keysSorter(input) { + if (Array.isArray(input)) { + return input.sort(); + } + + if (typeof input === 'object') { + return keysSorter(Object.keys(input)) + .sort((a, b) => Number(a) - Number(b)) + .map(key => input[key]); + } + + return input; +} + +function removeHash(input) { + const hashStart = input.indexOf('#'); + if (hashStart !== -1) { + input = input.slice(0, hashStart); + } + + return input; +} + +function getHash(url) { + let hash = ''; + const hashStart = url.indexOf('#'); + if (hashStart !== -1) { + hash = url.slice(hashStart); + } + + return hash; +} + +function extract(input) { + input = removeHash(input); + const queryStart = input.indexOf('?'); + if (queryStart === -1) { + return ''; + } + + return input.slice(queryStart + 1); +} + +function parseValue(value, options) { + if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) { + value = Number(value); + } else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) { + value = value.toLowerCase() === 'true'; + } + + return value; +} + +function parse(query, options) { + options = Object.assign({ + decode: true, + sort: true, + arrayFormat: 'none', + arrayFormatSeparator: ',', + parseNumbers: false, + parseBooleans: false + }, options); + + validateArrayFormatSeparator(options.arrayFormatSeparator); + + const formatter = parserForArrayFormat(options); + + // Create an object with no prototype + const ret = Object.create(null); + + if (typeof query !== 'string') { + return ret; + } + + query = query.trim().replace(/^[?#&]/, ''); + + if (!query) { + return ret; + } + + for (const param of query.split('&')) { + if (param === '') { + continue; + } + + let [key, value] = splitOnFirst(options.decode ? param.replace(/\+/g, ' ') : param, '='); + + // Missing `=` should be `null`: + // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters + value = value === undefined ? null : ['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options); + formatter(decode(key, options), value, ret); + } + + for (const key of Object.keys(ret)) { + const value = ret[key]; + if (typeof value === 'object' && value !== null) { + for (const k of Object.keys(value)) { + value[k] = parseValue(value[k], options); + } + } else { + ret[key] = parseValue(value, options); + } + } + + if (options.sort === false) { + return ret; + } + + return (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => { + const value = ret[key]; + if (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) { + // Sort object keys, not values + result[key] = keysSorter(value); + } else { + result[key] = value; + } + + return result; + }, Object.create(null)); +} + +exports.extract = extract; +exports.parse = parse; + +exports.stringify = (object, options) => { + if (!object) { + return ''; + } + + options = Object.assign({ + encode: true, + strict: true, + arrayFormat: 'none', + arrayFormatSeparator: ',' + }, options); + + validateArrayFormatSeparator(options.arrayFormatSeparator); + + const shouldFilter = key => ( + (options.skipNull && isNullOrUndefined(object[key])) || + (options.skipEmptyString && object[key] === '') + ); + + const formatter = encoderForArrayFormat(options); + + const objectCopy = {}; + + for (const key of Object.keys(object)) { + if (!shouldFilter(key)) { + objectCopy[key] = object[key]; + } + } + + const keys = Object.keys(objectCopy); + + if (options.sort !== false) { + keys.sort(options.sort); + } + + return keys.map(key => { + const value = object[key]; + + if (value === undefined) { + return ''; + } + + if (value === null) { + return encode(key, options); + } + + if (Array.isArray(value)) { + if (value.length === 0 && options.arrayFormat === 'bracket-separator') { + return encode(key, options) + '[]'; + } + + return value + .reduce(formatter(key), []) + .join('&'); + } + + return encode(key, options) + '=' + encode(value, options); + }).filter(x => x.length > 0).join('&'); +}; + +exports.parseUrl = (url, options) => { + options = Object.assign({ + decode: true + }, options); + + const [url_, hash] = splitOnFirst(url, '#'); + + return Object.assign( + { + url: url_.split('?')[0] || '', + query: parse(extract(url), options) + }, + options && options.parseFragmentIdentifier && hash ? {fragmentIdentifier: decode(hash, options)} : {} + ); +}; + +exports.stringifyUrl = (object, options) => { + options = Object.assign({ + encode: true, + strict: true, + [encodeFragmentIdentifier]: true + }, options); + + const url = removeHash(object.url).split('?')[0] || ''; + const queryFromUrl = exports.extract(object.url); + const parsedQueryFromUrl = exports.parse(queryFromUrl, {sort: false}); + + const query = Object.assign(parsedQueryFromUrl, object.query); + let queryString = exports.stringify(query, options); + if (queryString) { + queryString = `?${queryString}`; + } + + let hash = getHash(object.url); + if (object.fragmentIdentifier) { + hash = `#${options[encodeFragmentIdentifier] ? encode(object.fragmentIdentifier, options) : object.fragmentIdentifier}`; + } + + return `${url}${queryString}${hash}`; +}; + +exports.pick = (input, filter, options) => { + options = Object.assign({ + parseFragmentIdentifier: true, + [encodeFragmentIdentifier]: false + }, options); + + const {url, query, fragmentIdentifier} = exports.parseUrl(input, options); + return exports.stringifyUrl({ + url, + query: filterObject(query, filter), + fragmentIdentifier + }, options); +}; + +exports.exclude = (input, filter, options) => { + const exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value); + + return exports.pick(input, exclusionFilter, options); +}; diff --git a/node_modules/query-string/license b/node_modules/query-string/license new file mode 100644 index 0000000..e464bf7 --- /dev/null +++ b/node_modules/query-string/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (http://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/query-string/package.json b/node_modules/query-string/package.json new file mode 100644 index 0000000..d87d6df --- /dev/null +++ b/node_modules/query-string/package.json @@ -0,0 +1,54 @@ +{ + "name": "query-string", + "version": "7.1.3", + "description": "Parse and stringify URL query strings", + "license": "MIT", + "repository": "sindresorhus/query-string", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "benchmark": "node benchmark.js", + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "browser", + "querystring", + "query", + "string", + "qs", + "param", + "parameter", + "url", + "parse", + "stringify", + "encode", + "decode", + "searchparams", + "filter" + ], + "dependencies": { + "decode-uri-component": "^0.2.2", + "filter-obj": "^1.1.0", + "split-on-first": "^1.0.0", + "strict-uri-encode": "^2.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "benchmark": "^2.1.4", + "deep-equal": "^1.0.1", + "fast-check": "^1.5.0", + "tsd": "^0.7.3", + "xo": "^0.24.0" + } +} diff --git a/node_modules/query-string/readme.md b/node_modules/query-string/readme.md new file mode 100644 index 0000000..5721ca0 --- /dev/null +++ b/node_modules/query-string/readme.md @@ -0,0 +1,639 @@ +# query-string + +> Parse and stringify URL [query strings](https://en.wikipedia.org/wiki/Query_string) + +
+ +--- + +
+ +--- + +
+ +## Install + +``` +$ npm install query-string +``` + +**Not `npm install querystring`!!!!!** + +This module targets Node.js 6 or later and the latest version of Chrome, Firefox, and Safari. + +## Usage + +```js +const queryString = require('query-string'); + +console.log(location.search); +//=> '?foo=bar' + +const parsed = queryString.parse(location.search); +console.log(parsed); +//=> {foo: 'bar'} + +console.log(location.hash); +//=> '#token=bada55cafe' + +const parsedHash = queryString.parse(location.hash); +console.log(parsedHash); +//=> {token: 'bada55cafe'} + +parsed.foo = 'unicorn'; +parsed.ilike = 'pizza'; + +const stringified = queryString.stringify(parsed); +//=> 'foo=unicorn&ilike=pizza' + +location.search = stringified; +// note that `location.search` automatically prepends a question mark +console.log(location.search); +//=> '?foo=unicorn&ilike=pizza' +``` + +## API + +### .parse(string, options?) + +Parse a query string into an object. Leading `?` or `#` are ignored, so you can pass `location.search` or `location.hash` directly. + +The returned object is created with [`Object.create(null)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) and thus does not have a `prototype`. + +#### options + +Type: `object` + +##### decode + +Type: `boolean`\ +Default: `true` + +Decode the keys and values. URL components are decoded with [`decode-uri-component`](https://github.com/SamVerschueren/decode-uri-component). + +##### arrayFormat + +Type: `string`\ +Default: `'none'` + +- `'bracket'`: Parse arrays with bracket representation: + +```js +const queryString = require('query-string'); + +queryString.parse('foo[]=1&foo[]=2&foo[]=3', {arrayFormat: 'bracket'}); +//=> {foo: ['1', '2', '3']} +``` + +- `'index'`: Parse arrays with index representation: + +```js +const queryString = require('query-string'); + +queryString.parse('foo[0]=1&foo[1]=2&foo[3]=3', {arrayFormat: 'index'}); +//=> {foo: ['1', '2', '3']} +``` + +- `'comma'`: Parse arrays with elements separated by comma: + +```js +const queryString = require('query-string'); + +queryString.parse('foo=1,2,3', {arrayFormat: 'comma'}); +//=> {foo: ['1', '2', '3']} +``` + +- `'separator'`: Parse arrays with elements separated by a custom character: + +```js +const queryString = require('query-string'); + +queryString.parse('foo=1|2|3', {arrayFormat: 'separator', arrayFormatSeparator: '|'}); +//=> {foo: ['1', '2', '3']} +``` + +- `'bracket-separator'`: Parse arrays (that are explicitly marked with brackets) with elements separated by a custom character: + +```js +const queryString = require('query-string'); + +queryString.parse('foo[]', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); +//=> {foo: []} + +queryString.parse('foo[]=', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); +//=> {foo: ['']} + +queryString.parse('foo[]=1', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); +//=> {foo: ['1']} + +queryString.parse('foo[]=1|2|3', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); +//=> {foo: ['1', '2', '3']} + +queryString.parse('foo[]=1||3|||6', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); +//=> {foo: ['1', '', 3, '', '', '6']} + +queryString.parse('foo[]=1|2|3&bar=fluffy&baz[]=4', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); +//=> {foo: ['1', '2', '3'], bar: 'fluffy', baz:['4']} +``` + +- `'colon-list-separator'`: Parse arrays with parameter names that are explicitly marked with `:list`: + +```js +const queryString = require('query-string'); + +queryString.parse('foo:list=one&foo:list=two', {arrayFormat: 'colon-list-separator'}); +//=> {foo: ['one', 'two']} +``` + +- `'none'`: Parse arrays with elements using duplicate keys: + +```js +const queryString = require('query-string'); + +queryString.parse('foo=1&foo=2&foo=3'); +//=> {foo: ['1', '2', '3']} +``` + +##### arrayFormatSeparator + +Type: `string`\ +Default: `','` + +The character used to separate array elements when using `{arrayFormat: 'separator'}`. + +##### sort + +Type: `Function | boolean`\ +Default: `true` + +Supports both `Function` as a custom sorting function or `false` to disable sorting. + +##### parseNumbers + +Type: `boolean`\ +Default: `false` + +```js +const queryString = require('query-string'); + +queryString.parse('foo=1', {parseNumbers: true}); +//=> {foo: 1} +``` + +Parse the value as a number type instead of string type if it's a number. + +##### parseBooleans + +Type: `boolean`\ +Default: `false` + +```js +const queryString = require('query-string'); + +queryString.parse('foo=true', {parseBooleans: true}); +//=> {foo: true} +``` + +Parse the value as a boolean type instead of string type if it's a boolean. + +### .stringify(object, options?) + +Stringify an object into a query string and sorting the keys. + +#### options + +Type: `object` + +##### strict + +Type: `boolean`\ +Default: `true` + +Strictly encode URI components with [strict-uri-encode](https://github.com/kevva/strict-uri-encode). It uses [encodeURIComponent](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) if set to false. You probably [don't care](https://github.com/sindresorhus/query-string/issues/42) about this option. + +##### encode + +Type: `boolean`\ +Default: `true` + +[URL encode](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) the keys and values. + +##### arrayFormat + +Type: `string`\ +Default: `'none'` + +- `'bracket'`: Serialize arrays using bracket representation: + +```js +const queryString = require('query-string'); + +queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket'}); +//=> 'foo[]=1&foo[]=2&foo[]=3' +``` + +- `'index'`: Serialize arrays using index representation: + +```js +const queryString = require('query-string'); + +queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'index'}); +//=> 'foo[0]=1&foo[1]=2&foo[2]=3' +``` + +- `'comma'`: Serialize arrays by separating elements with comma: + +```js +const queryString = require('query-string'); + +queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'comma'}); +//=> 'foo=1,2,3' + +queryString.stringify({foo: [1, null, '']}, {arrayFormat: 'comma'}); +//=> 'foo=1,,' +// Note that typing information for null values is lost +// and `.parse('foo=1,,')` would return `{foo: [1, '', '']}`. +``` + +- `'separator'`: Serialize arrays by separating elements with a custom character: + +```js +const queryString = require('query-string'); + +queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'separator', arrayFormatSeparator: '|'}); +//=> 'foo=1|2|3' +``` + +- `'bracket-separator'`: Serialize arrays by explicitly post-fixing array names with brackets and separating elements with a custom character: + +```js +const queryString = require('query-string'); + +queryString.stringify({foo: []}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); +//=> 'foo[]' + +queryString.stringify({foo: ['']}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); +//=> 'foo[]=' + +queryString.stringify({foo: [1]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); +//=> 'foo[]=1' + +queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); +//=> 'foo[]=1|2|3' + +queryString.stringify({foo: [1, '', 3, null, null, 6]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); +//=> 'foo[]=1||3|||6' + +queryString.stringify({foo: [1, '', 3, null, null, 6]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|', skipNull: true}); +//=> 'foo[]=1||3|6' + +queryString.stringify({foo: [1, 2, 3], bar: 'fluffy', baz: [4]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); +//=> 'foo[]=1|2|3&bar=fluffy&baz[]=4' +``` + +- `'colon-list-separator'`: Serialize arrays with parameter names that are explicitly marked with `:list`: + +```js +const queryString = require('query-string'); + +queryString.stringify({foo: ['one', 'two']}, {arrayFormat: 'colon-list-separator'}); +//=> 'foo:list=one&foo:list=two' +``` + +- `'none'`: Serialize arrays by using duplicate keys: + +```js +const queryString = require('query-string'); + +queryString.stringify({foo: [1, 2, 3]}); +//=> 'foo=1&foo=2&foo=3' +``` + +##### arrayFormatSeparator + +Type: `string`\ +Default: `','` + +The character used to separate array elements when using `{arrayFormat: 'separator'}`. + +##### sort + +Type: `Function | boolean` + +Supports both `Function` as a custom sorting function or `false` to disable sorting. + +```js +const queryString = require('query-string'); + +const order = ['c', 'a', 'b']; + +queryString.stringify({a: 1, b: 2, c: 3}, { + sort: (a, b) => order.indexOf(a) - order.indexOf(b) +}); +//=> 'c=3&a=1&b=2' +``` + +```js +const queryString = require('query-string'); + +queryString.stringify({b: 1, c: 2, a: 3}, {sort: false}); +//=> 'b=1&c=2&a=3' +``` + +If omitted, keys are sorted using `Array#sort()`, which means, converting them to strings and comparing strings in Unicode code point order. + +##### skipNull + +Skip keys with `null` as the value. + +Note that keys with `undefined` as the value are always skipped. + +Type: `boolean`\ +Default: `false` + +```js +const queryString = require('query-string'); + +queryString.stringify({a: 1, b: undefined, c: null, d: 4}, { + skipNull: true +}); +//=> 'a=1&d=4' +``` + +```js +const queryString = require('query-string'); + +queryString.stringify({a: undefined, b: null}, { + skipNull: true +}); +//=> '' +``` + +##### skipEmptyString + +Skip keys with an empty string as the value. + +Type: `boolean`\ +Default: `false` + +```js +const queryString = require('query-string'); + +queryString.stringify({a: 1, b: '', c: '', d: 4}, { + skipEmptyString: true +}); +//=> 'a=1&d=4' +``` + +```js +const queryString = require('query-string'); + +queryString.stringify({a: '', b: ''}, { + skipEmptyString: true +}); +//=> '' +``` + +### .extract(string) + +Extract a query string from a URL that can be passed into `.parse()`. + +Note: This behaviour can be changed with the `skipNull` option. + +### .parseUrl(string, options?) + +Extract the URL and the query string as an object. + +Returns an object with a `url` and `query` property. + +If the `parseFragmentIdentifier` option is `true`, the object will also contain a `fragmentIdentifier` property. + +```js +const queryString = require('query-string'); + +queryString.parseUrl('https://foo.bar?foo=bar'); +//=> {url: 'https://foo.bar', query: {foo: 'bar'}} + +queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true}); +//=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'} +``` + +#### options + +Type: `object` + +The options are the same as for `.parse()`. + +Extra options are as below. + +##### parseFragmentIdentifier + +Parse the fragment identifier from the URL. + +Type: `boolean`\ +Default: `false` + +```js +const queryString = require('query-string'); + +queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true}); +//=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'} +``` + +### .stringifyUrl(object, options?) + +Stringify an object into a URL with a query string and sorting the keys. The inverse of [`.parseUrl()`](https://github.com/sindresorhus/query-string#parseurlstring-options) + +The `options` are the same as for `.stringify()`. + +Returns a string with the URL and a query string. + +Query items in the `query` property overrides queries in the `url` property. + +The `fragmentIdentifier` property overrides the fragment identifier in the `url` property. + +```js +queryString.stringifyUrl({url: 'https://foo.bar', query: {foo: 'bar'}}); +//=> 'https://foo.bar?foo=bar' + +queryString.stringifyUrl({url: 'https://foo.bar?foo=baz', query: {foo: 'bar'}}); +//=> 'https://foo.bar?foo=bar' + +queryString.stringifyUrl({ + url: 'https://foo.bar', + query: { + top: 'foo' + }, + fragmentIdentifier: 'bar' +}); +//=> 'https://foo.bar?top=foo#bar' +``` + +#### object + +Type: `object` + +##### url + +Type: `string` + +The URL to stringify. + +##### query + +Type: `object` + +Query items to add to the URL. + +### .pick(url, keys, options?) +### .pick(url, filter, options?) + +Pick query parameters from a URL. + +Returns a string with the new URL. + +```js +const queryString = require('query-string'); + +queryString.pick('https://foo.bar?foo=1&bar=2#hello', ['foo']); +//=> 'https://foo.bar?foo=1#hello' + +queryString.pick('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true}); +//=> 'https://foo.bar?bar=2#hello' +``` + +### .exclude(url, keys, options?) +### .exclude(url, filter, options?) + +Exclude query parameters from a URL. + +Returns a string with the new URL. + +```js +const queryString = require('query-string'); + +queryString.exclude('https://foo.bar?foo=1&bar=2#hello', ['foo']); +//=> 'https://foo.bar?bar=2#hello' + +queryString.exclude('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true}); +//=> 'https://foo.bar?foo=1#hello' +``` + +#### url + +Type: `string` + +The URL containing the query parameters to filter. + +#### keys + +Type: `string[]` + +The names of the query parameters to filter based on the function used. + +#### filter + +Type: `(key, value) => boolean` + +A filter predicate that will be provided the name of each query parameter and its value. The `parseNumbers` and `parseBooleans` options also affect `value`. + +#### options + +Type: `object` + +[Parse options](#options) and [stringify options](#options-1). + +## Nesting + +This module intentionally doesn't support nesting as it's not spec'd and varies between implementations, which causes a lot of [edge cases](https://github.com/visionmedia/node-querystring/issues). + +You're much better off just converting the object to a JSON string: + +```js +const queryString = require('query-string'); + +queryString.stringify({ + foo: 'bar', + nested: JSON.stringify({ + unicorn: 'cake' + }) +}); +//=> 'foo=bar&nested=%7B%22unicorn%22%3A%22cake%22%7D' +``` + +However, there is support for multiple instances of the same key: + +```js +const queryString = require('query-string'); + +queryString.parse('likes=cake&name=bob&likes=icecream'); +//=> {likes: ['cake', 'icecream'], name: 'bob'} + +queryString.stringify({color: ['taupe', 'chartreuse'], id: '515'}); +//=> 'color=taupe&color=chartreuse&id=515' +``` + +## Falsy values + +Sometimes you want to unset a key, or maybe just make it present without assigning a value to it. Here is how falsy values are stringified: + +```js +const queryString = require('query-string'); + +queryString.stringify({foo: false}); +//=> 'foo=false' + +queryString.stringify({foo: null}); +//=> 'foo' + +queryString.stringify({foo: undefined}); +//=> '' +``` + +## FAQ + +### Why is it parsing `+` as a space? + +See [this answer](https://github.com/sindresorhus/query-string/issues/305). + +## query-string for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of query-string and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-query-string?utm_source=npm-query-string&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/readable-stream/CONTRIBUTING.md b/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 0000000..f478d58 --- /dev/null +++ b/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/node_modules/readable-stream/GOVERNANCE.md b/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 0000000..16ffb93 --- /dev/null +++ b/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/node_modules/readable-stream/LICENSE b/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..2873b3b --- /dev/null +++ b/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" diff --git a/node_modules/readable-stream/README.md b/node_modules/readable-stream/README.md new file mode 100644 index 0000000..19117c1 --- /dev/null +++ b/node_modules/readable-stream/README.md @@ -0,0 +1,106 @@ +# readable-stream + +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) + +```bash +npm install --save readable-stream +``` + +This package is a mirror of the streams implementations in Node.js. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.18.1/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 3.x.x + +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. + +### Big Thanks + +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +```` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> + +[sauce]: https://saucelabs.com diff --git a/node_modules/readable-stream/errors-browser.js b/node_modules/readable-stream/errors-browser.js new file mode 100644 index 0000000..fb8e73e --- /dev/null +++ b/node_modules/readable-stream/errors-browser.js @@ -0,0 +1,127 @@ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; diff --git a/node_modules/readable-stream/errors.js b/node_modules/readable-stream/errors.js new file mode 100644 index 0000000..8471526 --- /dev/null +++ b/node_modules/readable-stream/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/node_modules/readable-stream/experimentalWarning.js b/node_modules/readable-stream/experimentalWarning.js new file mode 100644 index 0000000..78e8414 --- /dev/null +++ b/node_modules/readable-stream/experimentalWarning.js @@ -0,0 +1,17 @@ +'use strict' + +var experimentalWarnings = new Set(); + +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} + +function noop() {} + +module.exports.emitExperimentalWarning = process.emitWarning + ? emitExperimentalWarning + : noop; diff --git a/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..19abfa6 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,126 @@ +// Copyright Joyent, Inc. and other Node 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. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); +require('inherits')(Duplex, Readable); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} +function onEndNT(self) { + self.end(); +} +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..24a6bdd --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node 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. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; +var Transform = require('./_stream_transform'); +require('inherits')(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..df1f608 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1027 @@ +// Copyright Joyent, Inc. and other Node 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. + +'use strict'; + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ +var debugUtil = require('util'); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = require('./internal/streams/buffer_list'); +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + +// Lazy loaded to improve the startup performance. +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; +require('inherits')(Readable, Stream); +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; + +// Don't raise the hwm > 1GB +var MAX_HWM = 0x40000000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit('data', ret); + return ret; +}; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; +}; +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; +}; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} +function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState.paused = true; + return this; +}; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; +}; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); + } + return createReadableStreamAsyncIterator(this); + }; +} +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = require('./internal/streams/from'); + } + return from(Readable, iterable, opts); + }; +} +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..1ccb715 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,190 @@ +// Copyright Joyent, Inc. and other Node 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. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; +var Duplex = require('./_stream_duplex'); +require('inherits')(Transform, Duplex); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} +function prefinish() { + var _this = this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..292415e --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,641 @@ +// Copyright Joyent, Inc. and other Node 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. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +var errorOrDestroy = destroyImpl.errorOrDestroy; +require('inherits')(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; +} +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; +Writable.prototype._writev = null; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + return this; +}; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; +} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/node_modules/readable-stream/lib/internal/streams/async_iterator.js new file mode 100644 index 0000000..742c5a4 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/async_iterator.js @@ -0,0 +1,180 @@ +'use strict'; + +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = require('./end-of-stream'); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 0000000..69bda49 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,183 @@ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = require('buffer'), + Buffer = _require.Buffer; +var _require2 = require('util'), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/destroy.js b/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 0000000..31a17c4 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,96 @@ +'use strict'; + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; +} +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} +function emitErrorNT(self, err) { + self.emit('error', err); +} +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 0000000..59c671b --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; +} +function noop() {} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} +module.exports = eos; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/from-browser.js b/node_modules/readable-stream/lib/internal/streams/from-browser.js new file mode 100644 index 0000000..a4ce56f --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/from-browser.js @@ -0,0 +1,3 @@ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; diff --git a/node_modules/readable-stream/lib/internal/streams/from.js b/node_modules/readable-stream/lib/internal/streams/from.js new file mode 100644 index 0000000..0a34ee9 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/from.js @@ -0,0 +1,52 @@ +'use strict'; + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; +function from(Readable, iterable, opts) { + var iterator; + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); + // Reading boolean to protect against _read + // being called before last iteration completion. + var reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), + value = _yield$iterator$next.value, + done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + return readable; +} +module.exports = from; diff --git a/node_modules/readable-stream/lib/internal/streams/pipeline.js b/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 0000000..e6f3924 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} +module.exports = pipeline; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/state.js b/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 0000000..3fbf892 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,22 @@ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 0000000..9332a3f --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/node_modules/readable-stream/lib/internal/streams/stream.js b/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 0000000..ce2ad5b --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/node_modules/readable-stream/package.json b/node_modules/readable-stream/package.json new file mode 100644 index 0000000..ade59e7 --- /dev/null +++ b/node_modules/readable-stream/package.json @@ -0,0 +1,68 @@ +{ + "name": "readable-stream", + "version": "3.6.2", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "engines": { + "node": ">= 6" + }, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "devDependencies": { + "@babel/cli": "^7.2.0", + "@babel/core": "^7.2.0", + "@babel/polyfill": "^7.0.0", + "@babel/preset-env": "^7.2.0", + "airtap": "0.0.9", + "assert": "^1.4.0", + "bl": "^2.0.0", + "deep-strict-equal": "^0.2.0", + "events.once": "^2.0.2", + "glob": "^7.1.2", + "gunzip-maybe": "^1.4.1", + "hyperquest": "^2.1.3", + "lolex": "^2.6.0", + "nyc": "^11.0.0", + "pump": "^3.0.0", + "rimraf": "^2.6.2", + "tap": "^12.0.0", + "tape": "^4.9.0", + "tar-fs": "^1.16.2", + "util-promisify": "^2.1.0" + }, + "scripts": { + "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js", + "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", + "test-browser-local": "airtap --open --local -- test/browser.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "update-browser-errors": "babel -o errors-browser.js errors.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false, + "worker_threads": false, + "./errors": "./errors-browser.js", + "./readable.js": "./readable-browser.js", + "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT" +} diff --git a/node_modules/readable-stream/readable-browser.js b/node_modules/readable-stream/readable-browser.js new file mode 100644 index 0000000..adbf60d --- /dev/null +++ b/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,9 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); +exports.finished = require('./lib/internal/streams/end-of-stream.js'); +exports.pipeline = require('./lib/internal/streams/pipeline.js'); diff --git a/node_modules/readable-stream/readable.js b/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..9e0ca12 --- /dev/null +++ b/node_modules/readable-stream/readable.js @@ -0,0 +1,16 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} diff --git a/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/safe-buffer/README.md b/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/safe-buffer/index.d.ts b/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/safe-buffer/index.js b/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..f8d3ec9 --- /dev/null +++ b/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/safe-buffer/package.json b/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..f2869e2 --- /dev/null +++ b/node_modules/safe-buffer/package.json @@ -0,0 +1,51 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/sax/LICENSE.md b/node_modules/sax/LICENSE.md new file mode 100644 index 0000000..c5402b9 --- /dev/null +++ b/node_modules/sax/LICENSE.md @@ -0,0 +1,55 @@ +# Blue Oak Model License + +Version 1.0.0 + +## Purpose + +This license gives everyone as much permission to work with +this software as possible, while protecting contributors +from liability. + +## Acceptance + +In order to receive this license, you must agree to its +rules. The rules of this license are both obligations +under that agreement and conditions to your license. +You must not do anything with this software that triggers +a rule that you cannot or will not follow. + +## Copyright + +Each contributor licenses you to do everything with this +software that would otherwise infringe that contributor's +copyright in it. + +## Notices + +You must ensure that everyone who gets a copy of +any part of this software from you, with or without +changes, also gets the text of this license or a link to +. + +## Excuse + +If anyone notifies you in writing that you have not +complied with [Notices](#notices), you can keep your +license by taking all practical steps to comply within 30 +days after the notice. If you do not do so, your license +ends immediately. + +## Patent + +Each contributor licenses you to do everything with this +software that would otherwise infringe any patent claims +they can license or become able to license. + +## Reliability + +No contributor can revoke this license. + +## No Liability + +***As far as the law allows, this software comes as is, +without any warranty or condition, and no contributor +will be liable to anyone for any damages related to this +software or this license, under any kind of legal claim.*** diff --git a/node_modules/sax/README.md b/node_modules/sax/README.md new file mode 100644 index 0000000..682d207 --- /dev/null +++ b/node_modules/sax/README.md @@ -0,0 +1,227 @@ +# sax js + +A sax-style parser for XML and HTML. + +Designed with [node](http://nodejs.org/) in mind, but should work fine in +the browser or other CommonJS implementations. + +## What This Is + +- A very simple tool to parse through an XML string. +- A stepping stone to a streaming HTML parser. +- A handy way to deal with RSS and other mostly-ok-but-kinda-broken XML + docs. + +## What This Is (probably) Not + +- An HTML Parser - That's a fine goal, but this isn't it. It's just + XML. +- A DOM Builder - You can use it to build an object model out of XML, + but it doesn't do that out of the box. +- XSLT - No DOM = no querying. +- 100% Compliant with (some other SAX implementation) - Most SAX + implementations are in Java and do a lot more than this does. +- An XML Validator - It does a little validation when in strict mode, but + not much. +- A Schema-Aware XSD Thing - Schemas are an exercise in fetishistic + masochism. +- A DTD-aware Thing - Fetching DTDs is a much bigger job. + +## Regarding `Hello, world!').close() + +// stream usage +// takes the same options as the parser +var saxStream = require('sax').createStream(strict, options) +saxStream.on('error', function (e) { + // unhandled errors will throw, since this is a proper node + // event emitter. + console.error('error!', e) + // clear the error + this._parser.error = null + this._parser.resume() +}) +saxStream.on('opentag', function (node) { + // same object as above +}) +// pipe is supported, and it's readable/writable +// same chunks coming in also go out. +fs.createReadStream('file.xml') + .pipe(saxStream) + .pipe(fs.createWriteStream('file-copy.xml')) +``` + +## Arguments + +Pass the following arguments to the parser function. All are optional. + +`strict` - Boolean. Whether or not to be a jerk. Default: `false`. + +`opt` - Object bag of settings regarding string formatting. All default to `false`. + +Settings supported: + +- `trim` - Boolean. Whether or not to trim text and comment nodes. +- `normalize` - Boolean. If true, then turn any whitespace into a single + space. +- `lowercase` - Boolean. If true, then lowercase tag names and attribute names + in loose mode, rather than uppercasing them. +- `xmlns` - Boolean. If true, then namespaces are supported. +- `position` - Boolean. If false, then don't track line/col/position. +- `strictEntities` - Boolean. If true, only parse [predefined XML + entities](http://www.w3.org/TR/REC-xml/#sec-predefined-ent) + (`&`, `'`, `>`, `<`, and `"`) +- `unquotedAttributeValues` - Boolean. If true, then unquoted + attribute values are allowed. Defaults to `false` when `strict` + is true, `true` otherwise. + +## Methods + +`write` - Write bytes onto the stream. You don't have to do this all at +once. You can keep writing as much as you want. + +`close` - Close the stream. Once closed, no more data may be written until +it is done processing the buffer, which is signaled by the `end` event. + +`resume` - To gracefully handle errors, assign a listener to the `error` +event. Then, when the error is taken care of, you can call `resume` to +continue parsing. Otherwise, the parser will not continue while in an error +state. + +## Members + +At all times, the parser object will have the following members: + +`line`, `column`, `position` - Indications of the position in the XML +document where the parser currently is looking. + +`startTagPosition` - Indicates the position where the current tag starts. + +`closed` - Boolean indicating whether or not the parser can be written to. +If it's `true`, then wait for the `ready` event to write again. + +`strict` - Boolean indicating whether or not the parser is a jerk. + +`opt` - Any options passed into the constructor. + +`tag` - The current tag being dealt with. + +And a bunch of other stuff that you probably shouldn't touch. + +## Events + +All events emit with a single argument. To listen to an event, assign a +function to `on`. Functions get executed in the this-context of +the parser object. The list of supported events are also in the exported +`EVENTS` array. + +When using the stream interface, assign handlers using the EventEmitter +`on` function in the normal fashion. + +`error` - Indication that something bad happened. The error will be hanging +out on `parser.error`, and must be deleted before parsing can continue. By +listening to this event, you can keep an eye on that kind of stuff. Note: +this happens _much_ more in strict mode. Argument: instance of `Error`. + +`text` - Text node. Argument: string of text. + +`doctype` - The ``. Argument: +object with `name` and `body` members. Attributes are not parsed, as +processing instructions have implementation dependent semantics. + +`sgmldeclaration` - Random SGML declarations. Stuff like `` +would trigger this kind of event. This is a weird thing to support, so it +might go away at some point. SAX isn't intended to be used to parse SGML, +after all. + +`opentagstart` - Emitted immediately when the tag name is available, +but before any attributes are encountered. Argument: object with a +`name` field and an empty `attributes` set. Note that this is the +same object that will later be emitted in the `opentag` event. + +`opentag` - An opening tag. Argument: object with `name` and `attributes`. +In non-strict mode, tag names are uppercased, unless the `lowercase` +option is set. If the `xmlns` option is set, then it will contain +namespace binding information on the `ns` member, and will have a +`local`, `prefix`, and `uri` member. + +`closetag` - A closing tag. In loose mode, tags are auto-closed if their +parent closes. In strict mode, well-formedness is enforced. Note that +self-closing tags will have `closeTag` emitted immediately after `openTag`. +Argument: tag name. + +`attribute` - An attribute node. Argument: object with `name` and `value`. +In non-strict mode, attribute names are uppercased, unless the `lowercase` +option is set. If the `xmlns` option is set, it will also contains namespace +information. + +`comment` - A comment node. Argument: the string of the comment. + +`opencdata` - The opening tag of a ``) of a `` tags trigger a `"script"` +event, and their contents are not checked for special xml characters. +If you pass `noscript: true`, then this behavior is suppressed. + +## Reporting Problems + +It's best to write a failing test if you find an issue. I will always +accept pull requests with failing tests if they demonstrate intended +behavior, but it is very hard to figure out what issue you're describing +without a test. Writing a test is also the best way for you yourself +to figure out if you really understand the issue you think you have with +sax-js. diff --git a/node_modules/sax/lib/sax.js b/node_modules/sax/lib/sax.js new file mode 100644 index 0000000..1fc8eb6 --- /dev/null +++ b/node_modules/sax/lib/sax.js @@ -0,0 +1,1848 @@ +;(function (sax) { + // wrapper for non-node envs + sax.parser = function (strict, opt) { + return new SAXParser(strict, opt) + } + sax.SAXParser = SAXParser + sax.SAXStream = SAXStream + sax.createStream = createStream + + // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns. + // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)), + // since that's the earliest that a buffer overrun could occur. This way, checks are + // as rare as required, but as often as necessary to ensure never crossing this bound. + // Furthermore, buffers are only tested at most once per write(), so passing a very + // large string into write() might have undesirable effects, but this is manageable by + // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme + // edge case, result in creating at most one complete copy of the string passed in. + // Set to Infinity to have unlimited buffers. + sax.MAX_BUFFER_LENGTH = 64 * 1024 + + var buffers = [ + 'comment', + 'sgmlDecl', + 'textNode', + 'tagName', + 'doctype', + 'procInstName', + 'procInstBody', + 'entity', + 'attribName', + 'attribValue', + 'cdata', + 'script', + ] + + sax.EVENTS = [ + 'text', + 'processinginstruction', + 'sgmldeclaration', + 'doctype', + 'comment', + 'opentagstart', + 'attribute', + 'opentag', + 'closetag', + 'opencdata', + 'cdata', + 'closecdata', + 'error', + 'end', + 'ready', + 'script', + 'opennamespace', + 'closenamespace', + ] + + function SAXParser(strict, opt) { + if (!(this instanceof SAXParser)) { + return new SAXParser(strict, opt) + } + + var parser = this + clearBuffers(parser) + parser.q = parser.c = '' + parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH + parser.encoding = null; + parser.opt = opt || {} + parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags + parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase' + parser.opt.maxEntityCount = parser.opt.maxEntityCount || 512 + parser.opt.maxEntityDepth = parser.opt.maxEntityDepth || 4 + parser.entityCount = parser.entityDepth = 0 + parser.tags = [] + parser.closed = parser.closedRoot = parser.sawRoot = false + parser.tag = parser.error = null + parser.strict = !!strict + parser.noscript = !!(strict || parser.opt.noscript) + parser.state = S.BEGIN + parser.strictEntities = parser.opt.strictEntities + parser.ENTITIES = + parser.strictEntities ? + Object.create(sax.XML_ENTITIES) + : Object.create(sax.ENTITIES) + parser.attribList = [] + + // namespaces form a prototype chain. + // it always points at the current tag, + // which protos to its parent tag. + if (parser.opt.xmlns) { + parser.ns = Object.create(rootNS) + } + + // disallow unquoted attribute values if not otherwise configured + // and strict mode is true + if (parser.opt.unquotedAttributeValues === undefined) { + parser.opt.unquotedAttributeValues = !strict + } + + // mostly just for error reporting + parser.trackPosition = parser.opt.position !== false + if (parser.trackPosition) { + parser.position = parser.line = parser.column = 0 + } + emit(parser, 'onready') + } + + if (!Object.create) { + Object.create = function (o) { + function F() {} + F.prototype = o + var newf = new F() + return newf + } + } + + if (!Object.keys) { + Object.keys = function (o) { + var a = [] + for (var i in o) if (o.hasOwnProperty(i)) a.push(i) + return a + } + } + + function checkBufferLength(parser) { + var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10) + var maxActual = 0 + for (var i = 0, l = buffers.length; i < l; i++) { + var len = parser[buffers[i]].length + if (len > maxAllowed) { + // Text/cdata nodes can get big, and since they're buffered, + // we can get here under normal conditions. + // Avoid issues by emitting the text node now, + // so at least it won't get any bigger. + switch (buffers[i]) { + case 'textNode': + closeText(parser) + break + + case 'cdata': + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + break + + case 'script': + emitNode(parser, 'onscript', parser.script) + parser.script = '' + break + + default: + error(parser, 'Max buffer length exceeded: ' + buffers[i]) + } + } + maxActual = Math.max(maxActual, len) + } + // schedule the next check for the earliest possible buffer overrun. + var m = sax.MAX_BUFFER_LENGTH - maxActual + parser.bufferCheckPosition = m + parser.position + } + + function clearBuffers(parser) { + for (var i = 0, l = buffers.length; i < l; i++) { + parser[buffers[i]] = '' + } + } + + function flushBuffers(parser) { + closeText(parser) + if (parser.cdata !== '') { + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + } + if (parser.script !== '') { + emitNode(parser, 'onscript', parser.script) + parser.script = '' + } + } + + SAXParser.prototype = { + end: function () { + end(this) + }, + write: write, + resume: function () { + this.error = null + return this + }, + close: function () { + return this.write(null) + }, + flush: function () { + flushBuffers(this) + }, + } + + var Stream + try { + Stream = require('stream').Stream + } catch (ex) { + Stream = function () {} + } + if (!Stream) Stream = function () {} + + var streamWraps = sax.EVENTS.filter(function (ev) { + return ev !== 'error' && ev !== 'end' + }) + + function createStream(strict, opt) { + return new SAXStream(strict, opt) + } + + function determineBufferEncoding(data, isEnd) { + // BOM-based detection is the most reliable signal when present. + if (data.length >= 2) { + if (data[0] === 0xff && data[1] === 0xfe) { + return 'utf-16le' + } + + if (data[0] === 0xfe && data[1] === 0xff) { + return 'utf-16be' + } + } + + if (data.length >= 3 && data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) { + return 'utf8' + } + + if (data.length >= 4) { + // XML documents without a BOM still start with "' || isWhitespace(c) + } + + function isMatch(regex, c) { + return regex.test(c) + } + + function notMatch(regex, c) { + return !isMatch(regex, c) + } + + var S = 0 + sax.STATE = { + BEGIN: S++, // leading byte order mark or whitespace + BEGIN_WHITESPACE: S++, // leading whitespace + TEXT: S++, // general stuff + TEXT_ENTITY: S++, // & and such. + OPEN_WAKA: S++, // < + SGML_DECL: S++, // + SCRIPT: S++, //