This commit is contained in:
Lukáš Kaňka 2023-08-15 18:35:50 +02:00
commit ea3e372146
10019 changed files with 2548539 additions and 0 deletions

8
CY_Auta_TS/.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/CY_Auta_TS.iml" filepath="$PROJECT_DIR$/.idea/CY_Auta_TS.iml" />
</modules>
</component>
</project>

6
CY_Auta_TS/.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

8
CY_Auta_TS/automaty/.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/automaty.iml" filepath="$PROJECT_DIR$/.idea/automaty.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,9 @@
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here
},
},
});

View File

@ -0,0 +1,19 @@
import { AaaAuto } from "cypress/page_objects/homepage";
const acka = new AaaAuto();
describe("Homepage AAA Auto", () => {
beforeEach(() => {
acka.hlavnistrana().rozliseni().cookiespotvrzeni();
})
it("horni hlavickova lista", () => {
acka.hlavicka();
});
it("slider bamer", () => {
acka.slider();
});
it("filter bar", () => {
acka.filterbar();
});
});

View File

@ -0,0 +1,37 @@
describe("Homepage AAA Auto", () => {
it("Filtrování vozu škoda Citigo a ověření zobrazení výsledků", () => {
cy.viewport(1920, 1080);
// Na homepage AAA (aaaauto.cz) vyplnte filter bar a potvrdte.
cy.visit("https://www.aaaauto.cz/");
// Potvrzení cookies
cy.contains("Pouze nezbytné cookies").click();
// Kliknutí na filtr značek
cy.get("#car_filter_make").click();
// Vybrání značky škoda
cy.contains("Škoda").click();
// Kliknutí na filtr modelů
cy.get("#car_filter_model").click();
// Vybrán model Citigo
cy.contains("Citigo").click();
// Kliknutí Stáří Vozu
cy.get("#car_filter_yearMin-topForm").click();
// Nastavení ve výběru vozu do stáří deseti let
cy.contains('Do 10 let').click();
cy.get("button[data-slider-filter-year-save]").click();
// Kliknutí na Vyberte cenu
cy.get("#car_filter_priceMax-topForm").click();
cy.contains("Do 200 000 Kč").click();
cy.get("button[data-slider-filter-price-save]").click();
// Kliknutí na Vyberte typ vozů
cy.get("#car_filter_category").click();
cy.contains("Úsporné vozy").click()
// Hledej
cy.get('form[name="car_filter"]').submit();
// Zkontrolovat výsledek filtrovaní
cy.get("#modern2019-list > div.flex.flexSB.flexAlignCenter.mv5.noprint > ul > li:nth-child(1) > span > span").contains("Škoda").should("be.visible");
cy.get('#modern2019-list > div.flex.flexSB.flexAlignCenter.mv5.noprint > ul > li:nth-child(2) > span > span').contains("Citigo").should("be.visible");
cy.get("#modern2019-list > div.flex.flexSB.flexAlignCenter.mv5.noprint > ul > li:nth-child(3) > span").contains("Rok od: 2013").should("be.visible");
cy.get("#modern2019-list > div.flex.flexSB.flexAlignCenter.mv5.noprint > ul > li:nth-child(4) > span").contains("Cena do: 200 000 Kč").should("be.visible");
cy.get("#modern2019-list > div.flex.flexSB.flexAlignCenter.mv5.noprint > ul > li:nth-child(5) > span > span").contains("Malé a ECO vozy").should("be.visible");
});
});

View File

@ -0,0 +1,47 @@
import { AaaAuto } from "cypress/page_objects/homepage";
import { Filtrovani } from "cypress/page_objects/filtrovani";
const acka = new AaaAuto();
const filtr = new Filtrovani();
// Filtry overeni
const znackaOvereni = "Škoda";
const modelOvereni = "Citigo";
const stariOvereni = "Rok od: 2013";
const cenaOvereni = "Cena do: 200 000 Kč";
const kategorieOvereni = "Malé a ECO vozy";
// Filtry vyber
const znackaVyber = "Škoda";
const typModelu = "Citigo";
const stariAuta = "Do 10 let";
const vyberCeny = "Do 200 000 Kč";
const vyberKategorie = "Úsporné vozy";
describe("Homepage AAA Auto", () => {
beforeEach(() => {
acka.hlavnistrana().rozliseni().cookiespotvrzeni();
});
it("Filtrování vozu škoda Citigo a ověření zobrazení výsledků", () => {
acka
.clickMenuZnacka()
.vyberZnacky(znackaVyber)
.clickMenuFiltrModelu()
.vyberModeluAuta(typModelu)
.clickMenuStariAuta()
.vyberStariAuta(stariAuta)
.potvrzeniStariAuta()
.clickMenuCenyAuta()
.vyberCenyAuta(vyberCeny)
.potvrzeniCenyAuta()
.clickMenuKategorieAuta()
.vyberKategorieAuta(vyberKategorie)
.clickNaTlacitkoHledej();
filtr
.filtrOvereniZnacky(znackaOvereni)
.filtrOvereniModelu(modelOvereni)
.filtrOvereniStari(stariOvereni)
.filtrOvereniCeny(cenaOvereni)
.filtrOvereniKategorie(kategorieOvereni);
});
});

View File

@ -0,0 +1,5 @@
{
"name": "Using fixtures to represent data",
"email": "hello@cypress.io",
"body": "Fixtures are a great way to mock data for responses to routes"
}

View File

@ -0,0 +1,47 @@
export class Filtrovani {
filtrOvereniZnacky(znackaOvereni) {
cy.get(
"#modern2019-list > div.flex.flexSB.flexAlignCenter.mv5.noprint > ul > li:nth-child(1) > span > span",
)
.contains(znackaOvereni)
.should("be.visible");
return this;
};
filtrOvereniModelu(modelOvereni) {
cy.get(
"#modern2019-list > div.flex.flexSB.flexAlignCenter.mv5.noprint > ul > li:nth-child(2) > span > span",
)
.contains(modelOvereni)
.should("be.visible");
return this;
};
filtrOvereniStari(stariOvereni) {
cy.get(
"#modern2019-list > div.flex.flexSB.flexAlignCenter.mv5.noprint > ul > li:nth-child(3) > span",
)
.contains(stariOvereni)
.should("be.visible");
return this;
};
filtrOvereniCeny(cenaOvereni) {
cy.get(
"#modern2019-list > div.flex.flexSB.flexAlignCenter.mv5.noprint > ul > li:nth-child(4) > span",
)
.contains(cenaOvereni)
.should("be.visible");
return this;
};
filtrOvereniKategorie(kategorieOvereni) {
cy.get(
"#modern2019-list > div.flex.flexSB.flexAlignCenter.mv5.noprint > ul > li:nth-child(5) > span > span",
)
.contains(kategorieOvereni)
.should("be.visible");
return this;
};
}

View File

@ -0,0 +1,173 @@
export class AaaAuto {
rozliseni() {
cy.viewport(1920, 1080);
return this;
};
hlavnistrana() {
cy.visit("https://www.aaaauto.cz/");
return this;
};
cookiespotvrzeni() {
cy.contains("Pouze nezbytné cookies").click();
return this;
};
hlavicka() {
// logo AAA
cy.get("#modern-header > header > div > div.headerMenu > a > svg").should(
"be.visible",
);
//Koupit
cy.get(
"#modern-header > header > div > div.headerMenu > ul > li:nth-child(1) > a",
)
.should("be.visible")
.trigger("mouseover");
// Prodat
cy.get(
"#modern-header > header > div > div.headerMenu > ul > li:nth-child(2) > a",
)
.should("be.visible")
.trigger("mouseover");
// Vyměnit
cy.get(
"#modern-header > header > div > div.headerMenu > ul > li:nth-child(3) > a",
)
.should("be.visible")
.trigger("mouseover");
// Financovat
cy.get(
"#modern-header > header > div > div.headerMenu > ul > li:nth-child(4) > a",
)
.should("be.visible")
.trigger("mouseover");
// Kariéra
cy.get(
"#modern-header > header > div > div.headerMenu > ul > li:nth-child(5) > a",
).should("be.visible");
// Ikona Lupy
cy.get(
"#modern-header > header > div > div.headerTools > span.headerToolsItem.searchButton > svg",
).should("be.visible");
// Kontakty otvírací doby
cy.get(
"#modern-header > header > div > div.headerTools > a:nth-child(2) > svg",
).should("be.visible");
// Garáž
cy.get("#notifications-desktop > span > svg")
.should("be.visible")
.trigger("mouseover");
// WhatsApp
cy.get(
"#modern-header > header > div > div.headerTools > a:nth-child(4) > svg > g > path:nth-child(4)",
).should("be.visible");
// Telefóní linka
cy.get(
"#modern-header > header > div > div.headerTools > span.headerToolsItem.headerToolsItemContact.hasSubmenu.submenuLink > h3",
)
.should("be.visible")
.trigger("mouseover");
return this;
};
slider() {
// api slidebar
cy.get("body > div.modern2018.fullHeight.fullWidth > div").should(
"be.visible",
);
return this;
};
filterbar() {
// Značka
cy.get("#hpFilterNG > form > div > div > div:nth-child(1)").should(
"be.visible",
);
// Model
cy.get("#hpFilterNG > form > div > div > div.select.disabled").should(
"be.visible",
);
// Rok
cy.get(
"#hpFilterNG > form > div > div > div.multiselect.multiselect--large",
).should("be.visible");
// Cena
cy.get("#hpFilterNG > form > div > div > div:nth-child(4)").should(
"be.visible",
);
// Kategorie
cy.get(
"#hpFilterNG > form > div > div > div.select.select--not-important",
).should("be.visible");
// Hledat
cy.get("#hpFilterNG > form > div > button").should("be.visible");
return this;
};
clickMenuZnacka() {
cy.get("#car_filter_make").click();
return this;
};
vyberZnacky(znackaVyber) {
cy.contains(znackaVyber).click();
return this;
};
clickMenuFiltrModelu() {
cy.get("#car_filter_model").click();
return this;
};
vyberModeluAuta(typModelu) {
cy.contains(typModelu).click();
return this;
};
clickMenuStariAuta() {
cy.get("#car_filter_yearMin-topForm").click();
return this;
};
vyberStariAuta(stariVyber) {
cy.contains(stariVyber).click();
return this;
};
potvrzeniStariAuta() {
cy.get("button[data-slider-filter-year-save]").click();
return this;
};
clickMenuCenyAuta() {
cy.get("#car_filter_priceMax-topForm").click();
return this;
};
vyberCenyAuta(vyberCeny) {
cy.contains(vyberCeny).click();
return this;
};
potvrzeniCenyAuta() {
cy.get("button[data-slider-filter-price-save]").click();
return this;
};
clickMenuKategorieAuta() {
cy.get("#car_filter_category").click();
return this;
};
vyberKategorieAuta(vyberKategorie) {
cy.contains(vyberKategorie).click();
return this;
};
clickNaTlacitkoHledej() {
cy.get('form[name="car_filter"]').submit();
return this;
}
};

View File

@ -0,0 +1,25 @@
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })

View File

@ -0,0 +1,21 @@
// ***********************************************************
// This example support/e2e.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************
// Import commands.js using ES2015 syntax:
import './commands'
// Alternatively you can use CommonJS syntax:
// require('./commands')
require("@cypress/xpath");

View File

@ -0,0 +1,7 @@
// cypress/support/index.js
const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot');
require('@cypress/xpath');
addMatchImageSnapshotPlugin();

19
CY_Auta_TS/automaty/node_modules/.package-lock.json generated vendored Normal file
View File

@ -0,0 +1,19 @@
{
"name": "automaty",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/typescript": {
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.6.tgz",
"integrity": "sha512-zaWCozRZ6DLEWAWFrVDz1H6FVXzUSfTy5FUMWsQlU8Ym5JP9eO4xkTIROFCQvhQf61z6O/G6ugw3SgAnvvm+HA==",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
}
}
}

View File

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

View File

@ -0,0 +1,219 @@
# @colors/colors ("colors.js")
[![Build Status](https://github.com/DABH/colors.js/actions/workflows/ci.yml/badge.svg)](https://github.com/DABH/colors.js/actions/workflows/ci.yml)
[![version](https://img.shields.io/npm/v/@colors/colors.svg)](https://www.npmjs.org/package/@colors/colors)
Please check out the [roadmap](ROADMAP.md) for upcoming features and releases. Please open Issues to provide feedback.
## get color and style in your node.js console
![Demo](https://raw.githubusercontent.com/DABH/colors.js/master/screenshots/colors.png)
## Installation
npm install @colors/colors
## colors and styles!
### text colors
- black
- red
- green
- yellow
- blue
- magenta
- cyan
- white
- gray
- grey
### bright text colors
- brightRed
- brightGreen
- brightYellow
- brightBlue
- brightMagenta
- brightCyan
- brightWhite
### background colors
- bgBlack
- bgRed
- bgGreen
- bgYellow
- bgBlue
- bgMagenta
- bgCyan
- bgWhite
- bgGray
- bgGrey
### bright background colors
- bgBrightRed
- bgBrightGreen
- bgBrightYellow
- bgBrightBlue
- bgBrightMagenta
- bgBrightCyan
- bgBrightWhite
### styles
- reset
- bold
- dim
- italic
- underline
- inverse
- hidden
- strikethrough
### extras
- rainbow
- zebra
- america
- trap
- random
## Usage
By popular demand, `@colors/colors` now ships with two types of usages!
The super nifty way
```js
var colors = require('@colors/colors');
console.log('hello'.green); // outputs green text
console.log('i like cake and pies'.underline.red); // outputs red underlined text
console.log('inverse the color'.inverse); // inverses the color
console.log('OMG Rainbows!'.rainbow); // rainbow
console.log('Run the trap'.trap); // Drops the bass
```
or a slightly less nifty way which doesn't extend `String.prototype`
```js
var colors = require('@colors/colors/safe');
console.log(colors.green('hello')); // outputs green text
console.log(colors.red.underline('i like cake and pies')); // outputs red underlined text
console.log(colors.inverse('inverse the color')); // inverses the color
console.log(colors.rainbow('OMG Rainbows!')); // rainbow
console.log(colors.trap('Run the trap')); // Drops the bass
```
I prefer the first way. Some people seem to be afraid of extending `String.prototype` and prefer the second way.
If you are writing good code you will never have an issue with the first approach. If you really don't want to touch `String.prototype`, the second usage will not touch `String` native object.
## Enabling/Disabling Colors
The package will auto-detect whether your terminal can use colors and enable/disable accordingly. When colors are disabled, the color functions do nothing. You can override this with a command-line flag:
```bash
node myapp.js --no-color
node myapp.js --color=false
node myapp.js --color
node myapp.js --color=true
node myapp.js --color=always
FORCE_COLOR=1 node myapp.js
```
Or in code:
```javascript
var colors = require('@colors/colors');
colors.enable();
colors.disable();
```
## Console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data)
```js
var name = 'Beowulf';
console.log(colors.green('Hello %s'), name);
// outputs -> 'Hello Beowulf'
```
## Custom themes
### Using standard API
```js
var colors = require('@colors/colors');
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log("this is an error".error);
// outputs yellow text
console.log("this is a warning".warn);
```
### Using string safe API
```js
var colors = require('@colors/colors/safe');
// set single property
var error = colors.red;
error('this is red');
// set theme
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log(colors.error("this is an error"));
// outputs yellow text
console.log(colors.warn("this is a warning"));
```
### Combining Colors
```javascript
var colors = require('@colors/colors');
colors.setTheme({
custom: ['red', 'underline']
});
console.log('test'.custom);
```
*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.*

View File

@ -0,0 +1,83 @@
var colors = require('../lib/index');
console.log('First some yellow text'.yellow);
console.log('Underline that text'.yellow.underline);
console.log('Make it bold and red'.red.bold);
console.log(('Double Raindows All Day Long').rainbow);
console.log('Drop the bass'.trap);
console.log('DROP THE RAINBOW BASS'.trap.rainbow);
// styles not widely supported
console.log('Chains are also cool.'.bold.italic.underline.red);
// styles not widely supported
console.log('So '.green + 'are'.underline + ' ' + 'inverse'.inverse
+ ' styles! '.yellow.bold);
console.log('Zebras are so fun!'.zebra);
//
// Remark: .strikethrough may not work with Mac OS Terminal App
//
console.log('This is ' + 'not'.strikethrough + ' fun.');
console.log('Background color attack!'.black.bgWhite);
console.log('Use random styles on everything!'.random);
console.log('America, Heck Yeah!'.america);
// eslint-disable-next-line max-len
console.log('Blindingly '.brightCyan + 'bright? '.brightRed + 'Why '.brightYellow + 'not?!'.brightGreen);
console.log('Setting themes is useful');
//
// Custom themes
//
console.log('Generic logging theme as JSON'.green.bold.underline);
// Load theme with JSON literal
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red',
});
// outputs red text
console.log('this is an error'.error);
// outputs yellow text
console.log('this is a warning'.warn);
// outputs grey text
console.log('this is an input'.input);
console.log('Generic logging theme as file'.green.bold.underline);
// Load a theme from file
try {
colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));
} catch (err) {
console.log(err);
}
// outputs red text
console.log('this is an error'.error);
// outputs yellow text
console.log('this is a warning'.warn);
// outputs grey text
console.log('this is an input'.input);
// console.log("Don't summon".zalgo)

View File

@ -0,0 +1,80 @@
var colors = require('../safe');
console.log(colors.yellow('First some yellow text'));
console.log(colors.yellow.underline('Underline that text'));
console.log(colors.red.bold('Make it bold and red'));
console.log(colors.rainbow('Double Raindows All Day Long'));
console.log(colors.trap('Drop the bass'));
console.log(colors.rainbow(colors.trap('DROP THE RAINBOW BASS')));
// styles not widely supported
console.log(colors.bold.italic.underline.red('Chains are also cool.'));
// styles not widely supported
console.log(colors.green('So ') + colors.underline('are') + ' '
+ colors.inverse('inverse') + colors.yellow.bold(' styles! '));
console.log(colors.zebra('Zebras are so fun!'));
console.log('This is ' + colors.strikethrough('not') + ' fun.');
console.log(colors.black.bgWhite('Background color attack!'));
console.log(colors.random('Use random styles on everything!'));
console.log(colors.america('America, Heck Yeah!'));
// eslint-disable-next-line max-len
console.log(colors.brightCyan('Blindingly ') + colors.brightRed('bright? ') + colors.brightYellow('Why ') + colors.brightGreen('not?!'));
console.log('Setting themes is useful');
//
// Custom themes
//
// console.log('Generic logging theme as JSON'.green.bold.underline);
// Load theme with JSON literal
colors.setTheme({
silly: 'rainbow',
input: 'blue',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red',
});
// outputs red text
console.log(colors.error('this is an error'));
// outputs yellow text
console.log(colors.warn('this is a warning'));
// outputs blue text
console.log(colors.input('this is an input'));
// console.log('Generic logging theme as file'.green.bold.underline);
// Load a theme from file
colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));
// outputs red text
console.log(colors.error('this is an error'));
// outputs yellow text
console.log(colors.warn('this is a warning'));
// outputs grey text
console.log(colors.input('this is an input'));
// console.log(colors.zalgo("Don't summon him"))

View File

@ -0,0 +1,136 @@
// Type definitions for @colors/colors 1.4+
// Project: https://github.com/Marak/colors.js
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Staffan Eketorp <https://github.com/staeke>
// Definitions: https://github.com/DABH/colors.js
export interface Color {
(text: string): string;
strip: Color;
stripColors: Color;
black: Color;
red: Color;
green: Color;
yellow: Color;
blue: Color;
magenta: Color;
cyan: Color;
white: Color;
gray: Color;
grey: Color;
bgBlack: Color;
bgRed: Color;
bgGreen: Color;
bgYellow: Color;
bgBlue: Color;
bgMagenta: Color;
bgCyan: Color;
bgWhite: Color;
reset: Color;
bold: Color;
dim: Color;
italic: Color;
underline: Color;
inverse: Color;
hidden: Color;
strikethrough: Color;
rainbow: Color;
zebra: Color;
america: Color;
trap: Color;
random: Color;
zalgo: Color;
}
export function enable(): void;
export function disable(): void;
export function setTheme(theme: any): void;
export let enabled: boolean;
export const strip: Color;
export const stripColors: Color;
export const black: Color;
export const red: Color;
export const green: Color;
export const yellow: Color;
export const blue: Color;
export const magenta: Color;
export const cyan: Color;
export const white: Color;
export const gray: Color;
export const grey: Color;
export const bgBlack: Color;
export const bgRed: Color;
export const bgGreen: Color;
export const bgYellow: Color;
export const bgBlue: Color;
export const bgMagenta: Color;
export const bgCyan: Color;
export const bgWhite: Color;
export const reset: Color;
export const bold: Color;
export const dim: Color;
export const italic: Color;
export const underline: Color;
export const inverse: Color;
export const hidden: Color;
export const strikethrough: Color;
export const rainbow: Color;
export const zebra: Color;
export const america: Color;
export const trap: Color;
export const random: Color;
export const zalgo: Color;
declare global {
interface String {
strip: string;
stripColors: string;
black: string;
red: string;
green: string;
yellow: string;
blue: string;
magenta: string;
cyan: string;
white: string;
gray: string;
grey: string;
bgBlack: string;
bgRed: string;
bgGreen: string;
bgYellow: string;
bgBlue: string;
bgMagenta: string;
bgCyan: string;
bgWhite: string;
reset: string;
// @ts-ignore
bold: string;
dim: string;
italic: string;
underline: string;
inverse: string;
hidden: string;
strikethrough: string;
rainbow: string;
zebra: string;
america: string;
trap: string;
random: string;
zalgo: string;
}
}

View File

@ -0,0 +1,211 @@
/*
The MIT License (MIT)
Original Library
- Copyright (c) Marak Squires
Additional functionality
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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.
*/
var colors = {};
module['exports'] = colors;
colors.themes = {};
var util = require('util');
var ansiStyles = colors.styles = require('./styles');
var defineProps = Object.defineProperties;
var newLineRegex = new RegExp(/[\r\n]+/g);
colors.supportsColor = require('./system/supports-colors').supportsColor;
if (typeof colors.enabled === 'undefined') {
colors.enabled = colors.supportsColor() !== false;
}
colors.enable = function() {
colors.enabled = true;
};
colors.disable = function() {
colors.enabled = false;
};
colors.stripColors = colors.strip = function(str) {
return ('' + str).replace(/\x1B\[\d+m/g, '');
};
// eslint-disable-next-line no-unused-vars
var stylize = colors.stylize = function stylize(str, style) {
if (!colors.enabled) {
return str+'';
}
var styleMap = ansiStyles[style];
// Stylize should work for non-ANSI styles, too
if (!styleMap && style in colors) {
// Style maps like trap operate as functions on strings;
// they don't have properties like open or close.
return colors[style](str);
}
return styleMap.open + str + styleMap.close;
};
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
var escapeStringRegexp = function(str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
return str.replace(matchOperatorsRe, '\\$&');
};
function build(_styles) {
var builder = function builder() {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
// __proto__ is used because we must return a function, but there is
// no way to create a function with a different prototype.
builder.__proto__ = proto;
return builder;
}
var styles = (function() {
var ret = {};
ansiStyles.grey = ansiStyles.gray;
Object.keys(ansiStyles).forEach(function(key) {
ansiStyles[key].closeRe =
new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
ret[key] = {
get: function() {
return build(this._styles.concat(key));
},
};
});
return ret;
})();
var proto = defineProps(function colors() {}, styles);
function applyStyle() {
var args = Array.prototype.slice.call(arguments);
var str = args.map(function(arg) {
// Use weak equality check so we can colorize null/undefined in safe mode
if (arg != null && arg.constructor === String) {
return arg;
} else {
return util.inspect(arg);
}
}).join(' ');
if (!colors.enabled || !str) {
return str;
}
var newLinesPresent = str.indexOf('\n') != -1;
var nestedStyles = this._styles;
var i = nestedStyles.length;
while (i--) {
var code = ansiStyles[nestedStyles[i]];
str = code.open + str.replace(code.closeRe, code.open) + code.close;
if (newLinesPresent) {
str = str.replace(newLineRegex, function(match) {
return code.close + match + code.open;
});
}
}
return str;
}
colors.setTheme = function(theme) {
if (typeof theme === 'string') {
console.log('colors.setTheme now only accepts an object, not a string. ' +
'If you are trying to set a theme from a file, it is now your (the ' +
'caller\'s) responsibility to require the file. The old syntax ' +
'looked like colors.setTheme(__dirname + ' +
'\'/../themes/generic-logging.js\'); The new syntax looks like '+
'colors.setTheme(require(__dirname + ' +
'\'/../themes/generic-logging.js\'));');
return;
}
for (var style in theme) {
(function(style) {
colors[style] = function(str) {
if (typeof theme[style] === 'object') {
var out = str;
for (var i in theme[style]) {
out = colors[theme[style][i]](out);
}
return out;
}
return colors[theme[style]](str);
};
})(style);
}
};
function init() {
var ret = {};
Object.keys(styles).forEach(function(name) {
ret[name] = {
get: function() {
return build([name]);
},
};
});
return ret;
}
var sequencer = function sequencer(map, str) {
var exploded = str.split('');
exploded = exploded.map(map);
return exploded.join('');
};
// custom formatter methods
colors.trap = require('./custom/trap');
colors.zalgo = require('./custom/zalgo');
// maps
colors.maps = {};
colors.maps.america = require('./maps/america')(colors);
colors.maps.zebra = require('./maps/zebra')(colors);
colors.maps.rainbow = require('./maps/rainbow')(colors);
colors.maps.random = require('./maps/random')(colors);
for (var map in colors.maps) {
(function(map) {
colors[map] = function(str) {
return sequencer(colors.maps[map], str);
};
})(map);
}
defineProps(colors, init());

View File

@ -0,0 +1,46 @@
module['exports'] = function runTheTrap(text, options) {
var result = '';
text = text || 'Run the trap, drop the bass';
text = text.split('');
var trap = {
a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'],
b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'],
c: ['\u00a9', '\u023b', '\u03fe'],
d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'],
e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc',
'\u0a6c'],
f: ['\u04fa'],
g: ['\u0262'],
h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'],
i: ['\u0f0f'],
j: ['\u0134'],
k: ['\u0138', '\u04a0', '\u04c3', '\u051e'],
l: ['\u0139'],
m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'],
n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'],
o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd',
'\u06dd', '\u0e4f'],
p: ['\u01f7', '\u048e'],
q: ['\u09cd'],
r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'],
s: ['\u00a7', '\u03de', '\u03df', '\u03e8'],
t: ['\u0141', '\u0166', '\u0373'],
u: ['\u01b1', '\u054d'],
v: ['\u05d8'],
w: ['\u0428', '\u0460', '\u047c', '\u0d70'],
x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'],
y: ['\u00a5', '\u04b0', '\u04cb'],
z: ['\u01b5', '\u0240'],
};
text.forEach(function(c) {
c = c.toLowerCase();
var chars = trap[c] || [' '];
var rand = Math.floor(Math.random() * chars.length);
if (typeof trap[c] !== 'undefined') {
result += trap[c][rand];
} else {
result += c;
}
});
return result;
};

View File

@ -0,0 +1,110 @@
// please no
module['exports'] = function zalgo(text, options) {
text = text || ' he is here ';
var soul = {
'up': [
'̍', '̎', '̄', '̅',
'̿', '̑', '̆', '̐',
'͒', '͗', '͑', '̇',
'̈', '̊', '͂', '̓',
'̈', '͊', '͋', '͌',
'̃', '̂', '̌', '͐',
'̀', '́', '̋', '̏',
'̒', '̓', '̔', '̽',
'̉', 'ͣ', 'ͤ', 'ͥ',
'ͦ', 'ͧ', 'ͨ', 'ͩ',
'ͪ', 'ͫ', 'ͬ', 'ͭ',
'ͮ', 'ͯ', '̾', '͛',
'͆', '̚',
],
'down': [
'̖', '̗', '̘', '̙',
'̜', '̝', '̞', '̟',
'̠', '̤', '̥', '̦',
'̩', '̪', '̫', '̬',
'̭', '̮', '̯', '̰',
'̱', '̲', '̳', '̹',
'̺', '̻', '̼', 'ͅ',
'͇', '͈', '͉', '͍',
'͎', '͓', '͔', '͕',
'͖', '͙', '͚', '̣',
],
'mid': [
'̕', '̛', '̀', '́',
'͘', '̡', '̢', '̧',
'̨', '̴', '̵', '̶',
'͜', '͝', '͞',
'͟', '͠', '͢', '̸',
'̷', '͡', ' ҉',
],
};
var all = [].concat(soul.up, soul.down, soul.mid);
function randomNumber(range) {
var r = Math.floor(Math.random() * range);
return r;
}
function isChar(character) {
var bool = false;
all.filter(function(i) {
bool = (i === character);
});
return bool;
}
function heComes(text, options) {
var result = '';
var counts;
var l;
options = options || {};
options['up'] =
typeof options['up'] !== 'undefined' ? options['up'] : true;
options['mid'] =
typeof options['mid'] !== 'undefined' ? options['mid'] : true;
options['down'] =
typeof options['down'] !== 'undefined' ? options['down'] : true;
options['size'] =
typeof options['size'] !== 'undefined' ? options['size'] : 'maxi';
text = text.split('');
for (l in text) {
if (isChar(l)) {
continue;
}
result = result + text[l];
counts = {'up': 0, 'down': 0, 'mid': 0};
switch (options.size) {
case 'mini':
counts.up = randomNumber(8);
counts.mid = randomNumber(2);
counts.down = randomNumber(8);
break;
case 'maxi':
counts.up = randomNumber(16) + 3;
counts.mid = randomNumber(4) + 1;
counts.down = randomNumber(64) + 3;
break;
default:
counts.up = randomNumber(8) + 1;
counts.mid = randomNumber(6) / 2;
counts.down = randomNumber(8) + 1;
break;
}
var arr = ['up', 'mid', 'down'];
for (var d in arr) {
var index = arr[d];
for (var i = 0; i <= counts[index]; i++) {
if (options[index]) {
result = result + soul[index][randomNumber(soul[index].length)];
}
}
}
}
return result;
}
// don't summon him
return heComes(text, options);
};

View File

@ -0,0 +1,110 @@
var colors = require('./colors');
module['exports'] = function() {
//
// Extends prototype of native string object to allow for "foo".red syntax
//
var addProperty = function(color, func) {
String.prototype.__defineGetter__(color, func);
};
addProperty('strip', function() {
return colors.strip(this);
});
addProperty('stripColors', function() {
return colors.strip(this);
});
addProperty('trap', function() {
return colors.trap(this);
});
addProperty('zalgo', function() {
return colors.zalgo(this);
});
addProperty('zebra', function() {
return colors.zebra(this);
});
addProperty('rainbow', function() {
return colors.rainbow(this);
});
addProperty('random', function() {
return colors.random(this);
});
addProperty('america', function() {
return colors.america(this);
});
//
// Iterate through all default styles and colors
//
var x = Object.keys(colors.styles);
x.forEach(function(style) {
addProperty(style, function() {
return colors.stylize(this, style);
});
});
function applyTheme(theme) {
//
// Remark: This is a list of methods that exist
// on String that you should not overwrite.
//
var stringPrototypeBlacklist = [
'__defineGetter__', '__defineSetter__', '__lookupGetter__',
'__lookupSetter__', 'charAt', 'constructor', 'hasOwnProperty',
'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString',
'valueOf', 'charCodeAt', 'indexOf', 'lastIndexOf', 'length',
'localeCompare', 'match', 'repeat', 'replace', 'search', 'slice',
'split', 'substring', 'toLocaleLowerCase', 'toLocaleUpperCase',
'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight',
];
Object.keys(theme).forEach(function(prop) {
if (stringPrototypeBlacklist.indexOf(prop) !== -1) {
console.log('warn: '.red + ('String.prototype' + prop).magenta +
' is probably something you don\'t want to override. ' +
'Ignoring style name');
} else {
if (typeof(theme[prop]) === 'string') {
colors[prop] = colors[theme[prop]];
addProperty(prop, function() {
return colors[prop](this);
});
} else {
var themePropApplicator = function(str) {
var ret = str || this;
for (var t = 0; t < theme[prop].length; t++) {
ret = colors[theme[prop][t]](ret);
}
return ret;
};
addProperty(prop, themePropApplicator);
colors[prop] = function(str) {
return themePropApplicator(str);
};
}
}
});
}
colors.setTheme = function(theme) {
if (typeof theme === 'string') {
console.log('colors.setTheme now only accepts an object, not a string. ' +
'If you are trying to set a theme from a file, it is now your (the ' +
'caller\'s) responsibility to require the file. The old syntax ' +
'looked like colors.setTheme(__dirname + ' +
'\'/../themes/generic-logging.js\'); The new syntax looks like '+
'colors.setTheme(require(__dirname + ' +
'\'/../themes/generic-logging.js\'));');
return;
} else {
applyTheme(theme);
}
};
};

View File

@ -0,0 +1,13 @@
var colors = require('./colors');
module['exports'] = colors;
// Remark: By default, colors will add style properties to String.prototype.
//
// If you don't wish to extend String.prototype, you can do this instead and
// native String will not be touched:
//
// var colors = require('colors/safe);
// colors.red("foo")
//
//
require('./extendStringPrototype')();

View File

@ -0,0 +1,10 @@
module['exports'] = function(colors) {
return function(letter, i, exploded) {
if (letter === ' ') return letter;
switch (i%3) {
case 0: return colors.red(letter);
case 1: return colors.white(letter);
case 2: return colors.blue(letter);
}
};
};

View File

@ -0,0 +1,12 @@
module['exports'] = function(colors) {
// RoY G BiV
var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta'];
return function(letter, i, exploded) {
if (letter === ' ') {
return letter;
} else {
return colors[rainbowColors[i++ % rainbowColors.length]](letter);
}
};
};

View File

@ -0,0 +1,11 @@
module['exports'] = function(colors) {
var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green',
'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed',
'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta'];
return function(letter, i, exploded) {
return letter === ' ' ? letter :
colors[
available[Math.round(Math.random() * (available.length - 2))]
](letter);
};
};

View File

@ -0,0 +1,5 @@
module['exports'] = function(colors) {
return function(letter, i, exploded) {
return i % 2 === 0 ? letter : colors.inverse(letter);
};
};

View File

@ -0,0 +1,95 @@
/*
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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.
*/
var styles = {};
module['exports'] = styles;
var codes = {
reset: [0, 0],
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
grey: [90, 39],
brightRed: [91, 39],
brightGreen: [92, 39],
brightYellow: [93, 39],
brightBlue: [94, 39],
brightMagenta: [95, 39],
brightCyan: [96, 39],
brightWhite: [97, 39],
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
bgGray: [100, 49],
bgGrey: [100, 49],
bgBrightRed: [101, 49],
bgBrightGreen: [102, 49],
bgBrightYellow: [103, 49],
bgBrightBlue: [104, 49],
bgBrightMagenta: [105, 49],
bgBrightCyan: [106, 49],
bgBrightWhite: [107, 49],
// legacy styles for colors pre v1.0.0
blackBG: [40, 49],
redBG: [41, 49],
greenBG: [42, 49],
yellowBG: [43, 49],
blueBG: [44, 49],
magentaBG: [45, 49],
cyanBG: [46, 49],
whiteBG: [47, 49],
};
Object.keys(codes).forEach(function(key) {
var val = codes[key];
var style = styles[key] = [];
style.open = '\u001b[' + val[0] + 'm';
style.close = '\u001b[' + val[1] + 'm';
});

View File

@ -0,0 +1,35 @@
/*
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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.
*/
'use strict';
module.exports = function(flag, argv) {
argv = argv || process.argv;
var terminatorPos = argv.indexOf('--');
var prefix = /^-{1,2}/.test(flag) ? '' : '--';
var pos = argv.indexOf(prefix + flag);
return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
};

View File

@ -0,0 +1,151 @@
/*
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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.
*/
'use strict';
var os = require('os');
var hasFlag = require('./has-flag.js');
var env = process.env;
var forceColor = void 0;
if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
forceColor = false;
} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true')
|| hasFlag('color=always')) {
forceColor = true;
}
if ('FORCE_COLOR' in env) {
forceColor = env.FORCE_COLOR.length === 0
|| parseInt(env.FORCE_COLOR, 10) !== 0;
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level: level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3,
};
}
function supportsColor(stream) {
if (forceColor === false) {
return 0;
}
if (hasFlag('color=16m') || hasFlag('color=full')
|| hasFlag('color=truecolor')) {
return 3;
}
if (hasFlag('color=256')) {
return 2;
}
if (stream && !stream.isTTY && forceColor !== true) {
return 0;
}
var min = forceColor ? 1 : 0;
if (process.platform === 'win32') {
// Node.js 7.5.0 is the first version of Node.js to include a patch to
// libuv that enables 256 color output on Windows. Anything earlier and it
// won't work. However, here we target Node.js 8 at minimum as it is an LTS
// release, and Node.js 7 is not. Windows 10 build 10586 is the first
// Windows release that supports 256 colors. Windows 10 build 14931 is the
// first release that supports 16m/TrueColor.
var osRelease = os.release().split('.');
if (Number(process.versions.node.split('.')[0]) >= 8
&& Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ('CI' in env) {
if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) {
return sign in env;
}) || env.CI_NAME === 'codeship') {
return 1;
}
return min;
}
if ('TEAMCITY_VERSION' in env) {
return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0
);
}
if ('TERM_PROGRAM' in env) {
var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
switch (env.TERM_PROGRAM) {
case 'iTerm.app':
return version >= 3 ? 3 : 2;
case 'Hyper':
return 3;
case 'Apple_Terminal':
return 2;
// No default
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ('COLORTERM' in env) {
return 1;
}
if (env.TERM === 'dumb') {
return min;
}
return min;
}
function getSupportLevel(stream) {
var level = supportsColor(stream);
return translateLevel(level);
}
module.exports = {
supportsColor: getSupportLevel,
stdout: getSupportLevel(process.stdout),
stderr: getSupportLevel(process.stderr),
};

View File

@ -0,0 +1,45 @@
{
"name": "@colors/colors",
"description": "get colors in your node.js console",
"version": "1.5.0",
"author": "DABH",
"contributors": [
{
"name": "DABH",
"url": "https://github.com/DABH"
}
],
"homepage": "https://github.com/DABH/colors.js",
"bugs": "https://github.com/DABH/colors.js/issues",
"keywords": [
"ansi",
"terminal",
"colors"
],
"repository": {
"type": "git",
"url": "http://github.com/DABH/colors.js.git"
},
"license": "MIT",
"scripts": {
"lint": "eslint . --fix",
"test": "export FORCE_COLOR=1 && node tests/basic-test.js && node tests/safe-test.js"
},
"engines": {
"node": ">=0.1.90"
},
"main": "lib/index.js",
"files": [
"examples",
"lib",
"LICENSE",
"safe.js",
"themes",
"index.d.ts",
"safe.d.ts"
],
"devDependencies": {
"eslint": "^5.2.0",
"eslint-config-google": "^0.11.0"
}
}

View File

@ -0,0 +1,48 @@
// Type definitions for Colors.js 1.2
// Project: https://github.com/Marak/colors.js
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Staffan Eketorp <https://github.com/staeke>
// Definitions: https://github.com/Marak/colors.js
export const enabled: boolean;
export function enable(): void;
export function disable(): void;
export function setTheme(theme: any): void;
export function strip(str: string): string;
export function stripColors(str: string): string;
export function black(str: string): string;
export function red(str: string): string;
export function green(str: string): string;
export function yellow(str: string): string;
export function blue(str: string): string;
export function magenta(str: string): string;
export function cyan(str: string): string;
export function white(str: string): string;
export function gray(str: string): string;
export function grey(str: string): string;
export function bgBlack(str: string): string;
export function bgRed(str: string): string;
export function bgGreen(str: string): string;
export function bgYellow(str: string): string;
export function bgBlue(str: string): string;
export function bgMagenta(str: string): string;
export function bgCyan(str: string): string;
export function bgWhite(str: string): string;
export function reset(str: string): string;
export function bold(str: string): string;
export function dim(str: string): string;
export function italic(str: string): string;
export function underline(str: string): string;
export function inverse(str: string): string;
export function hidden(str: string): string;
export function strikethrough(str: string): string;
export function rainbow(str: string): string;
export function zebra(str: string): string;
export function america(str: string): string;
export function trap(str: string): string;
export function random(str: string): string;
export function zalgo(str: string): string;

View File

@ -0,0 +1,10 @@
//
// Remark: Requiring this file will use the "safe" colors API,
// which will not touch String.prototype.
//
// var colors = require('colors/safe');
// colors.red("foo")
//
//
var colors = require('./lib/colors');
module['exports'] = colors;

View File

@ -0,0 +1,12 @@
module['exports'] = {
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red',
};

View File

@ -0,0 +1,55 @@
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:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
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
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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,155 @@
// Copyright 2010-2012 Mikeal Rogers
//
// 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.
'use strict'
var extend = require('extend')
var cookies = require('./lib/cookies')
var helpers = require('./lib/helpers')
var paramsHaveRequestBody = helpers.paramsHaveRequestBody
// organize params for patch, post, put, head, del
function initParams (uri, options, callback) {
if (typeof options === 'function') {
callback = options
}
var params = {}
if (options !== null && typeof options === 'object') {
extend(params, options, {uri: uri})
} else if (typeof uri === 'string') {
extend(params, {uri: uri})
} else {
extend(params, uri)
}
params.callback = callback || params.callback
return params
}
function request (uri, options, callback) {
if (typeof uri === 'undefined') {
throw new Error('undefined is not a valid uri or options object.')
}
var params = initParams(uri, options, callback)
if (params.method === 'HEAD' && paramsHaveRequestBody(params)) {
throw new Error('HTTP HEAD requests MUST NOT include a request body.')
}
return new request.Request(params)
}
function verbFunc (verb) {
var method = verb.toUpperCase()
return function (uri, options, callback) {
var params = initParams(uri, options, callback)
params.method = method
return request(params, params.callback)
}
}
// define like this to please codeintel/intellisense IDEs
request.get = verbFunc('get')
request.head = verbFunc('head')
request.options = verbFunc('options')
request.post = verbFunc('post')
request.put = verbFunc('put')
request.patch = verbFunc('patch')
request.del = verbFunc('delete')
request['delete'] = verbFunc('delete')
request.jar = function (store) {
return cookies.jar(store)
}
request.cookie = function (str) {
return cookies.parse(str)
}
function wrapRequestMethod (method, options, requester, verb) {
return function (uri, opts, callback) {
var params = initParams(uri, opts, callback)
var target = {}
extend(true, target, options, params)
target.pool = params.pool || options.pool
if (verb) {
target.method = verb.toUpperCase()
}
if (typeof requester === 'function') {
method = requester
}
return method(target, target.callback)
}
}
request.defaults = function (options, requester) {
var self = this
options = options || {}
if (typeof options === 'function') {
requester = options
options = {}
}
var defaults = wrapRequestMethod(self, options, requester)
var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete']
verbs.forEach(function (verb) {
defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
})
defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
defaults.jar = self.jar
defaults.defaults = self.defaults
return defaults
}
request.forever = function (agentOptions, optionsArg) {
var options = {}
if (optionsArg) {
extend(options, optionsArg)
}
if (agentOptions) {
options.agentOptions = agentOptions
}
options.forever = true
return request.defaults(options)
}
// Exports
module.exports = request
request.Request = require('./request')
request.initParams = initParams
// Backwards compatibility for request.debug
Object.defineProperty(request, 'debug', {
enumerable: true,
get: function () {
return request.Request.debug
},
set: function (debug) {
request.Request.debug = debug
}
})

View File

@ -0,0 +1,167 @@
'use strict'
var caseless = require('caseless')
var { v4: uuid } = require('uuid')
var helpers = require('./helpers')
var md5 = helpers.md5
var toBase64 = helpers.toBase64
function Auth (request) {
// define all public properties here
this.request = request
this.hasAuth = false
this.sentAuth = false
this.bearerToken = null
this.user = null
this.pass = null
}
Auth.prototype.basic = function (user, pass, sendImmediately) {
var self = this
if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
self.request.emit('error', new Error('auth() received invalid user or password'))
}
self.user = user
self.pass = pass
self.hasAuth = true
var header = user + ':' + (pass || '')
if (sendImmediately || typeof sendImmediately === 'undefined') {
var authHeader = 'Basic ' + toBase64(header)
self.sentAuth = true
return authHeader
}
}
Auth.prototype.bearer = function (bearer, sendImmediately) {
var self = this
self.bearerToken = bearer
self.hasAuth = true
if (sendImmediately || typeof sendImmediately === 'undefined') {
if (typeof bearer === 'function') {
bearer = bearer()
}
var authHeader = 'Bearer ' + (bearer || '')
self.sentAuth = true
return authHeader
}
}
Auth.prototype.digest = function (method, path, authHeader) {
// TODO: More complete implementation of RFC 2617.
// - handle challenge.domain
// - support qop="auth-int" only
// - handle Authentication-Info (not necessarily?)
// - check challenge.stale (not necessarily?)
// - increase nc (not necessarily?)
// For reference:
// http://tools.ietf.org/html/rfc2617#section-3
// https://github.com/bagder/curl/blob/master/lib/http_digest.c
var self = this
var challenge = {}
var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
while (true) {
var match = re.exec(authHeader)
if (!match) {
break
}
challenge[match[1]] = match[2] || match[3]
}
/**
* RFC 2617: handle both MD5 and MD5-sess algorithms.
*
* If the algorithm directive's value is "MD5" or unspecified, then HA1 is
* HA1=MD5(username:realm:password)
* If the algorithm directive's value is "MD5-sess", then HA1 is
* HA1=MD5(MD5(username:realm:password):nonce:cnonce)
*/
var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) {
var ha1 = md5(user + ':' + realm + ':' + pass)
if (algorithm && algorithm.toLowerCase() === 'md5-sess') {
return md5(ha1 + ':' + nonce + ':' + cnonce)
} else {
return ha1
}
}
var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
var nc = qop && '00000001'
var cnonce = qop && uuid().replace(/-/g, '')
var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce)
var ha2 = md5(method + ':' + path)
var digestResponse = qop
? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2)
: md5(ha1 + ':' + challenge.nonce + ':' + ha2)
var authValues = {
username: self.user,
realm: challenge.realm,
nonce: challenge.nonce,
uri: path,
qop: qop,
response: digestResponse,
nc: nc,
cnonce: cnonce,
algorithm: challenge.algorithm,
opaque: challenge.opaque
}
authHeader = []
for (var k in authValues) {
if (authValues[k]) {
if (k === 'qop' || k === 'nc' || k === 'algorithm') {
authHeader.push(k + '=' + authValues[k])
} else {
authHeader.push(k + '="' + authValues[k] + '"')
}
}
}
authHeader = 'Digest ' + authHeader.join(', ')
self.sentAuth = true
return authHeader
}
Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
var self = this
var request = self.request
var authHeader
if (bearer === undefined && user === undefined) {
self.request.emit('error', new Error('no auth mechanism defined'))
} else if (bearer !== undefined) {
authHeader = self.bearer(bearer, sendImmediately)
} else {
authHeader = self.basic(user, pass, sendImmediately)
}
if (authHeader) {
request.setHeader('authorization', authHeader)
}
}
Auth.prototype.onResponse = function (response) {
var self = this
var request = self.request
if (!self.hasAuth || self.sentAuth) { return null }
var c = caseless(response.headers)
var authHeader = c.get('www-authenticate')
var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase()
request.debug('reauth', authVerb)
switch (authVerb) {
case 'basic':
return self.basic(self.user, self.pass, true)
case 'bearer':
return self.bearer(self.bearerToken, true)
case 'digest':
return self.digest(request.method, request.path, authHeader)
}
}
exports.Auth = Auth

View File

@ -0,0 +1,38 @@
'use strict'
var tough = require('tough-cookie')
var Cookie = tough.Cookie
var CookieJar = tough.CookieJar
exports.parse = function (str) {
if (str && str.uri) {
str = str.uri
}
if (typeof str !== 'string') {
throw new Error('The cookie function only accepts STRING as param')
}
return Cookie.parse(str, {loose: true})
}
// Adapt the sometimes-Async api of tough.CookieJar to our requirements
function RequestJar (store) {
var self = this
self._jar = new CookieJar(store, {looseMode: true})
}
RequestJar.prototype.setCookie = function (cookieOrStr, uri, options) {
var self = this
return self._jar.setCookieSync(cookieOrStr, uri, options || {})
}
RequestJar.prototype.getCookieString = function (uri) {
var self = this
return self._jar.getCookieStringSync(uri)
}
RequestJar.prototype.getCookies = function (uri) {
var self = this
return self._jar.getCookiesSync(uri)
}
exports.jar = function (store) {
return new RequestJar(store)
}

View File

@ -0,0 +1,79 @@
'use strict'
function formatHostname (hostname) {
// canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
return hostname.replace(/^\.*/, '.').toLowerCase()
}
function parseNoProxyZone (zone) {
zone = zone.trim().toLowerCase()
var zoneParts = zone.split(':', 2)
var zoneHost = formatHostname(zoneParts[0])
var zonePort = zoneParts[1]
var hasPort = zone.indexOf(':') > -1
return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
}
function uriInNoProxy (uri, noProxy) {
var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
var hostname = formatHostname(uri.hostname)
var noProxyList = noProxy.split(',')
// iterate through the noProxyList until it finds a match.
return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) {
var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
var hostnameMatched = (
isMatchedAt > -1 &&
(isMatchedAt === hostname.length - noProxyZone.hostname.length)
)
if (noProxyZone.hasPort) {
return (port === noProxyZone.port) && hostnameMatched
}
return hostnameMatched
})
}
function getProxyFromURI (uri) {
// Decide the proper request proxy to use based on the request URI object and the
// environmental variables (NO_PROXY, HTTP_PROXY, etc.)
// respect NO_PROXY environment variables (see: https://lynx.invisible-island.net/lynx2.8.7/breakout/lynx_help/keystrokes/environments.html)
var noProxy = process.env.NO_PROXY || process.env.no_proxy || ''
// if the noProxy is a wildcard then return null
if (noProxy === '*') {
return null
}
// if the noProxy is not empty and the uri is found return null
if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
return null
}
// Check for HTTP or HTTPS Proxy in environment Else default to null
if (uri.protocol === 'http:') {
return process.env.HTTP_PROXY ||
process.env.http_proxy || null
}
if (uri.protocol === 'https:') {
return process.env.HTTPS_PROXY ||
process.env.https_proxy ||
process.env.HTTP_PROXY ||
process.env.http_proxy || null
}
// if none of that works, return null
// (What uri protocol are you using then?)
return null
}
module.exports = getProxyFromURI

View File

@ -0,0 +1,200 @@
'use strict'
var fs = require('fs')
var qs = require('querystring')
var extend = require('extend')
function Har (request) {
this.request = request
}
Har.prototype.reducer = function (obj, pair) {
// new property ?
if (obj[pair.name] === undefined) {
obj[pair.name] = pair.value
return obj
}
// existing? convert to array
var arr = [
obj[pair.name],
pair.value
]
obj[pair.name] = arr
return obj
}
Har.prototype.prep = function (data) {
// construct utility properties
data.queryObj = {}
data.headersObj = {}
data.postData.jsonObj = false
data.postData.paramsObj = false
// construct query objects
if (data.queryString && data.queryString.length) {
data.queryObj = data.queryString.reduce(this.reducer, {})
}
// construct headers objects
if (data.headers && data.headers.length) {
// loweCase header keys
data.headersObj = data.headers.reduceRight(function (headers, header) {
headers[header.name] = header.value
return headers
}, {})
}
// construct Cookie header
if (data.cookies && data.cookies.length) {
var cookies = data.cookies.map(function (cookie) {
return cookie.name + '=' + cookie.value
})
if (cookies.length) {
data.headersObj.cookie = cookies.join('; ')
}
}
// prep body
function some (arr) {
return arr.some(function (type) {
return data.postData.mimeType.indexOf(type) === 0
})
}
if (some([
'multipart/mixed',
'multipart/related',
'multipart/form-data',
'multipart/alternative'])) {
// reset values
data.postData.mimeType = 'multipart/form-data'
} else if (some([
'application/x-www-form-urlencoded'])) {
if (!data.postData.params) {
data.postData.text = ''
} else {
data.postData.paramsObj = data.postData.params.reduce(this.reducer, {})
// always overwrite
data.postData.text = qs.stringify(data.postData.paramsObj)
}
} else if (some([
'text/json',
'text/x-json',
'application/json',
'application/x-json'])) {
data.postData.mimeType = 'application/json'
if (data.postData.text) {
try {
data.postData.jsonObj = JSON.parse(data.postData.text)
} catch (e) {
this.request.debug(e)
// force back to text/plain
data.postData.mimeType = 'text/plain'
}
}
}
return data
}
Har.prototype.options = function (options) {
// skip if no har property defined
if (!options.har) {
return options
}
var har = {}
extend(har, options.har)
// only process the first entry
if (har.log && har.log.entries) {
har = har.log.entries[0]
}
// add optional properties to make validation successful
har.url = har.url || options.url || options.uri || options.baseUrl || '/'
har.httpVersion = har.httpVersion || 'HTTP/1.1'
har.queryString = har.queryString || []
har.headers = har.headers || []
har.cookies = har.cookies || []
har.postData = har.postData || {}
har.postData.mimeType = har.postData.mimeType || 'application/octet-stream'
har.bodySize = 0
har.headersSize = 0
har.postData.size = 0
// clean up and get some utility properties
var req = this.prep(har)
// construct new options
if (req.url) {
options.url = req.url
}
if (req.method) {
options.method = req.method
}
if (Object.keys(req.queryObj).length) {
options.qs = req.queryObj
}
if (Object.keys(req.headersObj).length) {
options.headers = req.headersObj
}
function test (type) {
return req.postData.mimeType.indexOf(type) === 0
}
if (test('application/x-www-form-urlencoded')) {
options.form = req.postData.paramsObj
} else if (test('application/json')) {
if (req.postData.jsonObj) {
options.body = req.postData.jsonObj
options.json = true
}
} else if (test('multipart/form-data')) {
options.formData = {}
req.postData.params.forEach(function (param) {
var attachment = {}
if (!param.fileName && !param.contentType) {
options.formData[param.name] = param.value
return
}
// attempt to read from disk!
if (param.fileName && !param.value) {
attachment.value = fs.createReadStream(param.fileName)
} else if (param.value) {
attachment.value = param.value
}
if (param.fileName) {
attachment.options = {
filename: param.fileName,
contentType: param.contentType ? param.contentType : null
}
}
options.formData[param.name] = attachment
})
} else {
if (req.postData.text) {
options.body = req.postData.text
}
}
return options
}
exports.Har = Har

View File

@ -0,0 +1,89 @@
'use strict'
var crypto = require('crypto')
function randomString (size) {
var bits = (size + 1) * 6
var buffer = crypto.randomBytes(Math.ceil(bits / 8))
var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
return string.slice(0, size)
}
function calculatePayloadHash (payload, algorithm, contentType) {
var hash = crypto.createHash(algorithm)
hash.update('hawk.1.payload\n')
hash.update((contentType ? contentType.split(';')[0].trim().toLowerCase() : '') + '\n')
hash.update(payload || '')
hash.update('\n')
return hash.digest('base64')
}
exports.calculateMac = function (credentials, opts) {
var normalized = 'hawk.1.header\n' +
opts.ts + '\n' +
opts.nonce + '\n' +
(opts.method || '').toUpperCase() + '\n' +
opts.resource + '\n' +
opts.host.toLowerCase() + '\n' +
opts.port + '\n' +
(opts.hash || '') + '\n'
if (opts.ext) {
normalized = normalized + opts.ext.replace('\\', '\\\\').replace('\n', '\\n')
}
normalized = normalized + '\n'
if (opts.app) {
normalized = normalized + opts.app + '\n' + (opts.dlg || '') + '\n'
}
var hmac = crypto.createHmac(credentials.algorithm, credentials.key).update(normalized)
var digest = hmac.digest('base64')
return digest
}
exports.header = function (uri, method, opts) {
var timestamp = opts.timestamp || Math.floor((Date.now() + (opts.localtimeOffsetMsec || 0)) / 1000)
var credentials = opts.credentials
if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
return ''
}
if (['sha1', 'sha256'].indexOf(credentials.algorithm) === -1) {
return ''
}
var artifacts = {
ts: timestamp,
nonce: opts.nonce || randomString(6),
method: method,
resource: uri.pathname + (uri.search || ''),
host: uri.hostname,
port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
hash: opts.hash,
ext: opts.ext,
app: opts.app,
dlg: opts.dlg
}
if (!artifacts.hash && (opts.payload || opts.payload === '')) {
artifacts.hash = calculatePayloadHash(opts.payload, credentials.algorithm, opts.contentType)
}
var mac = exports.calculateMac(credentials, artifacts)
var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''
var header = 'Hawk id="' + credentials.id +
'", ts="' + artifacts.ts +
'", nonce="' + artifacts.nonce +
(artifacts.hash ? '", hash="' + artifacts.hash : '') +
(hasExt ? '", ext="' + artifacts.ext.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '') +
'", mac="' + mac + '"'
if (artifacts.app) {
header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"'
}
return header
}

View File

@ -0,0 +1,66 @@
'use strict'
var jsonSafeStringify = require('json-stringify-safe')
var crypto = require('crypto')
var Buffer = require('safe-buffer').Buffer
var defer = typeof setImmediate === 'undefined'
? process.nextTick
: setImmediate
function paramsHaveRequestBody (params) {
return (
params.body ||
params.requestBodyStream ||
(params.json && typeof params.json !== 'boolean') ||
params.multipart
)
}
function safeStringify (obj, replacer) {
var ret
try {
ret = JSON.stringify(obj, replacer)
} catch (e) {
ret = jsonSafeStringify(obj, replacer)
}
return ret
}
function md5 (str) {
return crypto.createHash('md5').update(str).digest('hex')
}
function isReadStream (rs) {
return rs.readable && rs.path && rs.mode
}
function toBase64 (str) {
return Buffer.from(str || '', 'utf8').toString('base64')
}
function copy (obj) {
var o = {}
Object.keys(obj).forEach(function (i) {
o[i] = obj[i]
})
return o
}
function version () {
var numbers = process.version.replace('v', '').split('.')
return {
major: parseInt(numbers[0], 10),
minor: parseInt(numbers[1], 10),
patch: parseInt(numbers[2], 10)
}
}
exports.paramsHaveRequestBody = paramsHaveRequestBody
exports.safeStringify = safeStringify
exports.md5 = md5
exports.isReadStream = isReadStream
exports.toBase64 = toBase64
exports.copy = copy
exports.version = version
exports.defer = defer

View File

@ -0,0 +1,112 @@
'use strict'
var { v4: uuid } = require('uuid')
var CombinedStream = require('combined-stream')
var isstream = require('isstream')
var Buffer = require('safe-buffer').Buffer
function Multipart (request) {
this.request = request
this.boundary = uuid()
this.chunked = false
this.body = null
}
Multipart.prototype.isChunked = function (options) {
var self = this
var chunked = false
var parts = options.data || options
if (!parts.forEach) {
self.request.emit('error', new Error('Argument error, options.multipart.'))
}
if (options.chunked !== undefined) {
chunked = options.chunked
}
if (self.request.getHeader('transfer-encoding') === 'chunked') {
chunked = true
}
if (!chunked) {
parts.forEach(function (part) {
if (typeof part.body === 'undefined') {
self.request.emit('error', new Error('Body attribute missing in multipart.'))
}
if (isstream(part.body)) {
chunked = true
}
})
}
return chunked
}
Multipart.prototype.setHeaders = function (chunked) {
var self = this
if (chunked && !self.request.hasHeader('transfer-encoding')) {
self.request.setHeader('transfer-encoding', 'chunked')
}
var header = self.request.getHeader('content-type')
if (!header || header.indexOf('multipart') === -1) {
self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
} else {
if (header.indexOf('boundary') !== -1) {
self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1')
} else {
self.request.setHeader('content-type', header + '; boundary=' + self.boundary)
}
}
}
Multipart.prototype.build = function (parts, chunked) {
var self = this
var body = chunked ? new CombinedStream() : []
function add (part) {
if (typeof part === 'number') {
part = part.toString()
}
return chunked ? body.append(part) : body.push(Buffer.from(part))
}
if (self.request.preambleCRLF) {
add('\r\n')
}
parts.forEach(function (part) {
var preamble = '--' + self.boundary + '\r\n'
Object.keys(part).forEach(function (key) {
if (key === 'body') { return }
preamble += key + ': ' + part[key] + '\r\n'
})
preamble += '\r\n'
add(preamble)
add(part.body)
add('\r\n')
})
add('--' + self.boundary + '--')
if (self.request.postambleCRLF) {
add('\r\n')
}
return body
}
Multipart.prototype.onRequest = function (options) {
var self = this
var chunked = self.isChunked(options)
var parts = options.data || options
self.setHeaders(chunked)
self.chunked = chunked
self.body = self.build(parts, chunked)
}
exports.Multipart = Multipart

View File

@ -0,0 +1,50 @@
'use strict'
var qs = require('qs')
var querystring = require('querystring')
function Querystring (request) {
this.request = request
this.lib = null
this.useQuerystring = null
this.parseOptions = null
this.stringifyOptions = null
}
Querystring.prototype.init = function (options) {
if (this.lib) { return }
this.useQuerystring = options.useQuerystring
this.lib = (this.useQuerystring ? querystring : qs)
this.parseOptions = options.qsParseOptions || {}
this.stringifyOptions = options.qsStringifyOptions || {}
}
Querystring.prototype.stringify = function (obj) {
return (this.useQuerystring)
? this.rfc3986(this.lib.stringify(obj,
this.stringifyOptions.sep || null,
this.stringifyOptions.eq || null,
this.stringifyOptions))
: this.lib.stringify(obj, this.stringifyOptions)
}
Querystring.prototype.parse = function (str) {
return (this.useQuerystring)
? this.lib.parse(str,
this.parseOptions.sep || null,
this.parseOptions.eq || null,
this.parseOptions)
: this.lib.parse(str, this.parseOptions)
}
Querystring.prototype.rfc3986 = function (str) {
return str.replace(/[!'()*]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
Querystring.prototype.unescape = querystring.unescape
exports.Querystring = Querystring

View File

@ -0,0 +1,175 @@
'use strict'
var url = require('url')
var isUrl = /^https?:/
function Redirect (request) {
this.request = request
this.followRedirect = true
this.followRedirects = true
this.followAllRedirects = false
this.followOriginalHttpMethod = false
this.allowRedirect = function () { return true }
this.maxRedirects = 10
this.redirects = []
this.redirectsFollowed = 0
this.removeRefererHeader = false
}
Redirect.prototype.onRequest = function (options) {
var self = this
if (options.maxRedirects !== undefined) {
self.maxRedirects = options.maxRedirects
}
if (typeof options.followRedirect === 'function') {
self.allowRedirect = options.followRedirect
}
if (options.followRedirect !== undefined) {
self.followRedirects = !!options.followRedirect
}
if (options.followAllRedirects !== undefined) {
self.followAllRedirects = options.followAllRedirects
}
if (self.followRedirects || self.followAllRedirects) {
self.redirects = self.redirects || []
}
if (options.removeRefererHeader !== undefined) {
self.removeRefererHeader = options.removeRefererHeader
}
if (options.followOriginalHttpMethod !== undefined) {
self.followOriginalHttpMethod = options.followOriginalHttpMethod
}
}
Redirect.prototype.redirectTo = function (response) {
var self = this
var request = self.request
var redirectTo = null
if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) {
var location = response.caseless.get('location')
request.debug('redirect', location)
if (self.followAllRedirects) {
redirectTo = location
} else if (self.followRedirects) {
switch (request.method) {
case 'PATCH':
case 'PUT':
case 'POST':
case 'DELETE':
// Do not follow redirects
break
default:
redirectTo = location
break
}
}
} else if (response.statusCode === 401) {
var authHeader = request._auth.onResponse(response)
if (authHeader) {
request.setHeader('authorization', authHeader)
redirectTo = request.uri
}
}
return redirectTo
}
Redirect.prototype.onResponse = function (response, callback) {
var self = this
var request = self.request
var redirectTo = self.redirectTo(response)
if (!redirectTo) return callback(null, false)
function processRedirect (shouldRedirect) {
if (!shouldRedirect) return callback(null, false)
if (typeof shouldRedirect === 'string') {
// overridden redirect url
request.debug('redirect overridden', redirectTo)
redirectTo = shouldRedirect
}
request.debug('redirect to', redirectTo)
// ignore any potential response body. it cannot possibly be useful
// to us at this point.
// response.resume should be defined, but check anyway before calling. Workaround for browserify.
if (response.resume) {
response.resume()
}
if (self.redirectsFollowed >= self.maxRedirects) {
return callback(new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href))
}
self.redirectsFollowed += 1
if (!isUrl.test(redirectTo)) {
redirectTo = url.resolve(request.uri.href, redirectTo)
}
var uriPrev = request.uri
request.uri = url.parse(redirectTo)
// handle the case where we change protocol from https to http or vice versa
if (request.uri.protocol !== uriPrev.protocol) {
delete request.agent
}
self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo })
if (self.followAllRedirects && request.method !== 'HEAD' &&
response.statusCode !== 401 && response.statusCode !== 307) {
request.method = self.followOriginalHttpMethod ? request.method : 'GET'
}
// request.method = 'GET' // Force all redirects to use GET || commented out fixes #215
delete request.src
delete request.req
delete request._started
if (response.statusCode !== 401 && response.statusCode !== 307) {
// Remove parameters from the previous response, unless this is the second request
// for a server that requires digest authentication.
delete request.body
delete request._form
if (request.headers) {
request.removeHeader('host')
request.removeHeader('content-type')
request.removeHeader('content-length')
if (request.uri.hostname !== request.originalHost.split(':')[0]) {
// Remove authorization if changing hostnames (but not if just
// changing ports or protocols). This matches the behavior of curl:
// https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710
request.removeHeader('authorization')
}
}
}
if (!self.removeRefererHeader) {
request.setHeader('referer', uriPrev.href)
}
request.emit('redirect')
request.init()
callback(null, true)
}
// test allowRedirect arity; if has more than one argument,
// assume it's asynchronous via a callback
if (self.allowRedirect.length > 1) {
return self.allowRedirect.call(request, response, function (err, result) {
if (err) return callback(err)
processRedirect(result)
})
}
var allowsRedirect = self.allowRedirect.call(request, response)
if (allowsRedirect && allowsRedirect.then) {
return allowsRedirect.then(processRedirect, callback)
}
// treat as a regular boolean
processRedirect(allowsRedirect)
}
exports.Redirect = Redirect

View File

@ -0,0 +1,175 @@
'use strict'
var url = require('url')
var tunnel = require('tunnel-agent')
var defaultProxyHeaderWhiteList = [
'accept',
'accept-charset',
'accept-encoding',
'accept-language',
'accept-ranges',
'cache-control',
'content-encoding',
'content-language',
'content-location',
'content-md5',
'content-range',
'content-type',
'connection',
'date',
'expect',
'max-forwards',
'pragma',
'referer',
'te',
'user-agent',
'via'
]
var defaultProxyHeaderExclusiveList = [
'proxy-authorization'
]
function constructProxyHost (uriObject) {
var port = uriObject.port
var protocol = uriObject.protocol
var proxyHost = uriObject.hostname + ':'
if (port) {
proxyHost += port
} else if (protocol === 'https:') {
proxyHost += '443'
} else {
proxyHost += '80'
}
return proxyHost
}
function constructProxyHeaderWhiteList (headers, proxyHeaderWhiteList) {
var whiteList = proxyHeaderWhiteList
.reduce(function (set, header) {
set[header.toLowerCase()] = true
return set
}, {})
return Object.keys(headers)
.filter(function (header) {
return whiteList[header.toLowerCase()]
})
.reduce(function (set, header) {
set[header] = headers[header]
return set
}, {})
}
function constructTunnelOptions (request, proxyHeaders) {
var proxy = request.proxy
var tunnelOptions = {
proxy: {
host: proxy.hostname,
port: +proxy.port,
proxyAuth: proxy.auth,
headers: proxyHeaders
},
headers: request.headers,
ca: request.ca,
cert: request.cert,
key: request.key,
passphrase: request.passphrase,
pfx: request.pfx,
ciphers: request.ciphers,
rejectUnauthorized: request.rejectUnauthorized,
secureOptions: request.secureOptions,
secureProtocol: request.secureProtocol
}
return tunnelOptions
}
function constructTunnelFnName (uri, proxy) {
var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http')
var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http')
return [uriProtocol, proxyProtocol].join('Over')
}
function getTunnelFn (request) {
var uri = request.uri
var proxy = request.proxy
var tunnelFnName = constructTunnelFnName(uri, proxy)
return tunnel[tunnelFnName]
}
function Tunnel (request) {
this.request = request
this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList
this.proxyHeaderExclusiveList = []
if (typeof request.tunnel !== 'undefined') {
this.tunnelOverride = request.tunnel
}
}
Tunnel.prototype.isEnabled = function () {
var self = this
var request = self.request
// Tunnel HTTPS by default. Allow the user to override this setting.
// If self.tunnelOverride is set (the user specified a value), use it.
if (typeof self.tunnelOverride !== 'undefined') {
return self.tunnelOverride
}
// If the destination is HTTPS, tunnel.
if (request.uri.protocol === 'https:') {
return true
}
// Otherwise, do not use tunnel.
return false
}
Tunnel.prototype.setup = function (options) {
var self = this
var request = self.request
options = options || {}
if (typeof request.proxy === 'string') {
request.proxy = url.parse(request.proxy)
}
if (!request.proxy || !request.tunnel) {
return false
}
// Setup Proxy Header Exclusive List and White List
if (options.proxyHeaderWhiteList) {
self.proxyHeaderWhiteList = options.proxyHeaderWhiteList
}
if (options.proxyHeaderExclusiveList) {
self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList
}
var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList)
var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList)
// Setup Proxy Headers and Proxy Headers Host
// Only send the Proxy White Listed Header names
var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList)
proxyHeaders.host = constructProxyHost(request.uri)
proxyHeaderExclusiveList.forEach(request.removeHeader, request)
// Set Agent from Tunnel Data
var tunnelFn = getTunnelFn(request)
var tunnelOptions = constructTunnelOptions(request, proxyHeaders)
request.agent = tunnelFn(tunnelOptions)
return true
}
Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList
Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList
exports.Tunnel = Tunnel

View File

@ -0,0 +1,84 @@
{
"name": "@cypress/request",
"description": "Cypress's fork of a simplified HTTP request client.",
"keywords": [
"http",
"simple",
"util",
"utility"
],
"version": "2.88.12",
"author": "Mikeal Rogers <mikeal.rogers@gmail.com>",
"repository": {
"type": "git",
"url": "https://github.com/cypress-io/request.git"
},
"bugs": {
"url": "http://github.com/cypress-io/request/issues"
},
"license": "Apache-2.0",
"engines": {
"node": ">= 6"
},
"main": "index.js",
"files": [
"lib/",
"index.js",
"request.js"
],
"dependencies": {
"aws-sign2": "~0.7.0",
"aws4": "^1.8.0",
"caseless": "~0.12.0",
"combined-stream": "~1.0.6",
"extend": "~3.0.2",
"forever-agent": "~0.6.1",
"form-data": "~2.3.2",
"http-signature": "~1.3.6",
"is-typedarray": "~1.0.0",
"isstream": "~0.1.2",
"json-stringify-safe": "~5.0.1",
"mime-types": "~2.1.19",
"performance-now": "^2.1.0",
"qs": "~6.10.3",
"safe-buffer": "^5.1.2",
"tough-cookie": "^4.1.3",
"tunnel-agent": "^0.6.0",
"uuid": "^8.3.2"
},
"scripts": {
"test": "npm run lint && npm run test-ci && npm run test-browser",
"test-ci": "tap --no-check-coverage tests/test-*.js",
"test-cov": "nyc --reporter=lcov tape tests/test-*.js",
"test-browser": "echo 'Skipping browser tests.' || node tests/browser/start.js",
"lint": "standard"
},
"devDependencies": {
"bluebird": "^3.2.1",
"browserify": "^13.0.1",
"browserify-istanbul": "^2.0.0",
"buffer-equal": "^1.0.0",
"codecov": "^3.0.4",
"coveralls": "^3.0.2",
"function-bind": "^1.0.2",
"karma": "^3.0.0",
"karma-browserify": "^5.0.1",
"karma-cli": "^2.0.0",
"karma-coverage": "^2.0.3",
"karma-phantomjs-launcher": "^1.0.0",
"karma-tap": "^4.2.0",
"nyc": "^15.1.0",
"phantomjs-prebuilt": "^2.1.3",
"rimraf": "^2.2.8",
"server-destroy": "^1.0.1",
"standard": "^9.0.0",
"tap": "^15.1.5",
"tape": "^4.6.0"
},
"greenkeeper": {
"ignore": [
"hawk",
"har-validator"
]
}
}

File diff suppressed because it is too large Load Diff

20
CY_Auta_TS/automaty/node_modules/@cypress/xvfb/LICENSE generated vendored Normal file
View File

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

View File

@ -0,0 +1,48 @@
## @cypress/xvfb
> easily start and stop an X Virtual Frame Buffer from your node apps.
[![CircleCI](https://circleci.com/gh/cypress-io/xvfb/tree/master.svg?style=svg)](https://circleci.com/gh/cypress-io/xvfb/tree/master)
[![Build Status](https://travis-ci.org/cypress-io/xvfb.svg?branch=master)](https://travis-ci.org/cypress-io/xvfb)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) [![renovate-app badge][renovate-badge]][renovate-app]
### Usage
```javascript
var Xvfb = require('xvfb');
var options = {}; // optional
var xvfb = new Xvfb(options);
xvfb.start(function(err, xvfbProcess) {
// code that uses the virtual frame buffer here
xvfb.stop(function(err) {
// the Xvfb is stopped
});
});
```
The Xvfb constructor takes four options:
* <code>displayNum</code> - the X display to use, defaults to the lowest unused display number >= 99 if <code>reuse</code> is false or 99 if <code>reuse</code> is true.
* <code>reuse</code> - whether to reuse an existing Xvfb instance if it already exists on the X display referenced by displayNum.
* <code>timeout</code> - number of milliseconds to wait when starting Xvfb before assuming it failed to start, defaults to 2000.
* <code>silent</code> - don't pipe Xvfb stderr to the process's stderr.
* <code>xvfb_args</code> - Extra arguments to pass to `Xvfb`.
* <code>onStderrData</code> - Function to receive `stderr` output
### Debugging
Run with `DEBUG=xvfb` environment variable to see debug messages. If you want
to see log messages from the Xvfb process itself, use `DEBUG=xvfb,xvfb-process`.
### Thanks to
Forked from [node-xvfb](https://github.com/Rob--W/node-xvfb)
* [kesla](https://github.com/kesla) for https://github.com/kesla/node-headless
* [leonid-shevtsov](https://github.com/leonid-shevtsov) for https://github.com/leonid-shevtsov/headless
* [paulbaumgart](https://github.com/paulbaumgart) for creating the initial version of this package.
both of which served as inspiration for this package.
[renovate-badge]: https://img.shields.io/badge/renovate-app-blue.svg
[renovate-app]: https://renovateapp.com/

221
CY_Auta_TS/automaty/node_modules/@cypress/xvfb/index.js generated vendored Normal file
View File

@ -0,0 +1,221 @@
/* eslint-disable node/no-deprecated-api */
'use strict'
// our debug log messages
const debug = require('debug')('xvfb')
const once = require('lodash.once')
const fs = require('fs')
const path = require('path')
const spawn = require('child_process').spawn
fs.exists = fs.exists || path.exists
fs.existsSync = fs.existsSync || path.existsSync
function Xvfb(options) {
options = options || {}
this._display = options.displayNum ? `:${options.displayNum}` : null
this._reuse = options.reuse
this._timeout = options.timeout || options.timeOut || 2000
this._silent = options.silent
this._onStderrData = options.onStderrData || (() => {})
this._xvfb_args = options.xvfb_args || []
}
Xvfb.prototype = {
start(cb) {
let self = this
if (!self._process) {
let lockFile = self._lockFile()
self._setDisplayEnvVariable()
fs.exists(lockFile, function(exists) {
let didSpawnFail = false
try {
self._spawnProcess(exists, function(e) {
debug('XVFB spawn failed')
debug(e)
didSpawnFail = true
if (cb) cb(e)
})
} catch (e) {
debug('spawn process error')
debug(e)
return cb && cb(e)
}
let totalTime = 0
;(function checkIfStarted() {
debug('checking if started by looking for the lock file', lockFile)
fs.exists(lockFile, function(exists) {
if (didSpawnFail) {
// When spawn fails, the callback will immediately be called.
// So we don't have to check whether the lock file exists.
debug('while checking for lock file, saw that spawn failed')
return
}
if (exists) {
debug('lock file %s found after %d ms', lockFile, totalTime)
return cb && cb(null, self._process)
} else {
totalTime += 10
if (totalTime > self._timeout) {
debug(
'could not start XVFB after %d ms (timeout %d ms)',
totalTime,
self._timeout
)
const err = new Error('Could not start Xvfb.')
err.timedOut = true
return cb && cb(err)
} else {
setTimeout(checkIfStarted, 10)
}
}
})
})()
})
}
},
stop(cb) {
let self = this
if (self._process) {
self._killProcess()
self._restoreDisplayEnvVariable()
let lockFile = self._lockFile()
debug('lock file', lockFile)
let totalTime = 0
;(function checkIfStopped() {
fs.exists(lockFile, function(exists) {
if (!exists) {
debug('lock file %s not found when stopping', lockFile)
return cb && cb(null, self._process)
} else {
totalTime += 10
if (totalTime > self._timeout) {
debug('lock file %s is still there', lockFile)
debug(
'after waiting for %d ms (timeout %d ms)',
totalTime,
self._timeout
)
const err = new Error('Could not stop Xvfb.')
err.timedOut = true
return cb && cb(err)
} else {
setTimeout(checkIfStopped, 10)
}
}
})
})()
} else {
return cb && cb(null)
}
},
display() {
if (!this._display) {
let displayNum = 98
let lockFile
do {
displayNum++
lockFile = this._lockFile(displayNum)
} while (!this._reuse && fs.existsSync(lockFile))
this._display = `:${displayNum}`
}
return this._display
},
_setDisplayEnvVariable() {
this._oldDisplay = process.env.DISPLAY
process.env.DISPLAY = this.display()
debug('setting DISPLAY %s', process.env.DISPLAY)
},
_restoreDisplayEnvVariable() {
debug('restoring process.env.DISPLAY variable')
// https://github.com/cypress-io/xvfb/issues/1
// only reset truthy backed' up values
if (this._oldDisplay) {
process.env.DISPLAY = this._oldDisplay
} else {
// else delete the values to get back
// to undefined
delete process.env.DISPLAY
}
},
_spawnProcess(lockFileExists, onAsyncSpawnError) {
let self = this
const onError = once(onAsyncSpawnError)
let display = self.display()
if (lockFileExists) {
if (!self._reuse) {
throw new Error(
`Display ${display} is already in use and the "reuse" option is false.`
)
}
} else {
const stderr = []
const allArguments = [display].concat(self._xvfb_args)
debug('all Xvfb arguments', allArguments)
self._process = spawn('Xvfb', allArguments)
self._process.stderr.on('data', function(data) {
stderr.push(data.toString())
if (self._silent) {
return
}
self._onStderrData(data)
})
self._process.on('close', (code, signal) => {
if (code !== 0) {
const str = stderr.join('\n')
debug('xvfb closed with error code', code)
debug('after receiving signal %s', signal)
debug('and stderr output')
debug(str)
const err = new Error(str)
err.nonZeroExitCode = true
onError(err)
}
})
// Bind an error listener to prevent an error from crashing node.
self._process.once('error', function(e) {
debug('xvfb spawn process error')
debug(e)
onError(e)
})
}
},
_killProcess() {
this._process.kill()
this._process = null
},
_lockFile(displayNum) {
displayNum =
displayNum ||
this.display()
.toString()
.replace(/^:/, '')
const filename = `/tmp/.X${displayNum}-lock`
debug('lock filename %s', filename)
return filename
},
}
module.exports = Xvfb

View File

@ -0,0 +1,395 @@
3.1.0 / 2017-09-26
==================
* Add `DEBUG_HIDE_DATE` env var (#486)
* Remove ReDoS regexp in %o formatter (#504)
* Remove "component" from package.json
* Remove `component.json`
* Ignore package-lock.json
* Examples: fix colors printout
* Fix: browser detection
* Fix: spelling mistake (#496, @EdwardBetts)
3.0.1 / 2017-08-24
==================
* Fix: Disable colors in Edge and Internet Explorer (#489)
3.0.0 / 2017-08-08
==================
* Breaking: Remove DEBUG_FD (#406)
* Breaking: Use `Date#toISOString()` instead to `Date#toUTCString()` when output is not a TTY (#418)
* Breaking: Make millisecond timer namespace specific and allow 'always enabled' output (#408)
* Addition: document `enabled` flag (#465)
* Addition: add 256 colors mode (#481)
* Addition: `enabled()` updates existing debug instances, add `destroy()` function (#440)
* Update: component: update "ms" to v2.0.0
* Update: separate the Node and Browser tests in Travis-CI
* Update: refactor Readme, fixed documentation, added "Namespace Colors" section, redid screenshots
* Update: separate Node.js and web browser examples for organization
* Update: update "browserify" to v14.4.0
* Fix: fix Readme typo (#473)
2.6.9 / 2017-09-22
==================
* remove ReDoS regexp in %o formatter (#504)
2.6.8 / 2017-05-18
==================
* Fix: Check for undefined on browser globals (#462, @marbemac)
2.6.7 / 2017-05-16
==================
* Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom)
* Fix: Inline extend function in node implementation (#452, @dougwilson)
* Docs: Fix typo (#455, @msasad)
2.6.5 / 2017-04-27
==================
* Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek)
* Misc: clean up browser reference checks (#447, @thebigredgeek)
* Misc: add npm-debug.log to .gitignore (@thebigredgeek)
2.6.4 / 2017-04-20
==================
* Fix: bug that would occur if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo)
* Chore: ignore bower.json in npm installations. (#437, @joaovieira)
* Misc: update "ms" to v0.7.3 (@tootallnate)
2.6.3 / 2017-03-13
==================
* Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts)
* Docs: Changelog fix (@thebigredgeek)
2.6.2 / 2017-03-10
==================
* Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin)
* Docs: Add backers and sponsors from Open Collective (#422, @piamancini)
* Docs: Add Slackin invite badge (@tootallnate)
2.6.1 / 2017-02-10
==================
* Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error
* Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0)
* Fix: IE8 "Expected identifier" error (#414, @vgoma)
* Fix: Namespaces would not disable once enabled (#409, @musikov)
2.6.0 / 2016-12-28
==================
* Fix: added better null pointer checks for browser useColors (@thebigredgeek)
* Improvement: removed explicit `window.debug` export (#404, @tootallnate)
* Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate)
2.5.2 / 2016-12-25
==================
* Fix: reference error on window within webworkers (#393, @KlausTrainer)
* Docs: fixed README typo (#391, @lurch)
* Docs: added notice about v3 api discussion (@thebigredgeek)
2.5.1 / 2016-12-20
==================
* Fix: babel-core compatibility
2.5.0 / 2016-12-20
==================
* Fix: wrong reference in bower file (@thebigredgeek)
* Fix: webworker compatibility (@thebigredgeek)
* Fix: output formatting issue (#388, @kribblo)
* Fix: babel-loader compatibility (#383, @escwald)
* Misc: removed built asset from repo and publications (@thebigredgeek)
* Misc: moved source files to /src (#378, @yamikuronue)
* Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue)
* Test: coveralls integration (#378, @yamikuronue)
* Docs: simplified language in the opening paragraph (#373, @yamikuronue)
2.4.5 / 2016-12-17
==================
* Fix: `navigator` undefined in Rhino (#376, @jochenberger)
* Fix: custom log function (#379, @hsiliev)
* Improvement: bit of cleanup + linting fixes (@thebigredgeek)
* Improvement: rm non-maintainted `dist/` dir (#375, @freewil)
* Docs: simplified language in the opening paragraph. (#373, @yamikuronue)
2.4.4 / 2016-12-14
==================
* Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts)
2.4.3 / 2016-12-14
==================
* Fix: navigation.userAgent error for react native (#364, @escwald)
2.4.2 / 2016-12-14
==================
* Fix: browser colors (#367, @tootallnate)
* Misc: travis ci integration (@thebigredgeek)
* Misc: added linting and testing boilerplate with sanity check (@thebigredgeek)
2.4.1 / 2016-12-13
==================
* Fix: typo that broke the package (#356)
2.4.0 / 2016-12-13
==================
* Fix: bower.json references unbuilt src entry point (#342, @justmatt)
* Fix: revert "handle regex special characters" (@tootallnate)
* Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate)
* Feature: %O`(big O) pretty-prints objects (#322, @tootallnate)
* Improvement: allow colors in workers (#335, @botverse)
* Improvement: use same color for same namespace. (#338, @lchenay)
2.3.3 / 2016-11-09
==================
* Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne)
* Fix: Returning `localStorage` saved values (#331, Levi Thomason)
* Improvement: Don't create an empty object when no `process` (Nathan Rajlich)
2.3.2 / 2016-11-09
==================
* Fix: be super-safe in index.js as well (@TooTallNate)
* Fix: should check whether process exists (Tom Newby)
2.3.1 / 2016-11-09
==================
* Fix: Added electron compatibility (#324, @paulcbetts)
* Improvement: Added performance optimizations (@tootallnate)
* Readme: Corrected PowerShell environment variable example (#252, @gimre)
* Misc: Removed yarn lock file from source control (#321, @fengmk2)
2.3.0 / 2016-11-07
==================
* Fix: Consistent placement of ms diff at end of output (#215, @gorangajic)
* Fix: Escaping of regex special characters in namespace strings (#250, @zacronos)
* Fix: Fixed bug causing crash on react-native (#282, @vkarpov15)
* Feature: Enabled ES6+ compatible import via default export (#212 @bucaran)
* Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom)
* Package: Update "ms" to 0.7.2 (#315, @DevSide)
* Package: removed superfluous version property from bower.json (#207 @kkirsche)
* Readme: fix USE_COLORS to DEBUG_COLORS
* Readme: Doc fixes for format string sugar (#269, @mlucool)
* Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0)
* Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable)
* Readme: better docs for browser support (#224, @matthewmueller)
* Tooling: Added yarn integration for development (#317, @thebigredgeek)
* Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek)
* Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman)
* Misc: Updated contributors (@thebigredgeek)
2.2.0 / 2015-05-09
==================
* package: update "ms" to v0.7.1 (#202, @dougwilson)
* README: add logging to file example (#193, @DanielOchoa)
* README: fixed a typo (#191, @amir-s)
* browser: expose `storage` (#190, @stephenmathieson)
* Makefile: add a `distclean` target (#189, @stephenmathieson)
2.1.3 / 2015-03-13
==================
* Updated stdout/stderr example (#186)
* Updated example/stdout.js to match debug current behaviour
* Renamed example/stderr.js to stdout.js
* Update Readme.md (#184)
* replace high intensity foreground color for bold (#182, #183)
2.1.2 / 2015-03-01
==================
* dist: recompile
* update "ms" to v0.7.0
* package: update "browserify" to v9.0.3
* component: fix "ms.js" repo location
* changed bower package name
* updated documentation about using debug in a browser
* fix: security error on safari (#167, #168, @yields)
2.1.1 / 2014-12-29
==================
* browser: use `typeof` to check for `console` existence
* browser: check for `console.log` truthiness (fix IE 8/9)
* browser: add support for Chrome apps
* Readme: added Windows usage remarks
* Add `bower.json` to properly support bower install
2.1.0 / 2014-10-15
==================
* node: implement `DEBUG_FD` env variable support
* package: update "browserify" to v6.1.0
* package: add "license" field to package.json (#135, @panuhorsmalahti)
2.0.0 / 2014-09-01
==================
* package: update "browserify" to v5.11.0
* node: use stderr rather than stdout for logging (#29, @stephenmathieson)
1.0.4 / 2014-07-15
==================
* dist: recompile
* example: remove `console.info()` log usage
* example: add "Content-Type" UTF-8 header to browser example
* browser: place %c marker after the space character
* browser: reset the "content" color via `color: inherit`
* browser: add colors support for Firefox >= v31
* debug: prefer an instance `log()` function over the global one (#119)
* Readme: update documentation about styled console logs for FF v31 (#116, @wryk)
1.0.3 / 2014-07-09
==================
* Add support for multiple wildcards in namespaces (#122, @seegno)
* browser: fix lint
1.0.2 / 2014-06-10
==================
* browser: update color palette (#113, @gscottolson)
* common: make console logging function configurable (#108, @timoxley)
* node: fix %o colors on old node <= 0.8.x
* Makefile: find node path using shell/which (#109, @timoxley)
1.0.1 / 2014-06-06
==================
* browser: use `removeItem()` to clear localStorage
* browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777)
* package: add "contributors" section
* node: fix comment typo
* README: list authors
1.0.0 / 2014-06-04
==================
* make ms diff be global, not be scope
* debug: ignore empty strings in enable()
* node: make DEBUG_COLORS able to disable coloring
* *: export the `colors` array
* npmignore: don't publish the `dist` dir
* Makefile: refactor to use browserify
* package: add "browserify" as a dev dependency
* Readme: add Web Inspector Colors section
* node: reset terminal color for the debug content
* node: map "%o" to `util.inspect()`
* browser: map "%j" to `JSON.stringify()`
* debug: add custom "formatters"
* debug: use "ms" module for humanizing the diff
* Readme: add "bash" syntax highlighting
* browser: add Firebug color support
* browser: add colors for WebKit browsers
* node: apply log to `console`
* rewrite: abstract common logic for Node & browsers
* add .jshintrc file
0.8.1 / 2014-04-14
==================
* package: re-add the "component" section
0.8.0 / 2014-03-30
==================
* add `enable()` method for nodejs. Closes #27
* change from stderr to stdout
* remove unnecessary index.js file
0.7.4 / 2013-11-13
==================
* remove "browserify" key from package.json (fixes something in browserify)
0.7.3 / 2013-10-30
==================
* fix: catch localStorage security error when cookies are blocked (Chrome)
* add debug(err) support. Closes #46
* add .browser prop to package.json. Closes #42
0.7.2 / 2013-02-06
==================
* fix package.json
* fix: Mobile Safari (private mode) is broken with debug
* fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript
0.7.1 / 2013-02-05
==================
* add repository URL to package.json
* add DEBUG_COLORED to force colored output
* add browserify support
* fix component. Closes #24
0.7.0 / 2012-05-04
==================
* Added .component to package.json
* Added debug.component.js build
0.6.0 / 2012-03-16
==================
* Added support for "-" prefix in DEBUG [Vinay Pulim]
* Added `.enabled` flag to the node version [TooTallNate]
0.5.0 / 2012-02-02
==================
* Added: humanize diffs. Closes #8
* Added `debug.disable()` to the CS variant
* Removed padding. Closes #10
* Fixed: persist client-side variant again. Closes #9
0.4.0 / 2012-02-01
==================
* Added browser variant support for older browsers [TooTallNate]
* Added `debug.enable('project:*')` to browser variant [TooTallNate]
* Added padding to diff (moved it to the right)
0.3.0 / 2012-01-26
==================
* Added millisecond diff when isatty, otherwise UTC string
0.2.0 / 2012-01-22
==================
* Added wildcard support
0.1.0 / 2011-12-02
==================
* Added: remove colors unless stderr isatty [TooTallNate]
0.0.1 / 2010-01-03
==================
* Initial release

View File

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

View File

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

View File

@ -0,0 +1 @@
module.exports = require('./src/node');

View File

@ -0,0 +1,51 @@
{
"name": "debug",
"version": "3.2.7",
"repository": {
"type": "git",
"url": "git://github.com/visionmedia/debug.git"
},
"description": "small debugging utility",
"keywords": [
"debug",
"log",
"debugger"
],
"files": [
"src",
"node.js",
"dist/debug.js",
"LICENSE",
"README.md"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"contributors": [
"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)",
"Andrew Rhyne <rhyneandrew@gmail.com>"
],
"license": "MIT",
"dependencies": {
"ms": "^2.1.1"
},
"devDependencies": {
"@babel/cli": "^7.0.0",
"@babel/core": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"browserify": "14.4.0",
"chai": "^3.5.0",
"concurrently": "^3.1.0",
"coveralls": "^3.0.2",
"istanbul": "^0.4.5",
"karma": "^3.0.0",
"karma-chai": "^0.1.0",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"mocha": "^5.2.0",
"mocha-lcov-reporter": "^1.2.0",
"rimraf": "^2.5.4",
"xo": "^0.23.0"
},
"main": "./src/index.js",
"browser": "./src/browser.js",
"unpkg": "./dist/debug.js"
}

View File

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

View File

@ -0,0 +1,249 @@
"use strict";
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
Object.keys(env).forEach(function (key) {
createDebug[key] = env[key];
});
/**
* Active `debug` instances.
*/
createDebug.instances = [];
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
var hash = 0;
for (var i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
var prevTime;
function debug() {
// Disabled?
if (!debug.enabled) {
return;
}
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var self = debug; // Set `diff` timestamp
var curr = Number(new Date());
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
} // Apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return match;
}
index++;
var formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
var val = args[index];
match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
}); // Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
var logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = createDebug.enabled(namespace);
debug.useColors = createDebug.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
debug.extend = extend; // Debug.formatArgs = formatArgs;
// debug.rawLog = rawLog;
// env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
createDebug.instances.push(debug);
return debug;
}
function destroy() {
var index = createDebug.instances.indexOf(this);
if (index !== -1) {
createDebug.instances.splice(index, 1);
return true;
}
return false;
}
function extend(namespace, delimiter) {
return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.names = [];
createDebug.skips = [];
var i;
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
for (i = 0; i < createDebug.instances.length; i++) {
var instance = createDebug.instances[i];
instance.enabled = createDebug.enabled(instance.namespace);
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
createDebug.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
var i;
var len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;

View File

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

View File

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

View File

@ -0,0 +1,63 @@
{
"name": "@cypress/xvfb",
"version": "1.2.4",
"private": false,
"author": "Rob Wu <rob@robwu.nl> (https://robwu.nl)",
"contributors": [
"ProxV, Inc. <support@proxv.com> (http://proxv.com)"
],
"description": "Easily start and stop an X Virtual Frame Buffer from your node apps.",
"publishConfig": {
"registry": "http://registry.npmjs.org/",
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/cypress-io/xvfb.git"
},
"dependencies": {
"debug": "^3.1.0",
"lodash.once": "^4.1.1"
},
"main": "index.js",
"files": [
"index.js"
],
"license": "MIT",
"scripts": {
"test": "eslint **/*.js && mocha",
"test-watch": "mocha watch",
"semantic-release": "semantic-release",
"commit": "commit-wizard",
"demo": "node ./demo",
"size": "t=\"$(npm pack .)\"; wc -c \"${t}\"; tar tvf \"${t}\"; rm \"${t}\";"
},
"devDependencies": {
"bluebird": "^3.5.1",
"chai": "^4.1.2",
"eslint": "^4.13.1",
"eslint-plugin-cypress-dev": "^1.1.2",
"eslint-plugin-mocha": "^4.11.0",
"husky": "1.0.1",
"mocha": "^3.5.0",
"npm-utils": "^2.0.0",
"semantic-release": "15.9.16"
},
"release": {
"analyzeCommits": {
"preset": "angular",
"releaseRules": [
{
"type": "break",
"release": "major"
}
]
}
},
"husky": {
"hooks": {
"pre-commit": "npm test",
"pre-push": "npm run size"
}
}
}

21
CY_Auta_TS/automaty/node_modules/@types/node/LICENSE generated vendored Normal file
View File

@ -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

16
CY_Auta_TS/automaty/node_modules/@types/node/README.md generated vendored Normal file
View File

@ -0,0 +1,16 @@
# Installation
> `npm install --save @types/node`
# Summary
This package contains type definitions for Node.js (https://nodejs.org/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node/v16.
### Additional Details
* Last updated: Fri, 21 Jul 2023 22:02:47 GMT
* Dependencies: none
* Global values: `AbortController`, `AbortSignal`, `__dirname`, `__filename`, `console`, `exports`, `gc`, `global`, `module`, `process`, `require`
# Credits
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Seth Westphal](https://github.com/westy92), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [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), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), and [wafuwafu13](https://github.com/wafuwafu13).

View File

@ -0,0 +1,962 @@
/**
* The `assert` module provides a set of assertion functions for verifying
* invariants.
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/assert.js)
*/
declare module 'assert' {
/**
* An alias of {@link ok}.
* @since v0.5.9
* @param value The input that is checked for being truthy.
*/
function assert(value: unknown, message?: string | Error): asserts value;
namespace assert {
/**
* Indicates the failure of an assertion. All errors thrown by the `assert` module
* will be instances of the `AssertionError` class.
*/
class AssertionError extends Error {
actual: unknown;
expected: unknown;
operator: string;
generatedMessage: boolean;
code: 'ERR_ASSERTION';
constructor(options?: {
/** If provided, the error message is set to this value. */
message?: string | undefined;
/** The `actual` property on the error instance. */
actual?: unknown | undefined;
/** The `expected` property on the error instance. */
expected?: unknown | undefined;
/** The `operator` property on the error instance. */
operator?: string | undefined;
/** If provided, the generated stack trace omits frames before this function. */
// tslint:disable-next-line:ban-types
stackStartFn?: Function | undefined;
});
}
/**
* This feature is currently experimental and behavior might still change.
* @since v14.2.0, v12.19.0
* @experimental
*/
class CallTracker {
/**
* The wrapper function is expected to be called exactly `exact` times. If the
* function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an
* error.
*
* ```js
* import assert from 'assert';
*
* // Creates call tracker.
* const tracker = new assert.CallTracker();
*
* function func() {}
*
* // Returns a function that wraps func() that must be called exact times
* // before tracker.verify().
* const callsfunc = tracker.calls(func);
* ```
* @since v14.2.0, v12.19.0
* @param [fn='A no-op function']
* @param [exact=1]
* @return that wraps `fn`.
*/
calls(exact?: number): () => void;
calls<Func extends (...args: any[]) => any>(fn?: Func, exact?: number): Func;
/**
* Example:
*
* ```js
* import assert from 'node:assert';
*
* const tracker = new assert.CallTracker();
*
* function func() {}
* const callsfunc = tracker.calls(func);
* callsfunc(1, 2, 3);
*
* assert.deepStrictEqual(tracker.getCalls(callsfunc),
* [{ thisArg: this, arguments: [1, 2, 3 ] }]);
* ```
*
* @since v18.8.0, v16.18.0
* @param fn
* @returns An Array with the calls to a tracked function.
*/
getCalls(fn: Function): CallTrackerCall[];
/**
* The arrays contains information about the expected and actual number of calls of
* the functions that have not been called the expected number of times.
*
* ```js
* import assert from 'assert';
*
* // Creates call tracker.
* const tracker = new assert.CallTracker();
*
* function func() {}
*
* function foo() {}
*
* // Returns a function that wraps func() that must be called exact times
* // before tracker.verify().
* const callsfunc = tracker.calls(func, 2);
*
* // Returns an array containing information on callsfunc()
* tracker.report();
* // [
* // {
* // message: 'Expected the func function to be executed 2 time(s) but was
* // executed 0 time(s).',
* // actual: 0,
* // expected: 2,
* // operator: 'func',
* // stack: stack trace
* // }
* // ]
* ```
* @since v14.2.0, v12.19.0
* @return of objects containing information about the wrapper functions returned by `calls`.
*/
report(): CallTrackerReportInformation[];
/**
* Reset calls of the call tracker.
* If a tracked function is passed as an argument, the calls will be reset for it.
* If no arguments are passed, all tracked functions will be reset.
*
* ```js
* import assert from 'node:assert';
*
* const tracker = new assert.CallTracker();
*
* function func() {}
* const callsfunc = tracker.calls(func);
*
* callsfunc();
* // Tracker was called once
* tracker.getCalls(callsfunc).length === 1;
*
* tracker.reset(callsfunc);
* tracker.getCalls(callsfunc).length === 0;
* ```
*
* @since v18.8.0, v16.18.0
* @param fn a tracked function to reset.
*/
reset(fn?: Function): void;
/**
* Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that
* have not been called the expected number of times.
*
* ```js
* import assert from 'assert';
*
* // Creates call tracker.
* const tracker = new assert.CallTracker();
*
* function func() {}
*
* // Returns a function that wraps func() that must be called exact times
* // before tracker.verify().
* const callsfunc = tracker.calls(func, 2);
*
* callsfunc();
*
* // Will throw an error since callsfunc() was only called once.
* tracker.verify();
* ```
* @since v14.2.0, v12.19.0
*/
verify(): void;
}
interface CallTrackerCall {
thisArg: object;
arguments: unknown[];
}
interface CallTrackerReportInformation {
message: string;
/** The actual number of times the function was called. */
actual: number;
/** The number of times the function was expected to be called. */
expected: number;
/** The name of the function that is wrapped. */
operator: string;
/** A stack trace of the function. */
stack: object;
}
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 'assert/strict';
*
* assert.fail();
* // AssertionError [ERR_ASSERTION]: Failed
*
* assert.fail('boom');
* // AssertionError [ERR_ASSERTION]: boom
*
* assert.fail(new TypeError('need array'));
* // TypeError: need array
* ```
*
* Using `assert.fail()` with more than two arguments is possible but deprecated.
* See below for further details.
* @since v0.1.21
* @param [message='Failed']
*/
function fail(message?: string | Error): never;
/** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */
function fail(
actual: unknown,
expected: unknown,
message?: string | Error,
operator?: string,
// tslint:disable-next-line:ban-types
stackStartFn?: Function
): 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 '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 'assert/strict';
*
* // Using `assert()` works the same:
* assert(0);
* // AssertionError: The expression evaluated to a falsy value:
* //
* // assert(0)
* ```
* @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 [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison) ( `==` ). `NaN` is special handled
* and treated as being identical in case both sides are `NaN`.
*
* ```js
* import assert from '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 [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison)(`!=` ). `NaN` is special handled and treated as
* being identical in case both
* sides are `NaN`.
*
* ```js
* import assert from '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 'assert';
*
* const obj1 = {
* a: {
* b: 1
* }
* };
* const obj2 = {
* a: {
* b: 2
* }
* };
* const obj3 = {
* a: {
* b: 1
* }
* };
* const obj4 = Object.create(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 the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue).
*
* ```js
* import assert from '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<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T;
/**
* Tests strict inequality between the `actual` and `expected` parameters as
* determined by the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue).
*
* ```js
* import assert from '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<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T;
/**
* Tests for deep strict inequality. Opposite of {@link deepStrictEqual}.
*
* ```js
* import assert from '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 '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:
* 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:
* 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 '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 '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 '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 '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 '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 '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 '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 '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` 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 `AssertionError` if the `asyncFn` fails to reject.
*
* ```js
* import assert from 'assert/strict';
*
* await assert.rejects(
* async () => {
* throw new TypeError('Wrong value');
* },
* {
* name: 'TypeError',
* message: 'Wrong value'
* }
* );
* ```
*
* ```js
* import assert from '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 '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<unknown>) | Promise<unknown>, message?: string | Error): Promise<void>;
function rejects(block: (() => Promise<unknown>) | Promise<unknown>, error: AssertPredicate, message?: string | Error): Promise<void>;
/**
* 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` 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 'assert/strict';
*
* await assert.doesNotReject(
* async () => {
* throw new TypeError('Wrong value');
* },
* SyntaxError
* );
* ```
*
* ```js
* import assert from 'assert/strict';
*
* assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
* .then(() => {
* // ...
* });
* ```
* @since v10.0.0
*/
function doesNotReject(block: (() => Promise<unknown>) | Promise<unknown>, message?: string | Error): Promise<void>;
function doesNotReject(block: (() => Promise<unknown>) | Promise<unknown>, error: AssertPredicate, message?: string | Error): Promise<void>;
/**
* Expects the `string` input to match the regular expression.
*
* ```js
* import assert from '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 `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 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 '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 `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 v13.6.0, v12.16.0
*/
function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void;
const strict: Omit<typeof assert, 'equal' | 'notEqual' | 'deepEqual' | 'notDeepEqual' | 'ok' | 'strictEqual' | 'deepStrictEqual' | 'ifError' | 'strict'> & {
(value: unknown, message?: string | Error): asserts value;
equal: typeof strictEqual;
notEqual: typeof notStrictEqual;
deepEqual: typeof deepStrictEqual;
notDeepEqual: typeof notDeepStrictEqual;
// Mapped types and assertion functions are incompatible?
// TS2775: Assertions require every name in the call target
// to be declared with an explicit type annotation.
ok: typeof ok;
strictEqual: typeof strictEqual;
deepStrictEqual: typeof deepStrictEqual;
ifError: typeof ifError;
strict: typeof strict;
};
}
export = assert;
}
declare module 'node:assert' {
import assert = require('assert');
export = assert;
}

View File

@ -0,0 +1,497 @@
/**
* The `async_hooks` module provides an API to track asynchronous resources. It
* can be accessed using:
*
* ```js
* import async_hooks from 'async_hooks';
* ```
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/async_hooks.js)
*/
declare module 'async_hooks' {
/**
* ```js
* import { executionAsyncId } from 'async_hooks';
*
* console.log(executionAsyncId()); // 1 - bootstrap
* 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`.
* @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 'fs';
* import { executionAsyncId, executionAsyncResource } from '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 'http';
* import {
* executionAsyncId,
* executionAsyncResource,
* createHook
* } from '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`.
* @return The ID of the resource responsible for calling the callback that is currently being executed.
*/
function triggerAsyncId(): number;
interface HookCallbacks {
/**
* Called when a class is constructed that has the possibility to emit an asynchronous event.
* @param asyncId a unique ID for the async resource
* @param type the type of the async resource
* @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created
* @param resource reference to the resource representing the async operation, needs to be released during destroy
*/
init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void;
/**
* When an asynchronous operation is initiated or completes a callback is called to notify the user.
* The before callback is called just before said callback is executed.
* @param asyncId the unique identifier assigned to the resource about to execute the callback.
*/
before?(asyncId: number): void;
/**
* Called immediately after the callback specified in before is completed.
* @param asyncId the unique identifier assigned to the resource which has executed the callback.
*/
after?(asyncId: number): void;
/**
* Called when a promise has resolve() called. This may not be in the same execution id
* as the promise itself.
* @param asyncId the unique id for the promise that was resolve()d.
*/
promiseResolve?(asyncId: number): void;
/**
* Called after the resource corresponding to asyncId is destroyed
* @param asyncId a unique ID for the async resource
*/
destroy?(asyncId: number): void;
}
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` section.
*
* ```js
* import { createHook } from '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 callbacks The `Hook Callbacks` to register
* @return Instance used for disabling and enabling hooks
*/
function createHook(callbacks: 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 '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.
*
* The returned function will have an `asyncResource` property referencing
* the `AsyncResource` to which the function is bound.
* @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<Func extends (this: ThisArg, ...args: any[]) => any, ThisArg>(
fn: Func,
type?: string,
thisArg?: ThisArg
): Func & {
asyncResource: AsyncResource;
};
/**
* Binds the given function to execute to this `AsyncResource`'s scope.
*
* The returned function will have an `asyncResource` property referencing
* the `AsyncResource` to which the function is bound.
* @since v14.8.0, v12.19.0
* @param fn The function to bind to the current `AsyncResource`.
*/
bind<Func extends (...args: any[]) => any>(
fn: Func
): Func & {
asyncResource: AsyncResource;
};
/**
* 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<This, Result>(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;
}
/**
* This class creates stores that stay coherent through asynchronous operations.
*
* While you can create your own implementation on top of the `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 'http';
* import { AsyncLocalStorage } from '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
* // 1: start
* // 0: finish
* // 1: finish
* ```
*
* Each instance of `AsyncLocalStorage` maintains an independent storage context.
* Multiple instances can safely exist simultaneously without risk of interfering
* with each other data.
* @since v13.10.0, v12.17.0
*/
class AsyncLocalStorage<T> {
/**
* 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;
/**
* Runs a function synchronously within a context and returns its
* return value. The store is not accessible outside of the callback function or
* the 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
* throw new Error();
* });
* } catch (e) {
* asyncLocalStorage.getStore(); // Returns undefined
* // The error will be caught here
* }
* ```
* @since v13.10.0, v12.17.0
*/
run<R, TArgs extends any[]>(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<R, TArgs extends any[]>(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;
}
}
declare module 'node:async_hooks' {
export * from 'async_hooks';
}

2236
CY_Auta_TS/automaty/node_modules/@types/node/buffer.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,418 @@
/**
* A single instance of Node.js runs in a single thread. To take advantage of
* multi-core systems, the user will sometimes want to launch a cluster of Node.js
* processes to handle the load.
*
* The cluster module allows easy creation of child processes that all share
* server ports.
*
* ```js
* import cluster from 'cluster';
* import http from 'http';
* import { cpus } from 'os';
* import process from 'process';
*
* const numCPUs = cpus().length;
*
* if (cluster.isPrimary) {
* console.log(`Primary ${process.pid} is running`);
*
* // Fork workers.
* for (let i = 0; i < numCPUs; i++) {
* cluster.fork();
* }
*
* cluster.on('exit', (worker, code, signal) => {
* console.log(`worker ${worker.process.pid} died`);
* });
* } else {
* // Workers can share any TCP connection
* // In this case it is an HTTP server
* http.createServer((req, res) => {
* res.writeHead(200);
* res.end('hello world\n');
* }).listen(8000);
*
* console.log(`Worker ${process.pid} started`);
* }
* ```
*
* Running Node.js will now share port 8000 between the workers:
*
* ```console
* $ node server.js
* Primary 3596 is running
* Worker 4324 started
* Worker 4520 started
* Worker 6056 started
* Worker 5644 started
* ```
*
* On Windows, it is not yet possible to set up a named pipe server in a worker.
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/cluster.js)
*/
declare module 'cluster' {
import * as child from 'node:child_process';
import EventEmitter = require('node:events');
import * as net from 'node:net';
type SerializationType = 'json' | 'advanced';
export interface ClusterSettings {
execArgv?: string[] | undefined; // default: process.execArgv
exec?: string | undefined;
args?: string[] | undefined;
silent?: boolean | undefined;
stdio?: any[] | undefined;
uid?: number | undefined;
gid?: number | undefined;
inspectPort?: number | (() => number) | undefined;
serialization?: SerializationType | undefined;
cwd?: string | undefined;
windowsHide?: boolean | undefined;
}
export interface Address {
address: string;
port: number;
addressType: number | 'udp4' | 'udp6'; // 4, 6, -1, "udp4", "udp6"
}
/**
* 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
*/
export class Worker extends EventEmitter {
/**
* 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()`, the returned object
* from this function is stored as `.process`. In a worker, the global `process`is stored.
*
* See: `Child Process module`.
*
* 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.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()`.
*
* 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. `options` supports the following properties:
*/
send(message: child.Serializable, callback?: (error: Error | null) => void): boolean;
send(message: child.Serializable, sendHandle: child.SendHandle, callback?: (error: Error | null) => void): boolean;
send(message: child.Serializable, sendHandle: child.SendHandle, options?: child.MessageOptions, callback?: (error: Error | null) => void): boolean;
/**
* This function will kill the worker. In the primary, it does this
* by disconnecting the `worker.process`, and once disconnected, killing
* with `signal`. In the worker, it does it by disconnecting the channel,
* and then exiting with code `0`.
*
* Because `kill()` attempts to gracefully disconnect the worker process, it is
* susceptible to waiting indefinitely for the disconnect to complete. For example,
* if the worker enters an infinite loop, a graceful disconnect will never occur.
* If the graceful disconnect behavior is not needed, use `worker.process.kill()`.
*
* Causes `.exitedAfterDisconnect` to be set.
*
* This method is aliased as `worker.destroy()` for backward compatibility.
*
* In a worker, `process.kill()` exists, but it is not this function;
* it is `kill()`.
* @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
* 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 net = require('net');
* 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(): void;
/**
* 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 'cluster';
* import http from 'http';
* import { cpus } from 'os';
* import process from 'process';
*
* const numCPUs = cpus().length;
*
* 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 `.kill()` or`.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;
/**
* events.EventEmitter
* 1. disconnect
* 2. error
* 3. exit
* 4. listening
* 5. message
* 6. online
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'disconnect', listener: () => void): this;
addListener(event: 'error', listener: (error: Error) => void): this;
addListener(event: 'exit', listener: (code: number, signal: string) => void): this;
addListener(event: 'listening', listener: (address: Address) => void): this;
addListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
addListener(event: 'online', listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: 'disconnect'): boolean;
emit(event: 'error', error: Error): boolean;
emit(event: 'exit', code: number, signal: string): boolean;
emit(event: 'listening', address: Address): boolean;
emit(event: 'message', message: any, handle: net.Socket | net.Server): boolean;
emit(event: 'online'): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'disconnect', listener: () => void): this;
on(event: 'error', listener: (error: Error) => void): this;
on(event: 'exit', listener: (code: number, signal: string) => void): this;
on(event: 'listening', listener: (address: Address) => void): this;
on(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
on(event: 'online', listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'disconnect', listener: () => void): this;
once(event: 'error', listener: (error: Error) => void): this;
once(event: 'exit', listener: (code: number, signal: string) => void): this;
once(event: 'listening', listener: (address: Address) => void): this;
once(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
once(event: 'online', listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'disconnect', listener: () => void): this;
prependListener(event: 'error', listener: (error: Error) => void): this;
prependListener(event: 'exit', listener: (code: number, signal: string) => void): this;
prependListener(event: 'listening', listener: (address: Address) => void): this;
prependListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependListener(event: 'online', listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'disconnect', listener: () => void): this;
prependOnceListener(event: 'error', listener: (error: Error) => void): this;
prependOnceListener(event: 'exit', listener: (code: number, signal: string) => void): this;
prependOnceListener(event: 'listening', listener: (address: Address) => void): this;
prependOnceListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependOnceListener(event: 'online', listener: () => void): this;
}
export interface Cluster extends EventEmitter {
disconnect(callback?: () => void): void;
fork(env?: any): Worker;
/** @deprecated since v16.0.0 - use isPrimary. */
readonly isMaster: boolean;
readonly isPrimary: boolean;
readonly isWorker: boolean;
schedulingPolicy: number;
readonly settings: ClusterSettings;
/** @deprecated since v16.0.0 - use setupPrimary. */
setupMaster(settings?: ClusterSettings): void;
/**
* `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings.
*/
setupPrimary(settings?: ClusterSettings): void;
readonly worker?: Worker | undefined;
readonly workers?: NodeJS.Dict<Worker> | undefined;
readonly SCHED_NONE: number;
readonly SCHED_RR: number;
/**
* events.EventEmitter
* 1. disconnect
* 2. exit
* 3. fork
* 4. listening
* 5. message
* 6. online
* 7. setup
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'disconnect', listener: (worker: Worker) => void): this;
addListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
addListener(event: 'fork', listener: (worker: Worker) => void): this;
addListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
addListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
addListener(event: 'online', listener: (worker: Worker) => void): this;
addListener(event: 'setup', listener: (settings: ClusterSettings) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: 'disconnect', worker: Worker): boolean;
emit(event: 'exit', worker: Worker, code: number, signal: string): boolean;
emit(event: 'fork', worker: Worker): boolean;
emit(event: 'listening', worker: Worker, address: Address): boolean;
emit(event: 'message', worker: Worker, message: any, handle: net.Socket | net.Server): boolean;
emit(event: 'online', worker: Worker): boolean;
emit(event: 'setup', settings: ClusterSettings): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'disconnect', listener: (worker: Worker) => void): this;
on(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
on(event: 'fork', listener: (worker: Worker) => void): this;
on(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
on(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
on(event: 'online', listener: (worker: Worker) => void): this;
on(event: 'setup', listener: (settings: ClusterSettings) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'disconnect', listener: (worker: Worker) => void): this;
once(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
once(event: 'fork', listener: (worker: Worker) => void): this;
once(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
once(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
once(event: 'online', listener: (worker: Worker) => void): this;
once(event: 'setup', listener: (settings: ClusterSettings) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'disconnect', listener: (worker: Worker) => void): this;
prependListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
prependListener(event: 'fork', listener: (worker: Worker) => void): this;
prependListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
// the handle is a net.Socket or net.Server object, or undefined.
prependListener(event: 'message', listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void): this;
prependListener(event: 'online', listener: (worker: Worker) => void): this;
prependListener(event: 'setup', listener: (settings: ClusterSettings) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'disconnect', listener: (worker: Worker) => void): this;
prependOnceListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
prependOnceListener(event: 'fork', listener: (worker: Worker) => void): this;
prependOnceListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
// the handle is a net.Socket or net.Server object, or undefined.
prependOnceListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this;
prependOnceListener(event: 'online', listener: (worker: Worker) => void): this;
prependOnceListener(event: 'setup', listener: (settings: ClusterSettings) => void): this;
}
const cluster: Cluster;
export default cluster;
}
declare module 'node:cluster' {
export * from 'cluster';
export { default as default } from 'cluster';
}

View File

@ -0,0 +1,412 @@
/**
* The `console` module provides a simple debugging console that is similar to the
* JavaScript console mechanism provided by web browsers.
*
* The module exports two specific components:
*
* * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream.
* * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`.
*
* _**Warning**_: The global console object's methods are neither consistently
* synchronous like the browser APIs they resemble, nor are they consistently
* asynchronous like all other Node.js streams. See the `note on process I/O` for
* more information.
*
* Example using the global `console`:
*
* ```js
* console.log('hello world');
* // Prints: hello world, to stdout
* console.log('hello %s', 'world');
* // Prints: hello world, to stdout
* console.error(new Error('Whoops, something bad happened'));
* // Prints error message and stack trace to stderr:
* // Error: Whoops, something bad happened
* // at [eval]:5:15
* // at Script.runInThisContext (node:vm:132:18)
* // at Object.runInThisContext (node:vm:309:38)
* // at node:internal/process/execution:77:19
* // at [eval]-wrapper:6:22
* // at evalScript (node:internal/process/execution:76:60)
* // at node:internal/main/eval_string:23:3
*
* const name = 'Will Robinson';
* console.warn(`Danger ${name}! Danger!`);
* // Prints: Danger Will Robinson! Danger!, to stderr
* ```
*
* Example using the `Console` class:
*
* ```js
* const out = getStreamSomehow();
* const err = getStreamSomehow();
* const myConsole = new console.Console(out, err);
*
* myConsole.log('hello world');
* // Prints: hello world, to out
* myConsole.log('hello %s', 'world');
* // Prints: hello world, to out
* myConsole.error(new Error('Whoops, something bad happened'));
* // Prints: [Error: Whoops, something bad happened], to err
*
* const name = 'Will Robinson';
* myConsole.warn(`Danger ${name}! Danger!`);
* // Prints: Danger Will Robinson! Danger!, to err
* ```
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/console.js)
*/
declare module 'console' {
import console = require('node:console');
export = console;
}
declare module 'node:console' {
import { InspectOptions } from 'node:util';
global {
// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build
interface Console {
Console: console.ConsoleConstructor;
/**
* `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only
* writes a message and does not otherwise affect execution. The output always
* starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`.
*
* If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens.
*
* ```js
* console.assert(true, 'does nothing');
*
* console.assert(false, 'Whoops %s work', 'didn\'t');
* // Assertion failed: Whoops didn't work
*
* console.assert();
* // Assertion failed
* ```
* @since v0.1.101
* @param value The value tested for being truthy.
* @param message All arguments besides `value` are used as error message.
*/
assert(value: any, message?: string, ...optionalParams: any[]): void;
/**
* When `stdout` is a TTY, calling `console.clear()` will attempt to clear the
* TTY. When `stdout` is not a TTY, this method does nothing.
*
* The specific operation of `console.clear()` can vary across operating systems
* and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the
* current terminal viewport for the Node.js
* binary.
* @since v8.3.0
*/
clear(): void;
/**
* Maintains an internal counter specific to `label` and outputs to `stdout` the
* number of times `console.count()` has been called with the given `label`.
*
* ```js
* > console.count()
* default: 1
* undefined
* > console.count('default')
* default: 2
* undefined
* > console.count('abc')
* abc: 1
* undefined
* > console.count('xyz')
* xyz: 1
* undefined
* > console.count('abc')
* abc: 2
* undefined
* > console.count()
* default: 3
* undefined
* >
* ```
* @since v8.3.0
* @param label The display label for the counter.
*/
count(label?: string): void;
/**
* Resets the internal counter specific to `label`.
*
* ```js
* > console.count('abc');
* abc: 1
* undefined
* > console.countReset('abc');
* undefined
* > console.count('abc');
* abc: 1
* undefined
* >
* ```
* @since v8.3.0
* @param label The display label for the counter.
*/
countReset(label?: string): void;
/**
* The `console.debug()` function is an alias for {@link log}.
* @since v8.0.0
*/
debug(message?: any, ...optionalParams: any[]): void;
/**
* Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`.
* This function bypasses any custom `inspect()` function defined on `obj`.
* @since v0.1.101
*/
dir(obj: any, options?: InspectOptions): void;
/**
* This method calls `console.log()` passing it the arguments received.
* This method does not produce any XML formatting.
* @since v8.0.0
*/
dirxml(...data: any[]): void;
/**
* Prints to `stderr` with newline. Multiple arguments can be passed, with the
* first used as the primary message and all additional used as substitution
* values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`).
*
* ```js
* const code = 5;
* console.error('error #%d', code);
* // Prints: error #5, to stderr
* console.error('error', code);
* // Prints: error 5, to stderr
* ```
*
* If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string
* values are concatenated. See `util.format()` for more information.
* @since v0.1.100
*/
error(message?: any, ...optionalParams: any[]): void;
/**
* Increases indentation of subsequent lines by spaces for `groupIndentation`length.
*
* If one or more `label`s are provided, those are printed first without the
* additional indentation.
* @since v8.5.0
*/
group(...label: any[]): void;
/**
* An alias for {@link group}.
* @since v8.5.0
*/
groupCollapsed(...label: any[]): void;
/**
* Decreases indentation of subsequent lines by spaces for `groupIndentation`length.
* @since v8.5.0
*/
groupEnd(): void;
/**
* The `console.info()` function is an alias for {@link log}.
* @since v0.1.100
*/
info(message?: any, ...optionalParams: any[]): void;
/**
* Prints to `stdout` with newline. Multiple arguments can be passed, with the
* first used as the primary message and all additional used as substitution
* values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`).
*
* ```js
* const count = 5;
* console.log('count: %d', count);
* // Prints: count: 5, to stdout
* console.log('count:', count);
* // Prints: count: 5, to stdout
* ```
*
* See `util.format()` for more information.
* @since v0.1.100
*/
log(message?: any, ...optionalParams: any[]): void;
/**
* Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just
* logging the argument if it cant be parsed as tabular.
*
* ```js
* // These can't be parsed as tabular data
* console.table(Symbol());
* // Symbol()
*
* console.table(undefined);
* // undefined
*
* console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
* // ┌─────────┬─────┬─────┐
* // │ (index) │ a │ b │
* // ├─────────┼─────┼─────┤
* // │ 0 │ 1 │ 'Y' │
* // │ 1 │ 'Z' │ 2 │
* // └─────────┴─────┴─────┘
*
* console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
* // ┌─────────┬─────┐
* // │ (index) │ a │
* // ├─────────┼─────┤
* // │ 0 │ 1 │
* // │ 1 │ 'Z' │
* // └─────────┴─────┘
* ```
* @since v10.0.0
* @param properties Alternate properties for constructing the table.
*/
table(tabularData: any, properties?: ReadonlyArray<string>): void;
/**
* Starts a timer that can be used to compute the duration of an operation. Timers
* are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in
* suitable time units to `stdout`. For example, if the elapsed
* time is 3869ms, `console.timeEnd()` displays "3.869s".
* @since v0.1.104
*/
time(label?: string): void;
/**
* Stops a timer that was previously started by calling {@link time} and
* prints the result to `stdout`:
*
* ```js
* console.time('100-elements');
* for (let i = 0; i < 100; i++) {}
* console.timeEnd('100-elements');
* // prints 100-elements: 225.438ms
* ```
* @since v0.1.104
*/
timeEnd(label?: string): void;
/**
* For a timer that was previously started by calling {@link time}, prints
* the elapsed time and other `data` arguments to `stdout`:
*
* ```js
* console.time('process');
* const value = expensiveProcess1(); // Returns 42
* console.timeLog('process', value);
* // Prints "process: 365.227ms 42".
* doExpensiveProcess2(value);
* console.timeEnd('process');
* ```
* @since v10.7.0
*/
timeLog(label?: string, ...data: any[]): void;
/**
* Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code.
*
* ```js
* console.trace('Show me');
* // Prints: (stack trace will vary based on where trace is called)
* // Trace: Show me
* // at repl:2:9
* // at REPLServer.defaultEval (repl.js:248:27)
* // at bound (domain.js:287:14)
* // at REPLServer.runBound [as eval] (domain.js:300:12)
* // at REPLServer.<anonymous> (repl.js:412:12)
* // at emitOne (events.js:82:20)
* // at REPLServer.emit (events.js:169:7)
* // at REPLServer.Interface._onLine (readline.js:210:10)
* // at REPLServer.Interface._line (readline.js:549:8)
* // at REPLServer.Interface._ttyWrite (readline.js:826:14)
* ```
* @since v0.1.104
*/
trace(message?: any, ...optionalParams: any[]): void;
/**
* The `console.warn()` function is an alias for {@link error}.
* @since v0.1.100
*/
warn(message?: any, ...optionalParams: any[]): void;
// --- Inspector mode only ---
/**
* This method does not display anything unless used in the inspector.
* Starts a JavaScript CPU profile with an optional label.
*/
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.
*/
profileEnd(label?: string): void;
/**
* This method does not display anything unless used in the inspector.
* Adds an event with the label `label` to the Timeline panel of the inspector.
*/
timeStamp(label?: string): void;
}
/**
* The `console` module provides a simple debugging console that is similar to the
* JavaScript console mechanism provided by web browsers.
*
* The module exports two specific components:
*
* * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream.
* * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`.
*
* _**Warning**_: The global console object's methods are neither consistently
* synchronous like the browser APIs they resemble, nor are they consistently
* asynchronous like all other Node.js streams. See the `note on process I/O` for
* more information.
*
* Example using the global `console`:
*
* ```js
* console.log('hello world');
* // Prints: hello world, to stdout
* console.log('hello %s', 'world');
* // Prints: hello world, to stdout
* console.error(new Error('Whoops, something bad happened'));
* // Prints error message and stack trace to stderr:
* // Error: Whoops, something bad happened
* // at [eval]:5:15
* // at Script.runInThisContext (node:vm:132:18)
* // at Object.runInThisContext (node:vm:309:38)
* // at node:internal/process/execution:77:19
* // at [eval]-wrapper:6:22
* // at evalScript (node:internal/process/execution:76:60)
* // at node:internal/main/eval_string:23:3
*
* const name = 'Will Robinson';
* console.warn(`Danger ${name}! Danger!`);
* // Prints: Danger Will Robinson! Danger!, to stderr
* ```
*
* Example using the `Console` class:
*
* ```js
* const out = getStreamSomehow();
* const err = getStreamSomehow();
* const myConsole = new console.Console(out, err);
*
* myConsole.log('hello world');
* // Prints: hello world, to out
* myConsole.log('hello %s', 'world');
* // Prints: hello world, to out
* myConsole.error(new Error('Whoops, something bad happened'));
* // Prints: [Error: Whoops, something bad happened], to err
*
* const name = 'Will Robinson';
* myConsole.warn(`Danger ${name}! Danger!`);
* // Prints: Danger Will Robinson! Danger!, to err
* ```
* @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js)
*/
namespace console {
interface ConsoleConstructorOptions {
stdout: NodeJS.WritableStream;
stderr?: NodeJS.WritableStream | undefined;
ignoreErrors?: boolean | undefined;
colorMode?: boolean | 'auto' | undefined;
inspectOptions?: InspectOptions | undefined;
/**
* Set group indentation
* @default 2
*/
groupIndentation?: number | undefined;
}
interface ConsoleConstructor {
prototype: Console;
new (stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console;
new (options: ConsoleConstructorOptions): Console;
}
}
var console: Console;
}
export = globalThis.console;
}

View File

@ -0,0 +1,18 @@
/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */
declare module 'constants' {
import { constants as osConstants, SignalConstants } from 'node:os';
import { constants as cryptoConstants } from 'node:crypto';
import { constants as fsConstants } from 'node:fs';
const exp: typeof osConstants.errno &
typeof osConstants.priority &
SignalConstants &
typeof cryptoConstants &
typeof fsConstants;
export = exp;
}
declare module 'node:constants' {
import constants = require('constants');
export = constants;
}

3869
CY_Auta_TS/automaty/node_modules/@types/node/crypto.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

545
CY_Auta_TS/automaty/node_modules/@types/node/dgram.d.ts generated vendored Normal file
View File

@ -0,0 +1,545 @@
/**
* The `dgram` module provides an implementation of UDP datagram sockets.
*
* ```js
* import dgram from 'dgram';
*
* const server = dgram.createSocket('udp4');
*
* server.on('error', (err) => {
* console.log(`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
* ```
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/dgram.js)
*/
declare module 'dgram' {
import { AddressInfo } from 'node:net';
import * as dns from 'node:dns';
import { EventEmitter, Abortable } from 'node:events';
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;
/**
* @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;
}
/**
* 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: Buffer, rinfo: RemoteInfo) => void): Socket;
function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
/**
* 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 extends 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 'cluster';
* import dgram from '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 'dgram';
*
* const server = dgram.createSocket('udp4');
*
* server.on('error', (err) => {
* console.log(`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;
/**
* 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 falsy, `'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 'dgram';
* import { Buffer } from '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 'dgram';
* import { Buffer } from '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 'dgram';
* import { Buffer } from '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 | Uint8Array | ReadonlyArray<any>, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array | ReadonlyArray<any>, port?: number, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array | ReadonlyArray<any>, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array, offset: number, length: number, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array, offset: number, length: number, port?: number, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array, 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 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 addition 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;
/**
* events.EventEmitter
* 1. close
* 2. connect
* 3. error
* 4. listening
* 5. message
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'close', listener: () => void): this;
addListener(event: 'connect', listener: () => void): this;
addListener(event: 'error', listener: (err: Error) => void): this;
addListener(event: 'listening', listener: () => void): this;
addListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: 'close'): boolean;
emit(event: 'connect'): boolean;
emit(event: 'error', err: Error): boolean;
emit(event: 'listening'): boolean;
emit(event: 'message', msg: Buffer, rinfo: RemoteInfo): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'close', listener: () => void): this;
on(event: 'connect', listener: () => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'listening', listener: () => void): this;
on(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'close', listener: () => void): this;
once(event: 'connect', listener: () => void): this;
once(event: 'error', listener: (err: Error) => void): this;
once(event: 'listening', listener: () => void): this;
once(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'close', listener: () => void): this;
prependListener(event: 'connect', listener: () => void): this;
prependListener(event: 'error', listener: (err: Error) => void): this;
prependListener(event: 'listening', listener: () => void): this;
prependListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'close', listener: () => void): this;
prependOnceListener(event: 'connect', listener: () => void): this;
prependOnceListener(event: 'error', listener: (err: Error) => void): this;
prependOnceListener(event: 'listening', listener: () => void): this;
prependOnceListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
}
}
declare module 'node:dgram' {
export * from 'dgram';
}

View File

@ -0,0 +1,191 @@
/**
* The `diagnostics_channel` module provides an API to create named channels
* to report arbitrary message data for diagnostics purposes.
*
* It can be accessed using:
*
* ```js
* import diagnostics_channel from 'diagnostics_channel';
* ```
*
* It is intended that a module writer wanting to report diagnostics messages
* will create one or many top-level channels to report messages through.
* Channels may also be acquired at runtime but it is not encouraged
* due to the additional overhead of doing so. Channels may be exported for
* convenience, but as long as the name is known it can be acquired anywhere.
*
* If you intend for your module to produce diagnostics data for others to
* consume it is recommended that you include documentation of what named
* channels are used along with the shape of the message data. Channel names
* should generally include the module name to avoid collisions with data from
* other modules.
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v16.19.1/lib/diagnostics_channel.js)
*/
declare module 'diagnostics_channel' {
/**
* 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 '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 interact with 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 '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 '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 diagnostics_channel.subscribe(name, onMessage).
*
* ```js
* import diagnostics_channel from '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
* @returns `true` if the handler was found, `false` otherwise
*/
function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean;
/**
* The class `Channel` represents an individual named channel within the data
* pipeline. It is use 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 '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 '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 '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 '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
*/
unsubscribe(onMessage: ChannelListener): void;
}
}
declare module 'node:diagnostics_channel' {
export * from 'diagnostics_channel';
}

655
CY_Auta_TS/automaty/node_modules/@types/node/dns.d.ts generated vendored Normal file
View File

@ -0,0 +1,655 @@
/**
* The `dns` module enables name resolution. For example, use it to look up IP
* addresses of host names.
*
* Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the
* DNS protocol for lookups. {@link lookup} uses the operating system
* facilities to perform name resolution. It may not need to perform any network
* communication. To perform name resolution the way other applications on the same
* system do, use {@link lookup}.
*
* ```js
* const dns = require('dns');
*
* dns.lookup('example.org', (err, address, family) => {
* console.log('address: %j family: IPv%s', address, family);
* });
* // address: "93.184.216.34" family: IPv4
* ```
*
* All other functions in the `dns` module connect to an actual DNS server to
* perform name resolution. They will always use the network to perform DNS
* queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform
* DNS queries, bypassing other name-resolution facilities.
*
* ```js
* const dns = require('dns');
*
* dns.resolve4('archive.org', (err, addresses) => {
* if (err) throw err;
*
* console.log(`addresses: ${JSON.stringify(addresses)}`);
*
* addresses.forEach((a) => {
* dns.reverse(a, (err, hostnames) => {
* if (err) {
* throw err;
* }
* console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
* });
* });
* });
* ```
*
* See the `Implementation considerations section` for more information.
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/dns.js)
*/
declare module 'dns' {
import * as dnsPromises from 'node:dns/promises';
// Supported getaddrinfo flags.
export const ADDRCONFIG: number;
export const V4MAPPED: number;
/**
* If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as
* well as IPv4 mapped IPv6 addresses.
*/
export const ALL: number;
export interface LookupOptions {
family?: number | undefined;
hints?: number | undefined;
all?: boolean | undefined;
verbatim?: boolean | undefined;
}
export interface LookupOneOptions extends LookupOptions {
all?: false | undefined;
}
export interface LookupAllOptions extends LookupOptions {
all: true;
}
export interface LookupAddress {
address: string;
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 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` before using`dns.lookup()`.
*
* Example usage:
*
* ```js
* const dns = require('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()` 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
*/
export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;
export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;
export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void;
export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void;
export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;
export namespace lookup {
function __promisify__(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<LookupAddress>;
function __promisify__(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
}
/**
* 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` object, where `err.code` is the error code.
*
* ```js
* const dns = require('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()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties.
* @since v0.11.14
*/
export function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void;
export namespace lookupService {
function __promisify__(
address: string,
port: number
): Promise<{
hostname: string;
service: string;
}>;
}
export interface ResolveOptions {
ttl: boolean;
}
export interface ResolveWithTtlOptions extends ResolveOptions {
ttl: true;
}
export interface RecordWithTtl {
address: string;
ttl: number;
}
/** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */
export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord;
export interface AnyARecord extends RecordWithTtl {
type: 'A';
}
export interface AnyAaaaRecord extends RecordWithTtl {
type: 'AAAA';
}
export interface CaaRecord {
critical: number;
issue?: string | undefined;
issuewild?: string | undefined;
iodef?: string | undefined;
contactemail?: string | undefined;
contactphone?: string | undefined;
}
export interface MxRecord {
priority: number;
exchange: string;
}
export interface AnyMxRecord extends MxRecord {
type: 'MX';
}
export interface NaptrRecord {
flags: string;
service: string;
regexp: string;
replacement: string;
order: number;
preference: number;
}
export interface AnyNaptrRecord extends NaptrRecord {
type: 'NAPTR';
}
export interface SoaRecord {
nsname: string;
hostmaster: string;
serial: number;
refresh: number;
retry: number;
expire: number;
minttl: number;
}
export interface AnySoaRecord extends SoaRecord {
type: 'SOA';
}
export interface SrvRecord {
priority: number;
weight: number;
port: number;
name: string;
}
export interface AnySrvRecord extends SrvRecord {
type: 'SRV';
}
export interface AnyTxtRecord {
type: 'TXT';
entries: string[];
}
export interface AnyNsRecord {
type: 'NS';
value: string;
}
export interface AnyPtrRecord {
type: 'PTR';
value: string;
}
export interface AnyCnameRecord {
type: 'CNAME';
value: string;
}
export type AnyRecord = AnyARecord | AnyAaaaRecord | AnyCnameRecord | AnyMxRecord | AnyNaptrRecord | AnyNsRecord | AnyPtrRecord | AnySoaRecord | AnySrvRecord | 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`:
*
* <omitted>
*
* On error, `err` is an `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.
*/
export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve(hostname: string, rrtype: 'A', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve(hostname: string, rrtype: 'AAAA', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve(hostname: string, rrtype: 'ANY', callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void;
export function resolve(hostname: string, rrtype: 'CNAME', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve(hostname: string, rrtype: 'MX', callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void;
export function resolve(hostname: string, rrtype: 'NAPTR', callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void;
export function resolve(hostname: string, rrtype: 'NS', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve(hostname: string, rrtype: 'PTR', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve(hostname: string, rrtype: 'SOA', callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void;
export function resolve(hostname: string, rrtype: 'SRV', callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void;
export function resolve(hostname: string, rrtype: 'TXT', callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void;
export function resolve(
hostname: string,
rrtype: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void
): void;
export namespace resolve {
function __promisify__(hostname: string, rrtype?: 'A' | 'AAAA' | 'CNAME' | 'NS' | 'PTR'): Promise<string[]>;
function __promisify__(hostname: string, rrtype: 'ANY'): Promise<AnyRecord[]>;
function __promisify__(hostname: string, rrtype: 'MX'): Promise<MxRecord[]>;
function __promisify__(hostname: string, rrtype: 'NAPTR'): Promise<NaptrRecord[]>;
function __promisify__(hostname: string, rrtype: 'SOA'): Promise<SoaRecord>;
function __promisify__(hostname: string, rrtype: 'SRV'): Promise<SrvRecord[]>;
function __promisify__(hostname: string, rrtype: 'TXT'): Promise<string[][]>;
function __promisify__(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | 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.
*/
export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void;
export function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void;
export namespace resolve4 {
function __promisify__(hostname: string): Promise<string[]>;
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
}
/**
* Uses the DNS protocol to resolve a 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.
*/
export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void;
export function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void;
export namespace resolve6 {
function __promisify__(hostname: string): Promise<string[]>;
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
}
/**
* 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
*/
export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export namespace resolveCname {
function __promisify__(hostname: string): Promise<string[]>;
}
/**
* 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
*/
export function resolveCaa(hostname: string, callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void): void;
export namespace resolveCaa {
function __promisify__(hostname: string): Promise<CaaRecord[]>;
}
/**
* 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
*/
export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void;
export namespace resolveMx {
function __promisify__(hostname: string): Promise<MxRecord[]>;
}
/**
* 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
*/
export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void;
export namespace resolveNaptr {
function __promisify__(hostname: string): Promise<NaptrRecord[]>;
}
/**
* 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
*/
export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export namespace resolveNs {
function __promisify__(hostname: string): Promise<string[]>;
}
/**
* 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
*/
export function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export namespace resolvePtr {
function __promisify__(hostname: string): Promise<string[]>;
}
/**
* 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
*/
export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void;
export namespace resolveSoa {
function __promisify__(hostname: string): Promise<SoaRecord>;
}
/**
* 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
*/
export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void;
export namespace resolveSrv {
function __promisify__(hostname: string): Promise<SrvRecord[]>;
}
/**
* 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
*/
export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void;
export namespace resolveTxt {
function __promisify__(hostname: string): Promise<string[][]>;
}
/**
* 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:
*
* <omitted>
*
* 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).
*/
export function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void;
export namespace resolveAny {
function __promisify__(hostname: string): Promise<AnyRecord[]>;
}
/**
* Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
* array of host names.
*
* On error, `err` is an `Error` object, where `err.code` is
* one of the `DNS error codes`.
* @since v0.1.16
*/
export function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void;
/**
* 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` formatted addresses
*/
export function setServers(servers: ReadonlyArray<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
*/
export function getServers(): string[];
/**
* Set the default value of `verbatim` in {@link lookup}. The value could be:
* - `ipv4first`: sets default `verbatim` `false`.
* - `verbatim`: sets default `verbatim` `true`.
*
* The default is `ipv4first` and {@link setDefaultResultOrder} have higher priority than `--dns-result-order`.
* When using worker threads, {@link setDefaultResultOrder} from the main thread won't affect the default dns orders in workers.
* @since v14.18.0
* @param order must be 'ipv4first' or 'verbatim'.
*/
export function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void;
// Error codes
export const NODATA: string;
export const FORMERR: string;
export const SERVFAIL: string;
export const NOTFOUND: string;
export const NOTIMP: string;
export const REFUSED: string;
export const BADQUERY: string;
export const BADNAME: string;
export const BADFAMILY: string;
export const BADRESP: string;
export const CONNREFUSED: string;
export const TIMEOUT: string;
export const EOF: string;
export const FILE: string;
export const NOMEM: string;
export const DESTRUCTION: string;
export const BADSTR: string;
export const BADFLAGS: string;
export const NONAME: string;
export const BADHINTS: string;
export const NOTINITIALIZED: string;
export const LOADIPHLPAPI: string;
export const ADDRGETNETWORKPARAMS: string;
export const CANCELLED: string;
export interface ResolverOptions {
timeout?: number | undefined;
/**
* @default 4
*/
tries?: number;
}
/**
* 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()` does not affect
* other resolvers:
*
* ```js
* const { Resolver } = require('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 `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
*/
export 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;
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
* @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;
}
export { dnsPromises as promises };
}
declare module 'node:dns' {
export * from 'dns';
}

View File

@ -0,0 +1,170 @@
/**
* **This module is pending deprecation.** Once a replacement API has been
* finalized, this module will be fully deprecated. Most developers should
* **not** have cause to use this module. Users who absolutely must have
* the functionality that domains provide may rely on it for the time being
* but should expect to have to migrate to a different solution
* in the future.
*
* Domains provide a way to handle multiple different IO operations as a
* single group. If any of the event emitters or callbacks registered to a
* domain emit an `'error'` event, or throw an error, then the domain object
* will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to
* exit immediately with an error code.
* @deprecated Since v1.4.2 - Deprecated
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/domain.js)
*/
declare module 'domain' {
import EventEmitter = require('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 timers and event emitters that have been explicitly added
* to the domain.
*/
members: Array<EventEmitter | NodeJS.Timer>;
/**
* 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 lowlevel 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
* const domain = require('domain');
* const fs = require('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<T>(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.
*
* This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by
* the domain `'error'` handler.
*
* If the Timer or `EventEmitter` was already bound to a domain, it is removed
* from that one, and bound to this one instead.
* @param emitter emitter or timer to be added to the domain
*/
add(emitter: EventEmitter | NodeJS.Timer): void;
/**
* The opposite of {@link add}. Removes domain handling from the
* specified emitter.
* @param emitter emitter or timer to be removed from the domain
*/
remove(emitter: EventEmitter | NodeJS.Timer): 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<T extends Function>(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<T extends Function>(callback: T): T;
}
function create(): Domain;
}
declare module 'node:domain' {
export * from 'domain';
}

View File

@ -0,0 +1,641 @@
/**
* Much of the Node.js core API is built around an idiomatic asynchronous
* event-driven architecture in which certain kinds of objects (called "emitters")
* emit named events that cause `Function` objects ("listeners") to be called.
*
* For instance: a `net.Server` object emits an event each time a peer
* connects to it; a `fs.ReadStream` emits an event when the file is opened;
* a `stream` emits an event whenever data is available to be read.
*
* All objects that emit events are instances of the `EventEmitter` class. These
* objects expose an `eventEmitter.on()` function that allows one or more
* functions to be attached to named events emitted by the object. Typically,
* event names are camel-cased strings but any valid JavaScript property key
* can be used.
*
* When the `EventEmitter` object emits an event, all of the functions attached
* to that specific event are called _synchronously_. Any values returned by the
* called listeners are _ignored_ and discarded.
*
* The following example shows a simple `EventEmitter` instance with a single
* listener. The `eventEmitter.on()` method is used to register listeners, while
* the `eventEmitter.emit()` method is used to trigger the event.
*
* ```js
* const EventEmitter = require('events');
*
* class MyEmitter extends EventEmitter {}
*
* const myEmitter = new MyEmitter();
* myEmitter.on('event', () => {
* console.log('an event occurred!');
* });
* myEmitter.emit('event');
* ```
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/events.js)
*/
declare module 'events' {
interface EventEmitterOptions {
/**
* Enables automatic capturing of promise rejection.
*/
captureRejections?: boolean | undefined;
}
interface NodeEventTarget {
once(eventName: string | symbol, listener: (...args: any[]) => void): this;
}
interface DOMEventTarget {
addEventListener(
eventName: string,
listener: (...args: any[]) => void,
opts?: {
once: boolean;
}
): any;
}
interface StaticEventEmitterOptions {
signal?: AbortSignal | undefined;
}
interface EventEmitter extends NodeJS.EventEmitter {}
/**
* The `EventEmitter` class is defined and exposed by the `events` module:
*
* ```js
* const EventEmitter = require('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 {
constructor(options?: EventEmitterOptions);
/**
* 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event
* semantics and does not listen to the `'error'` event.
*
* ```js
* const { once, EventEmitter } = require('events');
*
* async function run() {
* 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.log('error happened', err);
* }
* }
*
* run();
* ```
*
* 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
* const { EventEmitter, once } = require('events');
*
* const ee = new EventEmitter();
*
* once(ee, 'error')
* .then(([err]) => console.log('ok', err.message))
* .catch((err) => console.log('error', err.message));
*
* ee.emit('error', new Error('boom'));
*
* // Prints: ok boom
* ```
*
* An `AbortSignal` can be used to cancel waiting for the event:
*
* ```js
* const { EventEmitter, once } = require('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(); // Abort waiting for the event
* ee.emit('foo'); // Prints: Waiting for the event was canceled!
* ```
* @since v11.13.0, v10.16.0
*/
static once(emitter: NodeEventTarget, eventName: string | symbol, options?: StaticEventEmitterOptions): Promise<any[]>;
static once(emitter: DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise<any[]>;
/**
* ```js
* const { on, EventEmitter } = require('events');
*
* (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')) {
* // 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
* const { on, EventEmitter } = require('events');
* 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
* @param eventName The name of the event being listened for
* @return that iterates `eventName` events emitted by the `emitter`
*/
static on(emitter: NodeJS.EventEmitter, eventName: string, options?: StaticEventEmitterOptions): AsyncIterableIterator<any>;
/**
* A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`.
*
* ```js
* const { EventEmitter, listenerCount } = require('events');
* const myEmitter = new EventEmitter();
* myEmitter.on('event', () => {});
* myEmitter.on('event', () => {});
* console.log(listenerCount(myEmitter, 'event'));
* // Prints: 2
* ```
* @since v0.9.12
* @deprecated Since v3.2.0 - Use `listenerCount` instead.
* @param emitter The emitter to query
* @param eventName The event name
*/
static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number;
/**
* 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
* const { getEventListeners, EventEmitter } = require('events');
*
* {
* const ee = new EventEmitter();
* const listener = () => console.log('Events are fun');
* ee.on('foo', listener);
* getEventListeners(ee, 'foo'); // [listener]
* }
* {
* const et = new EventTarget();
* const listener = () => console.log('Events are fun');
* et.addEventListener('foo', listener);
* getEventListeners(et, 'foo'); // [listener]
* }
* ```
* @since v15.2.0
*/
static getEventListeners(emitter: DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[];
/**
* ```js
* const {
* setMaxListeners,
* EventEmitter
* } = require('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 eventsTargets 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.
*/
static setMaxListeners(n?: number, ...eventTargets: Array<DOMEventTarget | NodeJS.EventEmitter>): void;
/**
* 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.
*/
static readonly errorMonitor: unique symbol;
static readonly captureRejectionSymbol: unique symbol;
/**
* Sets or gets the default captureRejection value for all emitters.
*/
// TODO: These should be described using static getter/setter pairs:
static captureRejections: boolean;
static defaultMaxListeners: number;
}
import internal = require('node:events');
namespace EventEmitter {
// Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4
export { internal as EventEmitter };
export interface Abortable {
/**
* When provided the corresponding `AbortController` can be used to cancel an asynchronous action.
*/
signal?: AbortSignal | undefined;
}
}
global {
namespace NodeJS {
interface EventEmitter {
/**
* Alias for `emitter.on(eventName, listener)`.
* @since v0.1.26
*/
addListener(eventName: string | symbol, listener: (...args: any[]) => void): 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
* 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: string | symbol, listener: (...args: any[]) => void): 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
* 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: string | symbol, listener: (...args: any[]) => void): 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
* 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 indices 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
* 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: string | symbol, listener: (...args: any[]) => void): this;
/**
* Alias for `emitter.removeListener()`.
* @since v10.0.0
*/
off(eventName: string | symbol, listener: (...args: any[]) => void): this;
/**
* 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
*/
removeAllListeners(event?: string | symbol): 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;
/**
* Returns the current max listener value for the `EventEmitter` which is either
* set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}.
* @since v1.0.0
*/
getMaxListeners(): 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: string | symbol): Function[];
/**
* Returns a copy of the array of listeners for the event named `eventName`,
* including any wrappers (such as those created by `.once()`).
*
* ```js
* 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: string | symbol): Function[];
/**
* 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
* const EventEmitter = require('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: string | symbol, ...args: any[]): boolean;
/**
* Returns the number of listeners listening to the event named `eventName`.
* @since v3.2.0
* @param eventName The name of the event being listened for
*/
listenerCount(eventName: string | symbol): number;
/**
* 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: string | symbol, listener: (...args: any[]) => void): 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: string | symbol, listener: (...args: any[]) => void): this;
/**
* Returns an array listing the events for which the emitter has registered
* listeners. The values in the array are strings or `Symbol`s.
*
* ```js
* const EventEmitter = require('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(): Array<string | symbol>;
}
}
}
export = EventEmitter;
}
declare module 'node:events' {
import events = require('events');
export = events;
}

3803
CY_Auta_TS/automaty/node_modules/@types/node/fs.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,287 @@
// Declare "static" methods in Error
interface ErrorConstructor {
/** Create .stack property on a target object */
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
/**
* Optional override for formatting stack traces
*
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
*/
prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
stackTraceLimit: number;
}
/*-----------------------------------------------*
* *
* GLOBAL *
* *
------------------------------------------------*/
// For backwards compability
interface NodeRequire extends NodeJS.Require { }
interface RequireResolve extends NodeJS.RequireResolve { }
interface NodeModule extends NodeJS.Module { }
declare var process: NodeJS.Process;
declare var console: Console;
declare var __filename: string;
declare var __dirname: string;
declare var require: NodeRequire;
declare var module: NodeModule;
// Same as module.exports
declare var exports: any;
/**
* Only available if `--expose-gc` is passed to the process.
*/
declare var gc: undefined | (() => void);
//#region borrowed
// from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib
/** A controller object that allows you to abort one or more DOM requests as and when desired. */
interface AbortController {
/**
* Returns the AbortSignal object associated with this object.
*/
readonly signal: AbortSignal;
/**
* Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted.
*/
abort(reason?: any): void;
}
/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */
interface AbortSignal {
/**
* Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.
*/
readonly aborted: boolean;
readonly reason: any;
}
declare var AbortController: {
prototype: AbortController;
new(): AbortController;
};
declare var AbortSignal: {
prototype: AbortSignal;
new(): AbortSignal;
abort(reason?: any): AbortSignal;
timeout(milliseconds: number): AbortSignal;
};
//#endregion borrowed
//#region ArrayLike.at()
interface RelativeIndexable<T> {
/**
* Takes an integer value and returns the item at that index,
* allowing for positive and negative integers.
* Negative integers count back from the last item in the array.
*/
at(index: number): T | undefined;
}
interface String extends RelativeIndexable<string> {}
interface Array<T> extends RelativeIndexable<T> {}
interface ReadonlyArray<T> extends RelativeIndexable<T> {}
interface Int8Array extends RelativeIndexable<number> {}
interface Uint8Array extends RelativeIndexable<number> {}
interface Uint8ClampedArray extends RelativeIndexable<number> {}
interface Int16Array extends RelativeIndexable<number> {}
interface Uint16Array extends RelativeIndexable<number> {}
interface Int32Array extends RelativeIndexable<number> {}
interface Uint32Array extends RelativeIndexable<number> {}
interface Float32Array extends RelativeIndexable<number> {}
interface Float64Array extends RelativeIndexable<number> {}
interface BigInt64Array extends RelativeIndexable<bigint> {}
interface BigUint64Array extends RelativeIndexable<bigint> {}
//#endregion ArrayLike.at() end
/*----------------------------------------------*
* *
* GLOBAL INTERFACES *
* *
*-----------------------------------------------*/
declare namespace NodeJS {
interface CallSite {
/**
* Value of "this"
*/
getThis(): unknown;
/**
* Type of "this" as a string.
* This is the name of the function stored in the constructor field of
* "this", if available. Otherwise the object's [[Class]] internal
* property.
*/
getTypeName(): string | null;
/**
* Current function
*/
getFunction(): Function | undefined;
/**
* Name of the current function, typically its name property.
* If a name property is not available an attempt will be made to try
* to infer a name from the function's context.
*/
getFunctionName(): string | null;
/**
* Name of the property [of "this" or one of its prototypes] that holds
* the current function
*/
getMethodName(): string | null;
/**
* Name of the script [if this function was defined in a script]
*/
getFileName(): string | undefined;
/**
* Current line number [if this function was defined in a script]
*/
getLineNumber(): number | null;
/**
* Current column number [if this function was defined in a script]
*/
getColumnNumber(): number | null;
/**
* A call site object representing the location where eval was called
* [if this function was created using a call to eval]
*/
getEvalOrigin(): string | undefined;
/**
* Is this a toplevel invocation, that is, is "this" the global object?
*/
isToplevel(): boolean;
/**
* Does this call take place in code defined by a call to eval?
*/
isEval(): boolean;
/**
* Is this call in native V8 code?
*/
isNative(): boolean;
/**
* Is this a constructor call?
*/
isConstructor(): boolean;
}
interface ErrnoException extends Error {
errno?: number | undefined;
code?: string | undefined;
path?: string | undefined;
syscall?: string | undefined;
}
interface ReadableStream extends EventEmitter {
readable: boolean;
read(size?: number): string | Buffer;
setEncoding(encoding: BufferEncoding): this;
pause(): this;
resume(): this;
isPaused(): boolean;
pipe<T extends WritableStream>(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<string | Buffer>;
}
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): void;
end(data: string | Uint8Array, cb?: () => void): void;
end(str: string, encoding?: BufferEncoding, cb?: () => void): void;
}
interface ReadWriteStream extends ReadableStream, WritableStream { }
interface RefCounted {
ref(): this;
unref(): this;
}
type TypedArray =
| Uint8Array
| Uint8ClampedArray
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array
| BigUint64Array
| BigInt64Array
| Float32Array
| Float64Array;
type ArrayBufferView = TypedArray | DataView;
interface Require {
(id: string): any;
resolve: RequireResolve;
cache: Dict<NodeModule>;
/**
* @deprecated
*/
extensions: RequireExtensions;
main: Module | undefined;
}
interface RequireResolve {
(id: string, options?: { paths?: string[] | undefined; }): string;
paths(request: string): string[] | null;
}
interface RequireExtensions extends Dict<(m: Module, filename: string) => any> {
'.js': (m: Module, filename: string) => any;
'.json': (m: Module, filename: string) => any;
'.node': (m: Module, filename: string) => any;
}
interface Module {
/**
* `true` if the module is running during the Node.js preload
*/
isPreloading: boolean;
exports: any;
require: Require;
id: string;
filename: string;
loaded: boolean;
/** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */
parent: Module | null | undefined;
children: Module[];
/**
* @since v11.14.0
*
* The directory name of the module. This is usually the same as the path.dirname() of the module.id.
*/
path: string;
paths: string[];
}
interface Dict<T> {
[key: string]: T | undefined;
}
interface ReadOnlyDict<T> {
readonly [key: string]: T | undefined;
}
}

View File

@ -0,0 +1 @@
declare var global: typeof globalThis;

1504
CY_Auta_TS/automaty/node_modules/@types/node/http.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

2100
CY_Auta_TS/automaty/node_modules/@types/node/http2.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

532
CY_Auta_TS/automaty/node_modules/@types/node/https.d.ts generated vendored Normal file
View File

@ -0,0 +1,532 @@
/**
* HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
* separate module.
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/https.js)
*/
declare module 'https' {
import { Duplex } from 'node:stream';
import * as tls from 'node:tls';
import * as http from 'node:http';
import { URL } from 'node:url';
type ServerOptions<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
> = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions<Request, Response>;
type RequestOptions = http.RequestOptions &
tls.SecureContextOptions & {
checkServerIdentity?: typeof tls.checkServerIdentity | undefined;
rejectUnauthorized?: boolean | undefined; // Defaults to true
servername?: string | undefined; // SNI TLS Extension
};
interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions {
rejectUnauthorized?: boolean | undefined;
maxCachedSessions?: number | undefined;
}
/**
* An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information.
* @since v0.4.5
*/
class Agent extends http.Agent {
constructor(options?: AgentOptions);
options: AgentOptions;
}
interface Server<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
> extends http.Server<Request, Response> {}
/**
* 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<Request, Response>);
constructor(
options: ServerOptions<Request, Response>,
requestListener?: http.RequestListener<Request, Response>,
);
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
addListener(
event: 'newSession',
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
): this;
addListener(
event: 'OCSPRequest',
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
addListener(
event: 'resumeSession',
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
): this;
addListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this;
addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
addListener(event: 'close', listener: () => void): this;
addListener(event: 'connection', listener: (socket: Duplex) => void): this;
addListener(event: 'error', listener: (err: Error) => void): this;
addListener(event: 'listening', listener: () => void): this;
addListener(event: 'checkContinue', listener: http.RequestListener<Request, Response>): this;
addListener(event: 'checkExpectation', listener: http.RequestListener<Request, Response>): this;
addListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this;
addListener(
event: 'connect',
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
): this;
addListener(event: 'request', listener: http.RequestListener<Request, Response>): this;
addListener(
event: 'upgrade',
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
): this;
emit(event: string, ...args: any[]): boolean;
emit(event: 'keylog', line: Buffer, tlsSocket: tls.TLSSocket): boolean;
emit(
event: 'newSession',
sessionId: Buffer,
sessionData: Buffer,
callback: (err: Error, resp: Buffer) => void,
): boolean;
emit(
event: 'OCSPRequest',
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
): boolean;
emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean;
emit(event: 'secureConnection', tlsSocket: tls.TLSSocket): boolean;
emit(event: 'tlsClientError', err: Error, tlsSocket: tls.TLSSocket): boolean;
emit(event: 'close'): boolean;
emit(event: 'connection', socket: Duplex): boolean;
emit(event: 'error', err: Error): boolean;
emit(event: 'listening'): boolean;
emit(
event: 'checkContinue',
req: InstanceType<Request>,
res: InstanceType<Response> & { req: InstanceType<Request> },
): boolean;
emit(
event: 'checkExpectation',
req: InstanceType<Request>,
res: InstanceType<Response> & { req: InstanceType<Request> },
): boolean;
emit(event: 'clientError', err: Error, socket: Duplex): boolean;
emit(event: 'connect', req: InstanceType<Request>, socket: Duplex, head: Buffer): boolean;
emit(
event: 'request',
req: InstanceType<Request>,
res: InstanceType<Response> & { req: InstanceType<Request> },
): boolean;
emit(event: 'upgrade', req: InstanceType<Request>, socket: Duplex, head: Buffer): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
on(
event: 'newSession',
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
): this;
on(
event: 'OCSPRequest',
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
on(
event: 'resumeSession',
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
): this;
on(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this;
on(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
on(event: 'close', listener: () => void): this;
on(event: 'connection', listener: (socket: Duplex) => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'listening', listener: () => void): this;
on(event: 'checkContinue', listener: http.RequestListener<Request, Response>): this;
on(event: 'checkExpectation', listener: http.RequestListener<Request, Response>): this;
on(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this;
on(event: 'connect', listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this;
on(event: 'request', listener: http.RequestListener<Request, Response>): this;
on(event: 'upgrade', listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
once(
event: 'newSession',
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
): this;
once(
event: 'OCSPRequest',
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
once(
event: 'resumeSession',
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
): this;
once(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this;
once(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
once(event: 'close', listener: () => void): this;
once(event: 'connection', listener: (socket: Duplex) => void): this;
once(event: 'error', listener: (err: Error) => void): this;
once(event: 'listening', listener: () => void): this;
once(event: 'checkContinue', listener: http.RequestListener<Request, Response>): this;
once(event: 'checkExpectation', listener: http.RequestListener<Request, Response>): this;
once(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this;
once(event: 'connect', listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this;
once(event: 'request', listener: http.RequestListener<Request, Response>): this;
once(event: 'upgrade', listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
prependListener(
event: 'newSession',
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
): this;
prependListener(
event: 'OCSPRequest',
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
prependListener(
event: 'resumeSession',
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
): this;
prependListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this;
prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
prependListener(event: 'close', listener: () => void): this;
prependListener(event: 'connection', listener: (socket: Duplex) => void): this;
prependListener(event: 'error', listener: (err: Error) => void): this;
prependListener(event: 'listening', listener: () => void): this;
prependListener(event: 'checkContinue', listener: http.RequestListener<Request, Response>): this;
prependListener(event: 'checkExpectation', listener: http.RequestListener<Request, Response>): this;
prependListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this;
prependListener(
event: 'connect',
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
): this;
prependListener(event: 'request', listener: http.RequestListener<Request, Response>): this;
prependListener(
event: 'upgrade',
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
prependOnceListener(
event: 'newSession',
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
): this;
prependOnceListener(
event: 'OCSPRequest',
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
prependOnceListener(
event: 'resumeSession',
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
): this;
prependOnceListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this;
prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
prependOnceListener(event: 'close', listener: () => void): this;
prependOnceListener(event: 'connection', listener: (socket: Duplex) => void): this;
prependOnceListener(event: 'error', listener: (err: Error) => void): this;
prependOnceListener(event: 'listening', listener: () => void): this;
prependOnceListener(event: 'checkContinue', listener: http.RequestListener<Request, Response>): this;
prependOnceListener(event: 'checkExpectation', listener: http.RequestListener<Request, Response>): this;
prependOnceListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this;
prependOnceListener(
event: 'connect',
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
): this;
prependOnceListener(event: 'request', listener: http.RequestListener<Request, Response>): this;
prependOnceListener(
event: 'upgrade',
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
): this;
}
/**
* ```js
* // curl -k https://localhost:8000/
* const https = require('https');
* const fs = require('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
* const https = require('https');
* const fs = require('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<Request, Response>): Server<Request, Response>;
function createServer<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
>(
options: ServerOptions<Request, Response>,
requestListener?: http.RequestListener<Request, Response>,
): Server<Request, Response>;
/**
* 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
* const https = require('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
* const tls = require('tls');
* const https = require('https');
* const crypto = require('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-sha25 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
* const https = require('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 'node:https' {
export * from 'https';
}

131
CY_Auta_TS/automaty/node_modules/@types/node/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,131 @@
// Type definitions for non-npm package Node.js 16.18
// Project: https://nodejs.org/
// Definitions by: Microsoft TypeScript <https://github.com/Microsoft>
// DefinitelyTyped <https://github.com/DefinitelyTyped>
// Alberto Schiabel <https://github.com/jkomyno>
// Alvis HT Tang <https://github.com/alvis>
// Andrew Makarov <https://github.com/r3nya>
// Benjamin Toueg <https://github.com/btoueg>
// Chigozirim C. <https://github.com/smac89>
// David Junger <https://github.com/touffy>
// Deividas Bakanas <https://github.com/DeividasBakanas>
// Eugene Y. Q. Shen <https://github.com/eyqs>
// Hannes Magnusson <https://github.com/Hannes-Magnusson-CK>
// Huw <https://github.com/hoo29>
// Kelvin Jin <https://github.com/kjin>
// Klaus Meinhardt <https://github.com/ajafff>
// Lishude <https://github.com/islishude>
// Mariusz Wiktorczyk <https://github.com/mwiktorczyk>
// Mohsen Azimi <https://github.com/mohsen1>
// Nicolas Even <https://github.com/n-e>
// Nikita Galkin <https://github.com/galkin>
// Parambir Singh <https://github.com/parambirs>
// Sebastian Silbermann <https://github.com/eps1lon>
// Seth Westphal <https://github.com/westy92>
// Simon Schick <https://github.com/SimonSchick>
// Thomas den Hollander <https://github.com/ThomasdenH>
// Wilco Bakker <https://github.com/WilcoBakker>
// wwwy3y3 <https://github.com/wwwy3y3>
// Samuel Ainsworth <https://github.com/samuela>
// Kyle Uehlein <https://github.com/kuehlein>
// Thanik Bhongbhibhat <https://github.com/bhongy>
// 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>
// Yongsheng Zhang <https://github.com/ZYSzys>
// NodeJS Contributors <https://github.com/NodeJS>
// Linus Unnebäck <https://github.com/LinusU>
// wafuwafu13 <https://github.com/wafuwafu13>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* 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 NodeJS and TypeScript 4.9+.
// Reference required types from the default lib:
/// <reference lib="es2020" />
/// <reference lib="esnext.asynciterable" />
/// <reference lib="esnext.intl" />
/// <reference lib="esnext.bigint" />
// Base definitions for all NodeJS modules that are not specific to any version of TypeScript:
/// <reference path="assert.d.ts" />
/// <reference path="assert/strict.d.ts" />
/// <reference path="globals.d.ts" />
/// <reference path="async_hooks.d.ts" />
/// <reference path="buffer.d.ts" />
/// <reference path="child_process.d.ts" />
/// <reference path="cluster.d.ts" />
/// <reference path="console.d.ts" />
/// <reference path="constants.d.ts" />
/// <reference path="crypto.d.ts" />
/// <reference path="dgram.d.ts" />
/// <reference path="diagnostics_channel.d.ts" />
/// <reference path="dns.d.ts" />
/// <reference path="dns/promises.d.ts" />
/// <reference path="dns/promises.d.ts" />
/// <reference path="domain.d.ts" />
/// <reference path="events.d.ts" />
/// <reference path="fs.d.ts" />
/// <reference path="fs/promises.d.ts" />
/// <reference path="http.d.ts" />
/// <reference path="http2.d.ts" />
/// <reference path="https.d.ts" />
/// <reference path="inspector.d.ts" />
/// <reference path="module.d.ts" />
/// <reference path="net.d.ts" />
/// <reference path="os.d.ts" />
/// <reference path="path.d.ts" />
/// <reference path="perf_hooks.d.ts" />
/// <reference path="process.d.ts" />
/// <reference path="punycode.d.ts" />
/// <reference path="querystring.d.ts" />
/// <reference path="readline.d.ts" />
/// <reference path="repl.d.ts" />
/// <reference path="stream.d.ts" />
/// <reference path="stream/promises.d.ts" />
/// <reference path="stream/consumers.d.ts" />
/// <reference path="stream/web.d.ts" />
/// <reference path="string_decoder.d.ts" />
/// <reference path="test.d.ts" />
/// <reference path="timers.d.ts" />
/// <reference path="timers/promises.d.ts" />
/// <reference path="tls.d.ts" />
/// <reference path="trace_events.d.ts" />
/// <reference path="tty.d.ts" />
/// <reference path="url.d.ts" />
/// <reference path="util.d.ts" />
/// <reference path="v8.d.ts" />
/// <reference path="vm.d.ts" />
/// <reference path="wasi.d.ts" />
/// <reference path="worker_threads.d.ts" />
/// <reference path="zlib.d.ts" />
/// <reference path="globals.global.d.ts" />

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,115 @@
/**
* @since v0.3.7
*/
declare module 'module' {
import { URL } from 'node:url';
namespace Module {
/**
* 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
* const fs = require('fs');
* const assert = require('assert');
* const { syncBuiltinESMExports } = require('module');
*
* fs.readFile = newAPI;
*
* delete fs.readFileSync;
*
* function newAPI() {
* // ...
* }
*
* fs.newAPI = newAPI;
*
* syncBuiltinESMExports();
*
* import('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;
/**
* `path` is the resolved path for the file for which a corresponding source map
* should be fetched.
* @since v13.7.0, v12.17.0
*/
function findSourceMap(path: string, error?: Error): SourceMap;
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;
}
/**
* @since v13.7.0, v12.17.0
*/
class SourceMap {
/**
* Getter for the payload used to construct the `SourceMap` instance.
*/
readonly payload: SourceMapPayload;
constructor(payload: SourceMapPayload);
/**
* Given a line number and column number in the generated source file, returns
* an object representing the position in the original file. The object returned
* consists of the following keys:
*/
findEntry(line: number, column: number): SourceMapping;
}
}
interface Module extends NodeModule {}
class Module {
static runMain(): void;
static wrap(code: string): string;
static createRequire(path: string | URL): NodeRequire;
static builtinModules: string[];
static isBuiltin(moduleName: string): boolean;
static Module: typeof Module;
constructor(id: string, parent?: Module);
}
global {
interface ImportMeta {
url: string;
/**
* @experimental
* This feature is only available with the `--experimental-import-meta-resolve`
* command flag enabled.
*
* Provides a module-relative resolution function scoped to each module, returning
* the URL string.
*
* @param specified The module specifier to resolve relative to `parent`.
* @param parent The absolute parent module URL to resolve from. If none
* is specified, the value of `import.meta.url` is used as the default.
*/
resolve?(specified: string, parent?: string | URL): Promise<string>;
}
}
export = Module;
}
declare module 'node:module' {
import module = require('module');
export = module;
}

828
CY_Auta_TS/automaty/node_modules/@types/node/net.d.ts generated vendored Normal file
View File

@ -0,0 +1,828 @@
/**
* > Stability: 2 - Stable
*
* The `net` module provides an asynchronous network API for creating stream-based
* TCP or `IPC` servers ({@link createServer}) and clients
* ({@link createConnection}).
*
* It can be accessed using:
*
* ```js
* const net = require('net');
* ```
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/net.js)
*/
declare module 'net' {
import * as stream from 'node:stream';
import { Abortable, EventEmitter } from 'node:events';
import * as dns from 'node:dns';
type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void;
interface AddressInfo {
address: string;
family: string;
port: number;
}
interface SocketConstructorOpts {
fd?: number | undefined;
allowHalfOpen?: boolean | undefined;
readable?: boolean | undefined;
writable?: boolean | undefined;
signal?: AbortSignal;
}
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, buf: Uint8Array): boolean;
}
interface ConnectOpts {
/**
* If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket.
* Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will
* still be emitted as normal and methods like pause() and resume() will also behave as expected.
*/
onread?: OnReadOpts | undefined;
}
interface TcpSocketConnectOpts extends ConnectOpts {
port: number;
host?: string | undefined;
localAddress?: string | undefined;
localPort?: number | undefined;
hints?: number | undefined;
family?: number | undefined;
lookup?: LookupFunction | undefined;
noDelay?: boolean | undefined;
keepAlive?: boolean | undefined;
keepAliveInitialDelay?: number | undefined;
}
interface IpcSocketConnectOpts extends ConnectOpts {
path: string;
}
type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts;
type SocketReadyState = 'opening' | 'open' | 'readOnly' | 'writeOnly' | 'closed';
/**
* 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);
/**
* 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
* @param [encoding='utf8'] Only used when data is `string`.
*/
write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean;
write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => 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;
/**
* 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 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 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;
/**
* 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 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 v10.16.0
*/
readonly pending: boolean;
/**
* This property represents the state of the connection as a string.
* @see {https://nodejs.org/api/net.html#socketreadystate}
* @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'`.
* @since v0.11.14
*/
readonly remoteFamily?: string | undefined;
/**
* The numeric representation of the remote port. For example, `80` or `21`.
* @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 | undefined;
/**
* 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 [encoding='utf8'] Only used when data is `string`.
* @param callback Optional callback for when the socket is finished.
* @return The socket itself.
*/
end(callback?: () => void): this;
end(buffer: Uint8Array | string, callback?: () => void): this;
end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this;
/**
* events.EventEmitter
* 1. close
* 2. connect
* 3. data
* 4. drain
* 5. end
* 6. error
* 7. lookup
* 8. timeout
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'close', listener: (hadError: boolean) => void): this;
addListener(event: 'connect', listener: () => void): this;
addListener(event: 'data', listener: (data: Buffer) => void): this;
addListener(event: 'drain', listener: () => void): this;
addListener(event: 'end', listener: () => void): this;
addListener(event: 'error', listener: (err: Error) => void): this;
addListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this;
addListener(event: 'ready', listener: () => void): this;
addListener(event: 'timeout', listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: 'close', hadError: boolean): boolean;
emit(event: 'connect'): boolean;
emit(event: 'data', data: Buffer): boolean;
emit(event: 'drain'): boolean;
emit(event: 'end'): boolean;
emit(event: 'error', err: Error): boolean;
emit(event: 'lookup', err: Error, address: string, family: string | number, host: string): boolean;
emit(event: 'ready'): boolean;
emit(event: 'timeout'): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'close', listener: (hadError: boolean) => void): this;
on(event: 'connect', listener: () => void): this;
on(event: 'data', listener: (data: Buffer) => void): this;
on(event: 'drain', listener: () => void): this;
on(event: 'end', listener: () => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this;
on(event: 'ready', listener: () => void): this;
on(event: 'timeout', listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'close', listener: (hadError: boolean) => void): this;
once(event: 'connect', listener: () => void): this;
once(event: 'data', listener: (data: Buffer) => void): this;
once(event: 'drain', listener: () => void): this;
once(event: 'end', listener: () => void): this;
once(event: 'error', listener: (err: Error) => void): this;
once(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this;
once(event: 'ready', listener: () => void): this;
once(event: 'timeout', listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'close', listener: (hadError: boolean) => void): this;
prependListener(event: 'connect', listener: () => void): this;
prependListener(event: 'data', listener: (data: Buffer) => void): this;
prependListener(event: 'drain', listener: () => void): this;
prependListener(event: 'end', listener: () => void): this;
prependListener(event: 'error', listener: (err: Error) => void): this;
prependListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this;
prependListener(event: 'ready', listener: () => void): this;
prependListener(event: 'timeout', listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'close', listener: (hadError: boolean) => void): this;
prependOnceListener(event: 'connect', listener: () => void): this;
prependOnceListener(event: 'data', listener: (data: Buffer) => void): this;
prependOnceListener(event: 'drain', listener: () => void): this;
prependOnceListener(event: 'end', listener: () => void): this;
prependOnceListener(event: 'error', listener: (err: Error) => void): this;
prependOnceListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this;
prependOnceListener(event: 'ready', listener: () => void): this;
prependOnceListener(event: 'timeout', listener: () => void): this;
}
interface ListenOptions extends Abortable {
port?: number | undefined;
host?: string | undefined;
backlog?: number | undefined;
path?: string | undefined;
exclusive?: boolean | undefined;
readableAll?: boolean | undefined;
writableAll?: boolean | undefined;
/**
* @default false
*/
ipv6Only?: 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;
}
/**
* This class is used to create a TCP or `IPC` server.
* @since v0.1.90
*/
class Server extends 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.log('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): void;
/**
* 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
*/
listening: boolean;
/**
* events.EventEmitter
* 1. close
* 2. connection
* 3. error
* 4. listening
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'close', listener: () => void): this;
addListener(event: 'connection', listener: (socket: Socket) => void): this;
addListener(event: 'error', listener: (err: Error) => void): this;
addListener(event: 'listening', listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: 'close'): boolean;
emit(event: 'connection', socket: Socket): boolean;
emit(event: 'error', err: Error): boolean;
emit(event: 'listening'): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'close', listener: () => void): this;
on(event: 'connection', listener: (socket: Socket) => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'listening', listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'close', listener: () => void): this;
once(event: 'connection', listener: (socket: Socket) => void): this;
once(event: 'error', listener: (err: Error) => void): this;
once(event: 'listening', listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'close', listener: () => void): this;
prependListener(event: 'connection', listener: (socket: Socket) => void): this;
prependListener(event: 'error', listener: (err: Error) => void): this;
prependListener(event: 'listening', listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'close', listener: () => void): this;
prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this;
prependOnceListener(event: 'error', listener: (err: Error) => void): this;
prependOnceListener(event: 'listening', listener: () => void): this;
}
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
*/
class BlockList {
/**
* Adds a rule to block the given IP address.
* @since v15.0.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
* @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
* @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
* @param address The IP address to check
* @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
*/
check(address: SocketAddress): boolean;
check(address: string, type?: IPVersion): boolean;
}
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 an TCP echo server which listens for connections
* on port 8124:
*
* ```js
* const net = require('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`:
*
* ```console
* $ 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:
*
* ```console
* $ 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;
/**
* Tests if input is an IP address. Returns `0` for invalid strings,
* returns `4` for IP version 4 addresses, and returns `6` for IP version 6
* addresses.
* @since v0.3.0
*/
function isIP(input: string): number;
/**
* Returns `true` if input is a version 4 IP address, otherwise returns `false`.
* @since v0.3.0
*/
function isIPv4(input: string): boolean;
/**
* Returns `true` if input is a version 6 IP address, otherwise 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
*/
class SocketAddress {
constructor(options: SocketAddressInitOptions);
/**
* @since v15.14.0
*/
readonly address: string;
/**
* Either \`'ipv4'\` or \`'ipv6'\`.
* @since v15.14.0
*/
readonly family: IPVersion;
/**
* @since v15.14.0
*/
readonly port: number;
/**
* @since v15.14.0
*/
readonly flowlabel: number;
}
}
declare module 'node:net' {
export * from 'net';
}

455
CY_Auta_TS/automaty/node_modules/@types/node/os.d.ts generated vendored Normal file
View File

@ -0,0 +1,455 @@
/**
* The `os` module provides operating system-related utility methods and
* properties. It can be accessed using:
*
* ```js
* const os = require('os');
* ```
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/os.js)
*/
declare module 'os' {
interface CpuInfo {
model: string;
speed: number;
times: {
user: number;
nice: number;
sys: number;
idle: number;
irq: number;
};
}
interface NetworkInterfaceBase {
address: string;
netmask: string;
mac: string;
internal: boolean;
cidr: string | null;
}
interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase {
family: 'IPv4';
}
interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase {
family: 'IPv6';
scopeid: number;
}
interface UserInfo<T> {
username: T;
uid: number;
gid: number;
shell: T;
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 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.
* @since v0.3.3
*/
function cpus(): CpuInfo[];
/**
* 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<NetworkInterfaceInfo[]>;
/**
* 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;
/**
* 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` if a user has no `username` or `homedir`.
* @since v6.0.0
*/
function userInfo(options: { encoding: 'buffer' }): UserInfo<Buffer>;
function userInfo(options?: { encoding: BufferEncoding }): UserInfo<string>;
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 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;
const EOL: string;
/**
* Returns the operating system CPU architecture for which the Node.js binary was
* compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`.
*
* The return value is equivalent to `process.arch`.
* @since v0.5.0
*/
function arch(): string;
/**
* 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. 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 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 'node:os' {
export * from 'os';
}

View File

@ -0,0 +1,232 @@
{
"name": "@types/node",
"version": "16.18.39",
"description": "TypeScript definitions for Node.js",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node",
"license": "MIT",
"contributors": [
{
"name": "Microsoft TypeScript",
"url": "https://github.com/Microsoft",
"githubUsername": "Microsoft"
},
{
"name": "DefinitelyTyped",
"url": "https://github.com/DefinitelyTyped",
"githubUsername": "DefinitelyTyped"
},
{
"name": "Alberto Schiabel",
"url": "https://github.com/jkomyno",
"githubUsername": "jkomyno"
},
{
"name": "Alvis HT Tang",
"url": "https://github.com/alvis",
"githubUsername": "alvis"
},
{
"name": "Andrew Makarov",
"url": "https://github.com/r3nya",
"githubUsername": "r3nya"
},
{
"name": "Benjamin Toueg",
"url": "https://github.com/btoueg",
"githubUsername": "btoueg"
},
{
"name": "Chigozirim C.",
"url": "https://github.com/smac89",
"githubUsername": "smac89"
},
{
"name": "David Junger",
"url": "https://github.com/touffy",
"githubUsername": "touffy"
},
{
"name": "Deividas Bakanas",
"url": "https://github.com/DeividasBakanas",
"githubUsername": "DeividasBakanas"
},
{
"name": "Eugene Y. Q. Shen",
"url": "https://github.com/eyqs",
"githubUsername": "eyqs"
},
{
"name": "Hannes Magnusson",
"url": "https://github.com/Hannes-Magnusson-CK",
"githubUsername": "Hannes-Magnusson-CK"
},
{
"name": "Huw",
"url": "https://github.com/hoo29",
"githubUsername": "hoo29"
},
{
"name": "Kelvin Jin",
"url": "https://github.com/kjin",
"githubUsername": "kjin"
},
{
"name": "Klaus Meinhardt",
"url": "https://github.com/ajafff",
"githubUsername": "ajafff"
},
{
"name": "Lishude",
"url": "https://github.com/islishude",
"githubUsername": "islishude"
},
{
"name": "Mariusz Wiktorczyk",
"url": "https://github.com/mwiktorczyk",
"githubUsername": "mwiktorczyk"
},
{
"name": "Mohsen Azimi",
"url": "https://github.com/mohsen1",
"githubUsername": "mohsen1"
},
{
"name": "Nicolas Even",
"url": "https://github.com/n-e",
"githubUsername": "n-e"
},
{
"name": "Nikita Galkin",
"url": "https://github.com/galkin",
"githubUsername": "galkin"
},
{
"name": "Parambir Singh",
"url": "https://github.com/parambirs",
"githubUsername": "parambirs"
},
{
"name": "Sebastian Silbermann",
"url": "https://github.com/eps1lon",
"githubUsername": "eps1lon"
},
{
"name": "Seth Westphal",
"url": "https://github.com/westy92",
"githubUsername": "westy92"
},
{
"name": "Simon Schick",
"url": "https://github.com/SimonSchick",
"githubUsername": "SimonSchick"
},
{
"name": "Thomas den Hollander",
"url": "https://github.com/ThomasdenH",
"githubUsername": "ThomasdenH"
},
{
"name": "Wilco Bakker",
"url": "https://github.com/WilcoBakker",
"githubUsername": "WilcoBakker"
},
{
"name": "wwwy3y3",
"url": "https://github.com/wwwy3y3",
"githubUsername": "wwwy3y3"
},
{
"name": "Samuel Ainsworth",
"url": "https://github.com/samuela",
"githubUsername": "samuela"
},
{
"name": "Kyle Uehlein",
"url": "https://github.com/kuehlein",
"githubUsername": "kuehlein"
},
{
"name": "Thanik Bhongbhibhat",
"url": "https://github.com/bhongy",
"githubUsername": "bhongy"
},
{
"name": "Marcin Kopacz",
"url": "https://github.com/chyzwar",
"githubUsername": "chyzwar"
},
{
"name": "Trivikram Kamat",
"url": "https://github.com/trivikr",
"githubUsername": "trivikr"
},
{
"name": "Junxiao Shi",
"url": "https://github.com/yoursunny",
"githubUsername": "yoursunny"
},
{
"name": "Ilia Baryshnikov",
"url": "https://github.com/qwelias",
"githubUsername": "qwelias"
},
{
"name": "ExE Boss",
"url": "https://github.com/ExE-Boss",
"githubUsername": "ExE-Boss"
},
{
"name": "Piotr Błażejewicz",
"url": "https://github.com/peterblazejewicz",
"githubUsername": "peterblazejewicz"
},
{
"name": "Anna Henningsen",
"url": "https://github.com/addaleax",
"githubUsername": "addaleax"
},
{
"name": "Victor Perin",
"url": "https://github.com/victorperin",
"githubUsername": "victorperin"
},
{
"name": "Yongsheng Zhang",
"url": "https://github.com/ZYSzys",
"githubUsername": "ZYSzys"
},
{
"name": "NodeJS Contributors",
"url": "https://github.com/NodeJS",
"githubUsername": "NodeJS"
},
{
"name": "Linus Unnebäck",
"url": "https://github.com/LinusU",
"githubUsername": "LinusU"
},
{
"name": "wafuwafu13",
"url": "https://github.com/wafuwafu13",
"githubUsername": "wafuwafu13"
}
],
"main": "",
"types": "index.d.ts",
"typesVersions": {
"<=4.8": {
"*": [
"ts4.8/*"
]
}
},
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/node"
},
"scripts": {},
"dependencies": {},
"typesPublisherContentHash": "9de734dc90d87a4ef624f9d0ea48726baf5d8b1f888043d9319b07fa2129d49d",
"typeScriptVersion": "4.3"
}

191
CY_Auta_TS/automaty/node_modules/@types/node/path.d.ts generated vendored Normal file
View File

@ -0,0 +1,191 @@
declare module 'path/posix' {
import path = require('path');
export = path;
}
declare module 'path/win32' {
import path = require('path');
export = path;
}
/**
* The `path` module provides utilities for working with file and directory paths.
* It can be accessed using:
*
* ```js
* const path = require('path');
* ```
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/path.js)
*/
declare module '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;
}
interface PlatformPath {
/**
* 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.
*
* @param path string path to normalize.
* @throws {TypeError} if `path` is not a string.
*/
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.
*/
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 string paths to join.
* @throws {TypeError} if any of the arguments is not a string.
*/
resolve(...paths: string[]): string;
/**
* 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.
*/
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.
*/
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.
*/
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 ext 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.
*/
basename(path: string, ext?: 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.
*/
extname(path: string): string;
/**
* The platform-specific file separator. '\\' or '/'.
*/
readonly sep: '\\' | '/';
/**
* The platform-specific file delimiter. ';' or ':'.
*/
readonly 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.
*/
parse(path: string): ParsedPath;
/**
* Returns a path string from an object - the opposite of parse().
*
* @param pathObject path to evaluate.
*/
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.
*/
toNamespacedPath(path: string): string;
/**
* Posix specific pathing.
* Same as parent object on posix.
*/
readonly posix: PlatformPath;
/**
* Windows specific pathing.
* Same as parent object on windows
*/
readonly win32: PlatformPath;
}
}
const path: path.PlatformPath;
export = path;
}
declare module 'node:path' {
import path = require('path');
export = path;
}
declare module 'node:path/posix' {
import path = require('path/posix');
export = path;
}
declare module 'node:path/win32' {
import path = require('path/win32');
export = path;
}

View File

@ -0,0 +1,586 @@
/**
* This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for
* Node.js-specific performance measurements.
*
* Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/):
*
* * [High Resolution Time](https://www.w3.org/TR/hr-time-2)
* * [Performance Timeline](https://w3c.github.io/performance-timeline/)
* * [User Timing](https://www.w3.org/TR/user-timing/)
*
* ```js
* const { PerformanceObserver, performance } = require('perf_hooks');
*
* const obs = new PerformanceObserver((items) => {
* console.log(items.getEntries()[0].duration);
* performance.clearMarks();
* });
* obs.observe({ type: 'measure' });
* performance.measure('Start to Now');
*
* performance.mark('A');
* doSomeLongRunningProcess(() => {
* performance.measure('A to Now', 'A');
*
* performance.mark('B');
* performance.measure('A to B', 'A', 'B');
* });
* ```
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/perf_hooks.js)
*/
declare module 'perf_hooks' {
import { AsyncResource } from 'node:async_hooks';
type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http';
interface NodeGCPerformanceDetail {
/**
* When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies
* the type of garbage collection operation that occurred.
* See perf_hooks.constants for valid values.
*/
readonly kind?: number | undefined;
/**
* When `performanceEntry.entryType` is equal to 'gc', the `performance.flags`
* property contains additional information about garbage collection operation.
* See perf_hooks.constants for valid values.
*/
readonly flags?: number | undefined;
}
/**
* @since v8.5.0
*/
class PerformanceEntry {
protected constructor();
/**
* The total number of milliseconds elapsed for this entry. This value will not
* be meaningful for all Performance Entry types.
* @since v8.5.0
*/
readonly duration: number;
/**
* The name of the performance entry.
* @since v8.5.0
*/
readonly name: string;
/**
* The high resolution millisecond timestamp marking the starting time of the
* Performance Entry.
* @since v8.5.0
*/
readonly startTime: number;
/**
* The type of the performance entry. It may be one of:
*
* * `'node'` (Node.js only)
* * `'mark'` (available on the Web)
* * `'measure'` (available on the Web)
* * `'gc'` (Node.js only)
* * `'function'` (Node.js only)
* * `'http2'` (Node.js only)
* * `'http'` (Node.js only)
* @since v8.5.0
*/
readonly entryType: EntryType;
/**
* Additional detail specific to the `entryType`.
* @since v16.0.0
*/
readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type.
}
/**
* _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
*/
class 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;
/**
* 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 V8 platform was
* initialized.
* @since v8.5.0
*/
readonly v8Start: number;
}
interface EventLoopUtilization {
idle: number;
active: number;
utilization: number;
}
/**
* @param util1 The result of a previous call to eventLoopUtilization()
* @param util2 The result of a previous call to eventLoopUtilization() prior to util1
*/
type EventLoopUtilityFunction = (util1?: EventLoopUtilization, util2?: EventLoopUtilization) => EventLoopUtilization;
interface MarkOptions {
/**
* Additional optional detail to include with the mark.
*/
detail?: unknown | undefined;
/**
* An optional timestamp to be used as the mark time.
* @default `performance.now()`.
*/
startTime?: number | undefined;
}
interface MeasureOptions {
/**
* Additional optional detail to include with the mark.
*/
detail?: unknown | undefined;
/**
* Duration between start and end times.
*/
duration?: number | undefined;
/**
* Timestamp to be used as the end time, or a string identifying a previously recorded mark.
*/
end?: number | string | undefined;
/**
* Timestamp to be used as the start time, or a string identifying a previously recorded mark.
*/
start?: number | string | undefined;
}
interface TimerifyOptions {
/**
* A histogram object created using
* `perf_hooks.createHistogram()` that will record runtime durations in
* nanoseconds.
*/
histogram?: RecordableHistogram | undefined;
}
interface Performance {
/**
* If name is not provided, removes all PerformanceMark objects from the Performance Timeline.
* If name is provided, removes only the named mark.
* @param name
*/
clearMarks(name?: string): void;
/**
* If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline.
* If name is provided, removes only the named measure.
* @param name
* @since v16.7.0
*/
clearMeasures(name?: string): void;
/**
* Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`.
* If you are only interested in performance entries of certain types or that have certain names, see
* `performance.getEntriesByType()` and `performance.getEntriesByName()`.
* @since v16.7.0
*/
getEntries(): PerformanceEntry[];
/**
* Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`
* whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`.
* @param name
* @param type
* @since v16.7.0
*/
getEntriesByName(name: string, type?: EntryType): PerformanceEntry[];
/**
* Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`
* whose `performanceEntry.entryType` is equal to `type`.
* @param type
* @since v16.7.0
*/
getEntriesByType(type: EntryType): PerformanceEntry[];
/**
* Creates a new PerformanceMark entry in the Performance Timeline.
* A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark',
* and whose performanceEntry.duration is always 0.
* Performance marks are used to mark specific significant moments in the Performance Timeline.
* @param name
*/
mark(name?: string, options?: MarkOptions): void;
/**
* Creates a new PerformanceMeasure entry in the Performance Timeline.
* A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure',
* and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark.
*
* The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify
* any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist,
* then startMark is set to timeOrigin by default.
*
* The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp
* properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown.
* @param name
* @param startMark
* @param endMark
*/
measure(name: string, startMark?: string, endMark?: string): void;
measure(name: string, options: MeasureOptions): void;
/**
* An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones.
*/
readonly nodeTiming: PerformanceNodeTiming;
/**
* @return the current high resolution millisecond timestamp
*/
now(): number;
/**
* The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured.
*/
readonly timeOrigin: number;
/**
* 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.
* @param fn
*/
timerify<T extends (...params: any[]) => any>(fn: T, options?: TimerifyOptions): T;
/**
* eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time.
* 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.
*/
eventLoopUtilization: EventLoopUtilityFunction;
}
interface PerformanceObserverEntryList {
/**
* Returns a list of `PerformanceEntry` objects in chronological order
* with respect to `performanceEntry.startTime`.
*
* ```js
* const {
* performance,
* PerformanceObserver
* } = require('perf_hooks');
*
* const obs = new PerformanceObserver((perfObserverList, observer) => {
* console.log(perfObserverList.getEntries());
*
* * [
* * PerformanceEntry {
* * name: 'test',
* * entryType: 'mark',
* * startTime: 81.465639,
* * duration: 0
* * },
* * PerformanceEntry {
* * name: 'meow',
* * entryType: 'mark',
* * startTime: 81.860064,
* * duration: 0
* * }
* * ]
*
* observer.disconnect();
* });
* obs.observe({ type: 'mark' });
*
* performance.mark('test');
* performance.mark('meow');
* ```
* @since v8.5.0
*/
getEntries(): PerformanceEntry[];
/**
* Returns a list of `PerformanceEntry` objects in chronological order
* with respect to `performanceEntry.startTime` whose `performanceEntry.name` is
* equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`.
*
* ```js
* const {
* performance,
* PerformanceObserver
* } = require('perf_hooks');
*
* const obs = new PerformanceObserver((perfObserverList, observer) => {
* console.log(perfObserverList.getEntriesByName('meow'));
*
* * [
* * PerformanceEntry {
* * name: 'meow',
* * entryType: 'mark',
* * startTime: 98.545991,
* * duration: 0
* * }
* * ]
*
* console.log(perfObserverList.getEntriesByName('nope')); // []
*
* console.log(perfObserverList.getEntriesByName('test', 'mark'));
*
* * [
* * PerformanceEntry {
* * name: 'test',
* * entryType: 'mark',
* * startTime: 63.518931,
* * duration: 0
* * }
* * ]
*
* console.log(perfObserverList.getEntriesByName('test', 'measure')); // []
* observer.disconnect();
* });
* obs.observe({ entryTypes: ['mark', 'measure'] });
*
* performance.mark('test');
* performance.mark('meow');
* ```
* @since v8.5.0
*/
getEntriesByName(name: string, type?: EntryType): PerformanceEntry[];
/**
* Returns a list of `PerformanceEntry` objects in chronological order
* with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`.
*
* ```js
* const {
* performance,
* PerformanceObserver
* } = require('perf_hooks');
*
* const obs = new PerformanceObserver((perfObserverList, observer) => {
* console.log(perfObserverList.getEntriesByType('mark'));
*
* * [
* * PerformanceEntry {
* * name: 'test',
* * entryType: 'mark',
* * startTime: 55.897834,
* * duration: 0
* * },
* * PerformanceEntry {
* * name: 'meow',
* * entryType: 'mark',
* * startTime: 56.350146,
* * duration: 0
* * }
* * ]
*
* observer.disconnect();
* });
* obs.observe({ type: 'mark' });
*
* performance.mark('test');
* performance.mark('meow');
* ```
* @since v8.5.0
*/
getEntriesByType(type: EntryType): PerformanceEntry[];
}
type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void;
class PerformanceObserver extends AsyncResource {
constructor(callback: PerformanceObserverCallback);
/**
* Disconnects the `PerformanceObserver` instance from all notifications.
* @since v8.5.0
*/
disconnect(): void;
/**
* Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`:
*
* ```js
* const {
* performance,
* PerformanceObserver
* } = require('perf_hooks');
*
* const obs = new PerformanceObserver((list, observer) => {
* // Called three times synchronously. `list` contains one item.
* });
* obs.observe({ type: 'mark' });
*
* for (let n = 0; n < 3; n++)
* performance.mark(`test${n}`);
* ```
* @since v8.5.0
*/
observe(
options:
| {
entryTypes: ReadonlyArray<EntryType>;
buffered?: boolean | undefined;
}
| {
type: EntryType;
buffered?: boolean | undefined;
}
): void;
}
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;
}
const performance: Performance;
interface EventLoopMonitorOptions {
/**
* The sampling rate in milliseconds.
* Must be greater than zero.
* @default 10
*/
resolution?: number | undefined;
}
interface Histogram {
/**
* Returns a `Map` object detailing the accumulated percentile distribution.
* @since v11.10.0
*/
readonly percentiles: Map<number, number>;
/**
* 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 minimum recorded event loop delay.
* @since v11.10.0
*/
readonly min: number;
/**
* The maximum recorded event loop delay.
* @since v11.10.0
*/
readonly max: number;
/**
* The mean of the recorded event loop delays.
* @since v11.10.0
*/
readonly mean: number;
/**
* The standard deviation of the recorded event loop delays.
* @since v11.10.0
*/
readonly stddev: number;
/**
* Resets the collected histogram data.
* @since v11.10.0
*/
reset(): void;
/**
* 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;
}
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;
}
interface RecordableHistogram extends Histogram {
/**
* @since v15.9.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.
*
* ## Examples
* @since v15.9.0
*/
recordDelta(): void;
}
/**
* _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
* const { monitorEventLoopDelay } = require('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 CreateHistogramOptions {
/**
* The minimum recordable value. Must be an integer value greater than 0.
* @default 1
*/
min?: number | bigint | undefined;
/**
* The maximum recordable value. Must be an integer value greater than min.
* @default Number.MAX_SAFE_INTEGER
*/
max?: 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
*/
function createHistogram(options?: CreateHistogramOptions): RecordableHistogram;
}
declare module 'node:perf_hooks' {
export * from 'perf_hooks';
}

1481
CY_Auta_TS/automaty/node_modules/@types/node/process.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

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