Merge pull request #1 from DefinitelyTyped/master

Sync
This commit is contained in:
PopGoesTheWza
2018-12-31 18:12:02 +01:00
committed by GitHub
205 changed files with 4725 additions and 3008 deletions

View File

@@ -1512,6 +1512,12 @@
"sourceRepoURL": "https://github.com/mozilla/source-map",
"asOfVersion": "0.5.7"
},
{
"libraryName": "Spectacle",
"typingsPackageName": "spectacle",
"sourceRepoURL": "http://github.com/FormidableLabs/spectacle/",
"asOfVersion": "5.2.3"
},
{
"libraryName": "Spin.js",
"typingsPackageName": "spin.js",

View File

@@ -23,5 +23,6 @@
"devDependencies": {
"dtslint": "github:Microsoft/dtslint#production",
"types-publisher": "github:Microsoft/types-publisher#production"
}
},
"dependencies": {}
}

View File

@@ -1,30 +1,35 @@
import * as colors from 'ansi-colors';
import colors = require('ansi-colors');
let s: string;
colors.red('This is a red string!'); // $ExpectType string
colors.green('This is a red string!'); // $ExpectType string
colors.cyan('This is a cyan string!'); // $ExpectType string
colors.yellow('This is a yellow string!'); // $ExpectType string
s = colors.bgblack("hello");
s = colors.bgblue("hello");
s = colors.bgcyan("hello");
s = colors.bggreen("hello");
s = colors.bgmagenta("hello");
s = colors.bgred("hello");
s = colors.bgwhite("hello");
s = colors.bgyellow("hello");
s = colors.black("hello");
s = colors.blue("hello");
s = colors.bold("hello");
s = colors.cyan("hello");
s = colors.dim("hello");
s = colors.gray("hello");
s = colors.green("hello");
s = colors.grey("hello");
s = colors.hidden("hello");
s = colors.inverse("hello");
s = colors.italic("hello");
s = colors.magenta("hello");
s = colors.red("hello");
s = colors.reset("hello");
s = colors.strikethrough("hello");
s = colors.underline("hello");
s = colors.white("hello");
s = colors.yellow("hello");
colors.bold.red('this is a bold red message'); // $ExpectType string
colors.bold.yellow.italic('this is a bold yellow italicized message'); // $ExpectType string
colors.green.bold.underline('this is a bold green underlined message'); // $ExpectType string
colors.yellow(`foo ${colors.red.bold('red')} bar ${colors.cyan('cyan')} baz`); // $ExpectType string
colors.bold(`foo ${colors.red.dim('bar')} baz`); // $ExpectType string
colors.enabled = false;
colors.visible = false;
colors.hasAnsi(colors.blue('foo')); // $ExpectType boolean
colors.hasColor(colors.blue('foo')); // $ExpectType boolean
colors.unstyle(colors.blue.bold('foo bar baz')); // $ExpectType string
colors.stripColor(colors.blue.bold('foo bar baz')); // $ExpectType string
colors.none('foo'); // $ExpectType string
colors.clear('foo'); // $ExpectType string
colors.noop('foo'); // $ExpectType string
colors.define('reset', [0, 0], 'modifier');
colors.symbols.ballotCross; // $ExpectType string | undefined
colors.symbols.windows.ballotCross; // $ExpectError
colors.symbols.other.ballotCross; // $ExpectType string
colors.symbols.cross; // $ExpectType string
colors.symbols.windows.cross; // $ExpectType string
colors.symbols.other.cross; // $ExpectType string

View File

@@ -1,31 +1,111 @@
// Type definitions for ansi-colors 1.0
// Type definitions for ansi-colors 3.2
// Project: https://github.com/doowb/ansi-colors
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export function bgblack(s: string): string;
export function bgblue(s: string): string;
export function bgcyan(s: string): string;
export function bggreen(s: string): string;
export function bgmagenta(s: string): string;
export function bgred(s: string): string;
export function bgwhite(s: string): string;
export function bgyellow(s: string): string;
export function black(s: string): string;
export function blue(s: string): string;
export function bold(s: string): string;
export function cyan(s: string): string;
export function dim(s: string): string;
export function gray(s: string): string;
export function green(s: string): string;
export function grey(s: string): string;
export function hidden(s: string): string;
export function inverse(s: string): string;
export function italic(s: string): string;
export function magenta(s: string): string;
export function red(s: string): string;
export function reset(s: string): string;
export function strikethrough(s: string): string;
export function underline(s: string): string;
export function white(s: string): string;
export function yellow(s: string): string;
export = colors;
declare const colors: colors.Colors;
declare namespace colors {
type ColorFn = ((text: string) => string) & Colors;
interface Colors {
enabled: boolean;
visible: boolean;
reset: ColorFn;
bold: ColorFn;
dim: ColorFn;
italic: ColorFn;
underline: ColorFn;
inverse: ColorFn;
hidden: ColorFn;
strikethrough: ColorFn;
black: ColorFn;
red: ColorFn;
green: ColorFn;
yellow: ColorFn;
blue: ColorFn;
magenta: ColorFn;
cyan: ColorFn;
white: ColorFn;
gray: ColorFn;
grey: ColorFn;
bgBlack: ColorFn;
bgRed: ColorFn;
bgGreen: ColorFn;
bgYellow: ColorFn;
bgBlue: ColorFn;
bgMagenta: ColorFn;
bgCyan: ColorFn;
bgWhite: ColorFn;
blackBright: ColorFn;
redBright: ColorFn;
greenBright: ColorFn;
yellowBright: ColorFn;
blueBright: ColorFn;
magentaBright: ColorFn;
cyanBright: ColorFn;
whiteBright: ColorFn;
bgBlackBright: ColorFn;
bgRedBright: ColorFn;
bgGreenBright: ColorFn;
bgYellowBright: ColorFn;
bgBlueBright: ColorFn;
bgMagentaBright: ColorFn;
bgCyanBright: ColorFn;
bgWhiteBright: ColorFn;
hasColor(text: string): boolean;
hasAnsi(text: string): boolean;
unstyle(text: string): string;
stripColor(text: string): string;
none(text: string): string;
clear(text: string): string;
noop(text: string): string;
symbols: Symbols & {
windows: WindowsSymbols;
other: OtherPlatformsSymbols;
};
define(
name: string,
codes: [number, number],
type: 'modifier' | 'color' | 'bg' | 'bright' | 'bgBright'
): void;
}
interface WindowsSymbols {
bullet: string;
check: string;
cross: string;
ellipsis: string;
heart: string;
info: string;
line: string;
middot: string;
minus: string;
plus: string;
question: string;
questionSmall: string;
pointer: string;
pointerSmall: string;
warning: string;
}
interface ExtendedSymbols {
ballotCross: string;
questionFull: string;
}
type Symbols = WindowsSymbols & Partial<ExtendedSymbols>;
type OtherPlatformsSymbols = WindowsSymbols & ExtendedSymbols;
}

View File

@@ -20,4 +20,4 @@
"index.d.ts",
"ansi-colors-tests.ts"
]
}
}

View File

@@ -0,0 +1,30 @@
import * as colors from 'ansi-colors';
let s: string;
s = colors.bgblack("hello");
s = colors.bgblue("hello");
s = colors.bgcyan("hello");
s = colors.bggreen("hello");
s = colors.bgmagenta("hello");
s = colors.bgred("hello");
s = colors.bgwhite("hello");
s = colors.bgyellow("hello");
s = colors.black("hello");
s = colors.blue("hello");
s = colors.bold("hello");
s = colors.cyan("hello");
s = colors.dim("hello");
s = colors.gray("hello");
s = colors.green("hello");
s = colors.grey("hello");
s = colors.hidden("hello");
s = colors.inverse("hello");
s = colors.italic("hello");
s = colors.magenta("hello");
s = colors.red("hello");
s = colors.reset("hello");
s = colors.strikethrough("hello");
s = colors.underline("hello");
s = colors.white("hello");
s = colors.yellow("hello");

31
types/ansi-colors/v1/index.d.ts vendored Normal file
View File

@@ -0,0 +1,31 @@
// Type definitions for ansi-colors 1.0
// Project: https://github.com/doowb/ansi-colors
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export function bgblack(s: string): string;
export function bgblue(s: string): string;
export function bgcyan(s: string): string;
export function bggreen(s: string): string;
export function bgmagenta(s: string): string;
export function bgred(s: string): string;
export function bgwhite(s: string): string;
export function bgyellow(s: string): string;
export function black(s: string): string;
export function blue(s: string): string;
export function bold(s: string): string;
export function cyan(s: string): string;
export function dim(s: string): string;
export function gray(s: string): string;
export function green(s: string): string;
export function grey(s: string): string;
export function hidden(s: string): string;
export function inverse(s: string): string;
export function italic(s: string): string;
export function magenta(s: string): string;
export function red(s: string): string;
export function reset(s: string): string;
export function strikethrough(s: string): string;
export function underline(s: string): string;
export function white(s: string): string;
export function yellow(s: string): string;

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"paths": {
"ansi-colors": [
"ansi-colors/v1"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"ansi-colors-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -0,0 +1,8 @@
import diff = require('arr-diff');
const a = ['a', 'b', 'c', 'd'];
const b = [1, 2];
diff(['a']); // $ExpectType string[]
diff(['a'], [1]); // $ExpectType string[]
diff([1], ['a']); // $ExpectType number[]

8
types/arr-diff/index.d.ts vendored Normal file
View File

@@ -0,0 +1,8 @@
// Type definitions for arr-diff 4.0
// Project: https://github.com/jonschlinkert/arr-diff
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = arrDiff;
declare function arrDiff<T>(first: T[], ...args: any[][]): T[];

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"arr-diff-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -0,0 +1,3 @@
import extensions = require('binaryextensions');
extensions; // $ExpectType string[]

8
types/binaryextensions/index.d.ts vendored Normal file
View File

@@ -0,0 +1,8 @@
// Type definitions for binaryextensions 2.1
// Project: https://github.com/bevry/binaryextensions
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = extensions;
declare const extensions: string[];

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"binaryextensions-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -52,6 +52,7 @@ $("#carousel").carousel({
slide: false,
pause: "hover",
wrap: true,
touch: false,
});
$("#carousel").carousel({
@@ -245,6 +246,26 @@ $("a[data-toggle=\"list\"]").on("shown.bs.tab", (e) => {
const previousActiveTab: HTMLElement = e.relatedTarget;
});
// --------------------------------------------------------------------------------------
// Toast
// --------------------------------------------------------------------------------------
// $ExpectType JQuery<HTMLElement>
$("#toast").toast();
// $ExpectType JQuery<HTMLElement>
$("#toast").toast("show");
$("#toast").on("shown.bs.toast", () => {});
$("#toast").toast({
animation: false,
autohide: false,
delay: 100,
});
$("#toast").toast({});
// --------------------------------------------------------------------------------------
// Tooltip
// --------------------------------------------------------------------------------------

View File

@@ -1,4 +1,4 @@
// Type definitions for Bootstrap 4.1
// Type definitions for Bootstrap 4.2
// Project: https://github.com/twbs/bootstrap/
// Definitions by: denisname <https://github.com/denisname>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -64,9 +64,10 @@ export interface CarouselOption {
slide?: "next" | "prev" | false;
/**
* If set to "hover", pauses the cycling of the carousel on mouseenter and resumes the cycling of the carousel on mouseleave.
* If set to "hover", pauses the cycling of the carousel on `mouseenter` and resumes the cycling of the carousel on `mouseleave`.
* If set to false, hovering over the carousel won't pause it.
* On touch-enabled devices, when set to "hover", cycling will pause on touchend (once the user finished interacting with the carousel)
*
* On touch-enabled devices, when set to "hover", cycling will pause on `touchend` (once the user finished interacting with the carousel)
* for two intervals, before automatically resuming. Note that this is in addition to the above mouse behavior.
*
* @default "hover"
@@ -79,6 +80,13 @@ export interface CarouselOption {
* @default true
*/
wrap?: boolean;
/**
* Whether the carousel should support left/right swipe interactions on touchscreen devices.
*
* @default true
*/
touch?: boolean;
}
export interface CollapseOption {
@@ -210,6 +218,29 @@ export interface ScrollspyOption {
target?: string | Element;
}
export interface ToastOption {
/**
* Apply a CSS fade transition to the toast.
*
* @default true
*/
animation?: boolean;
/**
* Auto hide the toast.
*
* @default true
*/
autohide?: boolean;
/**
* Delay hiding the toast in millisecond.
*
* @default 500
*/
delay?: number;
}
export interface TooltipOption {
/**
* Apply a CSS fade transition to the tooltip or popover.
@@ -401,6 +432,7 @@ export type ModalEvent = "show.bs.modal" | "shown.bs.modal" | "hide.bs.modal" |
export type PopoverEvent = "show.bs.popover" | "shown.bs.popover" | "hide.bs.popover" | "hidden.bs.popover" | "inserted.bs.popover";
export type ScrollspyEvent = "activate.bs.scrollspy";
export type TapEvent = "show.bs.tab" | "shown.bs.tab" | "hide.bs.tab" | "hidden.bs.tab";
export type ToastEvent = "show.bs.toast" | "shown.bs.toast" | "hide.bs.toast" | "hidden.bs.toast";
export type TooltipEvent = "show.bs.tooltip" | "shown.bs.tooltip" | "hide.bs.tooltip" | "hidden.bs.tooltip" | "inserted.bs.tooltip";
// --------------------------------------------------------------------------------------
@@ -538,6 +570,20 @@ $('[data-spy="scroll"]').each(function () {
*/
tab(action: "show" | "dispose"): this;
/**
* Call a method on the toast element:
* * `show` Reveals an element's toast. You have to manually call this method, instead your toast won't show.
* * `hide` Hides an element's toast. You have to manually call this method if you made `autohide` to false.
* * `dispose` Hides an element's toast. Your toast will remain on the DOM but won't show anymore.
*
* Returns to the caller before the toast has actually been shown or hidden (i.e. before the `shown.bs.toast` or `hidden.bs.toast` event occurs).
*/
toast(action: "show" | "hide" | "dispose"): this;
/**
* Attaches a toast handler to an element collection.
*/
toast(options?: ToastOption): this;
/**
* Call a method on the tooltip element:
* * `show` Reveals an element's tooltip.
@@ -564,7 +610,7 @@ $('[data-spy="scroll"]').each(function () {
on(events: ModalEvent, handler: JQuery.EventHandlerBase<TElement, ModalEventHandler<TElement>>): this;
on(events: TapEvent, handler: JQuery.EventHandlerBase<TElement, TapEventHandler<TElement>>): this;
on(
events: AlertEvent | CollapseEvent | PopoverEvent | ScrollspyEvent | TooltipEvent,
events: AlertEvent | CollapseEvent | PopoverEvent | ScrollspyEvent | ToastEvent | TooltipEvent,
handler: JQuery.EventHandler<TElement>
): this;
}

View File

@@ -0,0 +1,11 @@
import crc32 = require('buffer-crc32');
const buf = new Buffer([0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00]);
crc32(buf); // $ExpectType Buffer
crc32('自動販売機'); // $ExpectType Buffer
crc32.signed(buf); // $ExpectType number
crc32.unsigned(buf); // $ExpectType number
const partialCrc = crc32('hey');
crc32(' ', partialCrc); // $ExpectType Buffer

15
types/buffer-crc32/index.d.ts vendored Normal file
View File

@@ -0,0 +1,15 @@
// Type definitions for buffer-crc32 0.2
// Project: https://github.com/brianloveswords/buffer-crc32
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
export = crc32;
declare function crc32(input: string | Buffer, partialCrc?: Buffer): Buffer;
declare namespace crc32 {
function signed(buffer: Buffer): number;
function unsigned(buffer: Buffer): number;
}

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"buffer-crc32-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -4576,7 +4576,10 @@ declare namespace chrome.omnibox {
description: string;
}
export interface OmniboxInputEnteredEvent extends chrome.events.Event<(text: string) => void> { }
/** The window disposition for the omnibox query. This is the recommended context to display results. */
export type OnInputEnteredDisposition = 'currentTab' | 'newForegroundTab' | 'newBackgroundTab';
export interface OmniboxInputEnteredEvent extends chrome.events.Event<(text: string, disposition: OnInputEnteredDisposition) => void> { }
export interface OmniboxInputChangedEvent extends chrome.events.Event<(text: string, suggest: (suggestResults: SuggestResult[]) => void) => void> { }
@@ -4584,6 +4587,8 @@ declare namespace chrome.omnibox {
export interface OmniboxInputCancelledEvent extends chrome.events.Event<() => void> { }
export interface OmniboxSuggestionDeletedEvent extends chrome.events.Event<(text: string) => void> { }
/**
* Sets the description and styling for the default suggestion. The default suggestion is the text that is displayed in the first suggestion row underneath the URL bar.
* @param suggestion A partial SuggestResult object, without the 'content' parameter.
@@ -4598,6 +4603,11 @@ declare namespace chrome.omnibox {
export var onInputStarted: OmniboxInputStartedEvent;
/** User has ended the keyword input session without accepting the input. */
export var onInputCancelled: OmniboxInputCancelledEvent;
/**
* User has deleted a suggested result
* @since Chrome 63.
*/
export var onDeleteSuggestion: OmniboxSuggestionDeletedEvent;
}
////////////////////

View File

@@ -0,0 +1,17 @@
import cliBoxes = require('cli-boxes');
cliBoxes.single; // $ExpectType BoxDefinition
cliBoxes.double; // $ExpectType BoxDefinition
cliBoxes.round; // $ExpectType BoxDefinition
cliBoxes['single-double']; // $ExpectType BoxDefinition
cliBoxes['double-single']; // $ExpectType BoxDefinition
cliBoxes.classic; // $ExpectType BoxDefinition
const single = cliBoxes.single;
single.bottomLeft; // $ExpectType string
single.bottomRight; // $ExpectType string
single.horizontal; // $ExpectType string
single.topLeft; // $ExpectType string
single.topRight; // $ExpectType string
single.vertical; // $ExpectType string

23
types/cli-boxes/index.d.ts vendored Normal file
View File

@@ -0,0 +1,23 @@
// Type definitions for cli-boxes 1.0
// Project: https://github.com/sindresorhus/cli-boxes
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export = boxes;
declare const boxes: boxes.Boxes;
declare namespace boxes {
type BoxNames = 'single' | 'double' | 'round' | 'single-double' | 'double-single' | 'classic';
type Boxes = Record<BoxNames, BoxDefinition>;
interface BoxDefinition {
topLeft: string;
topRight: string;
bottomRight: string;
bottomLeft: string;
vertical: string;
horizontal: string;
}
}

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"cli-boxes-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -0,0 +1 @@
import 'cypress-axe';

12
types/cypress-axe/index.d.ts vendored Normal file
View File

@@ -0,0 +1,12 @@
// Type definitions for cypress-axe 0.3
// Project: https://github.com/avanslaars/cypress-axe#readme
// Definitions by: Justin Hall <https://github.com/wKovacs64>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
declare namespace Cypress {
interface Chainable<Subject = any> {
injectAxe(): void;
checkA11y(): void;
}
}

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"cypress-axe-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -24,6 +24,12 @@ declare namespace download {
* Proxy endpoint
*/
proxy?: string;
/**
* Request Headers
*/
headers?: {
[name: string]: string;
};
}
}

View File

@@ -2126,7 +2126,7 @@ export namespace Location {
function getProviderStatusAsync(): Promise<ProviderStatus>;
function getHeadingAsync(): Promise<HeadingStatus>;
function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription;
function geocodeAsync(address: string): Promise<Coords>;
function geocodeAsync(address: string): Promise<Coords[]>;
function reverseGeocodeAsync(location: LocationProps): Promise<GeocodeData[]>;
function setApiKey(key: string): void;
}

View File

@@ -120,6 +120,7 @@ const myMatcher: fetchMock.MockMatcherFunction = (
fetchMock.flush().then(resolved => resolved.forEach(console.log));
fetchMock.flush().catch(r => r);
fetchMock.flush(true).catch(r => r);
fetchMock.get("http://test.com", {
body: 'abc',

View File

@@ -8,6 +8,7 @@
// Quentin Bouygues <https://github.com/quentinbouygues>
// Fumiaki Matsushima <https://github.com/mtsmfm>
// Colin Doig <https://github.com/captain-igloo>
// Felix Chen <https://github.com/ChenNima>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -441,8 +442,10 @@ declare namespace fetchMock {
/**
* Returns a promise that resolves once all fetches handled by fetch-mock
* have resolved.
* @param [waitForBody] Wait for all body parsing methods(res.json(),
* res.text(), etc.) to resolve too.
*/
flush(): Promise<MockResponse[]>;
flush(waitForBody?: boolean): Promise<MockResponse[]>;
/**
* Returns an array of all calls to fetch matching the given filters.

View File

@@ -0,0 +1,19 @@
import findCacheDir = require('find-cache-dir');
findCacheDir({ name: 'unicorns' }); // $ExpectType string | null
findCacheDir({ name: 'unicorns', files: 'foo' }); // $ExpectType string | null
findCacheDir({ name: 'unicorns', files: ['foo', 'bar'] }); // $ExpectType string | null
findCacheDir({ name: 'unicorns', cwd: 'foo' }); // $ExpectType string | null
findCacheDir({ name: 'unicorns', create: true }); // $ExpectType string | null
findCacheDir({ name: 'unicorns', thunk: false }); // $ExpectType string | null
findCacheDir({}); // $ExpectError
findCacheDir(); // $ExpectError
const thunk = findCacheDir({ name: 'unicorns', thunk: true });
thunk; // $ExpectType ((...pathParts: string[]) => string) | null
if (thunk) {
thunk(); // $ExpectType string
thunk('bar.js'); // $ExpectType string
thunk('baz', 'quz.js'); // $ExpectType string
}

57
types/find-cache-dir/index.d.ts vendored Normal file
View File

@@ -0,0 +1,57 @@
// Type definitions for find-cache-dir 2.0
// Project: https://github.com/avajs/find-cache-dir#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = findCacheDir;
/**
* Finds the cache directory using the supplied options. The algorithm tries to find a `package.json` file,
* searching every parent directory of the `cwd` specified (or implied from other options).
* @param options
* @returns A string containing the absolute path to the cache directory, or null if package.json was never found.
*/
declare function findCacheDir(
options: findCacheDir.OptionsWithThunk
): ((...pathParts: string[]) => string) | null;
declare function findCacheDir(options: findCacheDir.Options): string | null;
declare namespace findCacheDir {
interface Options {
/**
* Should be the same as your project name in `package.json`.
*/
name: string;
/**
* An array of files that will be searched for a common parent directory.
* This common parent directory will be used in lieu of the `cwd` option below.
*/
files?: string | string[];
/**
* Directory to start searching for a `package.json` from.
*/
cwd?: string;
/**
* If `true`, the directory will be created synchronously before returning.
* @default false
*/
create?: boolean;
/**
* If `true`, this modifies the return type to be a function that is a thunk for `path.join(theFoundCacheDirectory)`.
* @default false
*/
thunk?: boolean;
}
interface OptionsWithThunk extends Options {
/**
* If `true`, this modifies the return type to be a function that is a thunk for `path.join(theFoundCacheDirectory)`.
* @default false
*/
thunk: true;
}
}

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"find-cache-dir-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -457,7 +457,7 @@ interface FlickityOptions {
*
* default: disabled
*/
asNavFor?: string;
asNavFor?: string | HTMLElement;
/**
* The number of pixels a mouse or touch has to move before dragging begins. Increase dragThreshold to allow for more wiggle room for vertical page scrolling on touch devices.

View File

@@ -0,0 +1,12 @@
import getFuncName = require('get-func-name');
const unknownFunction = function myCoolFunction(word: string) {
return word + 'is cool';
};
const anonymousFunction = (() => {
return () => {};
})();
getFuncName(unknownFunction); // $ExpectType string
getFuncName(anonymousFunction); // $ExpectType string

8
types/get-func-name/index.d.ts vendored Normal file
View File

@@ -0,0 +1,8 @@
// Type definitions for get-func-name 2.0
// Project: https://github.com/chaijs/get-func-name#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = getFuncName;
declare function getFuncName(fn: Function): string; // tslint:disable-line:ban-types

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"get-func-name-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -1,14 +1,18 @@
import gitBranch = require('git-branch');
gitBranch()
.then((name) => {});
.then((name) => {
name; // $ExpectType string
});
gitBranch('cwd')
.then((name) => {});
.then((name) => {
name; // $ExpectType string
});
gitBranch.sync();
gitBranch.sync('cwd');
gitBranch.sync(); // $ExpectType string
gitBranch.sync('cwd'); // $ExpectType string
gitBranch((err, name) => {});
gitBranch((err, name) => {}); // $ExpectType void
gitBranch('cwd', (err, name) => {});
gitBranch('cwd', (err, name) => {}); // $ExpectType void

View File

@@ -8,7 +8,7 @@ export = GitBranch;
declare function GitBranch(cwd?: string): Promise<string>;
declare function GitBranch(cwd?: string, callback?: (err: null | string, name: string) => void): void;
declare function GitBranch(callback?: (err: null | string, name: string) => void): void;
declare function GitBranch(callback: (err: null | string, name: string) => void): void;
declare namespace GitBranch {
function sync(cwd?: string): string;

View File

@@ -89,6 +89,9 @@ export class Polyline extends React.Component<any, any> {
export class Circle extends React.Component<any, any> {
}
export class HeatMap extends React.Component<any, any> {
}
export interface InfoWindowProps extends Partial<google.maps.InfoWindowOptions> {
google: typeof google;
map: google.maps.Map;

View File

@@ -16,6 +16,7 @@
// Brad Zacher <https://github.com/bradzacher>
// Curtis Layne <https://github.com/clayne11>
// Jonathan Cardoso <https://github.com/JCMais>
// Pavel Lang <https://github.com/langpavel>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6

View File

@@ -1,19 +1,30 @@
import { ASTNode } from "./ast";
import {
ASTNode,
DefinitionNode,
ExecutableDefinitionNode,
SelectionNode,
ValueNode,
TypeNode,
TypeSystemDefinitionNode,
TypeDefinitionNode,
TypeSystemExtensionNode,
TypeExtensionNode,
} from "./ast";
export function isDefinitionNode(node: ASTNode): boolean;
export function isDefinitionNode(node: ASTNode): node is DefinitionNode;
export function isExecutableDefinitionNode(node: ASTNode): boolean;
export function isExecutableDefinitionNode(node: ASTNode): node is ExecutableDefinitionNode;
export function isSelectionNode(node: ASTNode): boolean;
export function isSelectionNode(node: ASTNode): node is SelectionNode;
export function isValueNode(node: ASTNode): boolean;
export function isValueNode(node: ASTNode): node is ValueNode;
export function isTypeNode(node: ASTNode): boolean;
export function isTypeNode(node: ASTNode): node is TypeNode;
export function isTypeSystemDefinitionNode(node: ASTNode): boolean;
export function isTypeSystemDefinitionNode(node: ASTNode): node is TypeSystemDefinitionNode;
export function isTypeDefinitionNode(node: ASTNode): boolean;
export function isTypeDefinitionNode(node: ASTNode): node is TypeDefinitionNode;
export function isTypeSystemExtensionNode(node: ASTNode): boolean;
export function isTypeSystemExtensionNode(node: ASTNode): node is TypeSystemExtensionNode;
export function isTypeExtensionNode(node: ASTNode): boolean;
export function isTypeExtensionNode(node: ASTNode): node is TypeExtensionNode;

View File

@@ -968,6 +968,11 @@ declare global {
* @param callback - gets called when a free port is found
*/
getPort(port: number, callback: (port: number) => void): void;
/**
* Helper function that looks for first free TCP port starting with the given one.
* @param port - The port to start with
*/
getPortAsync(port: number): Promise<number>;
/** Stops the adapter. Note: Is not always defined. */
stop?: () => void;
@@ -978,16 +983,52 @@ declare global {
/** Validates username and password */
checkPassword(user: string, password: string, callback: (result: boolean) => void): void;
checkPassword(user: string, password: string, options: unknown, callback: (result: boolean) => void): void;
/** Validates username and password */
checkPasswordAsync(user: string, password: string, options?: unknown): Promise<boolean>;
/** Sets a new password for the given user */
setPassword(user: string, password: string, options?: unknown, callback?: (err?: any) => void): void;
setPassword(user: string, password: string, callback?: (err?: any) => void): void;
setPassword(user: string, password: string, options: unknown, callback?: (err?: any) => void): void;
/** Sets a new password for the given user */
setPasswordAsync(user: string, password: string, options?: unknown): Promise<void>;
/** <INTERNAL> Checks if a user exists and is in the given group. */
checkGroup(user: string, group: string, callback: (result: boolean) => void): void;
checkGroup(user: string, group: string, options: unknown, callback: (result: boolean) => void): void;
/** <INTERNAL> Checks if a user exists and is in the given group. */
checkGroupAsync(user: string, group: string, options?: unknown): Promise<boolean>;
/** <INTERNAL> Determines the users permissions */
calculatePermissions(user: string, commandsPermissions: CommandsPermissions, callback: (result: PermissionSet) => void): void;
calculatePermissions(user: string, commandsPermissions: CommandsPermissions, options: unknown, callback: (result: PermissionSet) => void): void;
/** <INTERNAL> Determines the users permissions */
calculatePermissionsAsync(user: string, commandsPermissions: CommandsPermissions, options?: unknown): Promise<PermissionSet>;
/** Returns SSL certificates by name (private key, public cert and chained certificate) for creation of HTTPS servers */
getCertificates(publicName: string, privateName: string, chainedName: string, callback: (err: string | null, certs?: Certificates, useLetsEncryptCert?: boolean) => void): void;
// TODO: getCertificates cannot be represented with promises right now
/**
* Terminates the adapter execution but does not disable the adapter
* @param reason (optional) A message to print into the log prior to termination
*/
terminate(reason?: string): never;
/** Restarts the adapter */
restart(): never;
/**
* Disables and stops the adapter instance.
* It is recommended that you leave the current method (e.g. by using `return`) after calling this.
*/
disable(): void;
/**
* Updates the adapter config with new values. Only a subset of the configuration has to be provided,
* since merging with the existing config is done automatically.
*
* After updating the configuration, the adapter is automatically restarted. It is recommended that you
* leave the current method (e.g. by using `return`) after calling this.
*
* @param newConfig The new config values to be stored
*/
updateConfig(newConfig: Partial<AdapterConfig>): void;
/**
* Sends a message to a specific instance or all instances of some specific adapter.
@@ -999,12 +1040,26 @@ declare global {
*/
sendTo(instanceName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void;
sendTo(instanceName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void;
/**
* Sends a message to a specific instance or all instances of some specific adapter.
* @param instanceName The instance to send this message to.
* If the ID of an instance is given (e.g. "admin.0"), only this instance will receive the message.
* If the name of an adapter is given (e.g. "admin"), all instances of this adapter will receive it.
* @param command (optional) Command name of the target instance. Default: "send"
* @param message The message (e.g. params) to send.
*/
sendToAsync(instanceName: string, message: string | object): Promise<any>;
sendToAsync(instanceName: string, command: string, message: string | object): Promise<any>;
/**
* Sends a message to a specific host or all hosts.
*/
sendToHost(hostName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void;
sendToHost(hostName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void;
/**
* Sends a message to a specific host or all hosts.
*/
sendToHostAsync(hostName: string, message: string | object): Promise<any>;
sendToHostAsync(hostName: string, command: string, message: string | object): Promise<any>;
/** Convert ID to {device: D, channel: C, state: S} */
idToDCS(id: string): {
@@ -1019,109 +1074,175 @@ declare global {
/** Reads an object from the object db */
getObject(id: string, callback: GetObjectCallback): void;
getObject(id: string, options: unknown, callback: GetObjectCallback): void;
/** Reads an object from the object db */
getObjectAsync(id: string, options?: unknown): Promise<CallbackReturnTypeOf<GetObjectCallback>>;
/** Creates or overwrites an object in the object db */
setObject(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void;
setObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void;
/** Creates or overwrites an object in the object db */
setObjectAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
/** Creates an object in the object db. Existing objects are not overwritten. */
setObjectNotExists(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void;
setObjectNotExists(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void;
/** Creates an object in the object db. Existing objects are not overwritten. */
setObjectNotExistsAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
/** Get all states, channels and devices of this adapter */
getAdapterObjects(callback: (objects: Record<string, ioBroker.Object>) => void): void;
/** Get all states, channels and devices of this adapter */
getAdapterObjectsAsync(): Promise<Record<string, ioBroker.Object>>;
/** Extend an object and create it if it might not exist */
extendObject(id: string, objPart: PartialObject, callback?: SetObjectCallback): void;
extendObject(id: string, objPart: PartialObject, options: unknown, callback?: SetObjectCallback): void;
/** Extend an object and create it if it might not exist */
extendObjectAsync(id: string, objPart: PartialObject, options?: unknown): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
/**
* Deletes an object from the object db
* @param id - The id of the object without namespace
*/
delObject(id: string, callback?: ErrorCallback): void;
delObject(id: string, options: unknown, callback?: ErrorCallback): void;
/**
* Deletes an object from the object db
* @param id - The id of the object without namespace
*/
delObjectAsync(id: string, options?: unknown): Promise<void>;
// ==============================
// foreign objects
// tslint:disable:unified-signatures
/** Reads an object (which might not belong to this adapter) from the object db */
getForeignObject(id: string, callback: GetObjectCallback): void;
getForeignObject(id: string, options: unknown, callback: GetObjectCallback): void;
/** Reads an object (which might not belong to this adapter) from the object db */
getForeignObjectAsync(id: string, options?: unknown): Promise<CallbackReturnTypeOf<GetObjectCallback>>;
/** Get foreign objects by pattern, by specific type and resolve their enums. */
// tslint:disable:unified-signatures
getForeignObjects(pattern: string, callback: GetObjectsCallback): void;
getForeignObjects(pattern: string, options: unknown, callback: GetObjectsCallback): void;
getForeignObjects(pattern: string, type: ObjectType, callback: GetObjectsCallback): void;
getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, callback: GetObjectsCallback): void;
getForeignObjects(pattern: string, type: ObjectType, options: unknown, callback: GetObjectsCallback): void;
getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, options: unknown, callback: GetObjectsCallback): void;
// tslint:enable:unified-signatures
/** Get foreign objects by pattern, by specific type and resolve their enums. */
getForeignObjectsAsync(pattern: string, options?: unknown): Promise<CallbackReturnTypeOf<GetObjectCallback>>;
getForeignObjectsAsync(pattern: string, type: ObjectType, options?: unknown): Promise<CallbackReturnTypeOf<GetObjectCallback>>;
getForeignObjectsAsync(pattern: string, type: ObjectType, enums: EnumList, options?: unknown): Promise<CallbackReturnTypeOf<GetObjectCallback>>;
/** Creates or overwrites an object (which might not belong to this adapter) in the object db */
setForeignObject(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void;
setForeignObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void;
/** Creates or overwrites an object (which might not belong to this adapter) in the object db */
setForeignObjectAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
/** Creates an object (which might not belong to this adapter) in the object db. Existing objects are not overwritten. */
setForeignObjectNotExists(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void;
setForeignObjectNotExists(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void;
/** Creates an object (which might not belong to this adapter) in the object db. Existing objects are not overwritten. */
setForeignObjectNotExistsAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
/** Extend an object (which might not belong to this adapter) and create it if it might not exist */
extendForeignObject(id: string, objPart: PartialObject, callback?: SetObjectCallback): void;
extendForeignObject(id: string, objPart: PartialObject, options: unknown, callback?: SetObjectCallback): void;
// tslint:enable:unified-signatures
/** Extend an object (which might not belong to this adapter) and create it if it might not exist */
extendForeignObjectAsync(id: string, objPart: PartialObject, options?: unknown): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
/**
* Finds an object by its ID or name
* @param type - common.type of the state
*/
findForeignObject(idOrName: string, type: string, callback: FindObjectCallback): void;
findForeignObject(idOrName: string, type: string, options: unknown, callback: FindObjectCallback): void;
/**
* Finds an object by its ID or name
* @param type - common.type of the state
*/
findForeignObjectAsync(idOrName: string, type: string): Promise<{ id: string, name: string }>;
/**
* Deletes an object (which might not belong to this adapter) from the object db
* @param id - The id of the object including namespace
*/
delForeignObject(id: string, callback?: ErrorCallback): void;
delForeignObject(id: string, options: unknown, callback?: ErrorCallback): void;
/**
* Deletes an object (which might not belong to this adapter) from the object db
* @param id - The id of the object including namespace
*/
delForeignObjectAsync(id: string, options?: unknown): Promise<void>;
// ==============================
// states
// Multiple signatures help understanding what the parameters are about
// tslint:disable:unified-signatures
/** Writes a value into the states DB. */
// tslint:disable:unified-signatures
setState(id: string, state: string | number | boolean | State | Partial<State>, callback?: SetStateCallback): void;
setState(id: string, state: string | number | boolean | State | Partial<State>, ack: boolean, callback?: SetStateCallback): void;
setState(id: string, state: string | number | boolean | State | Partial<State>, options: unknown, callback?: SetStateCallback): void;
setState(id: string, state: string | number | boolean | State | Partial<State>, ack: boolean, options: unknown, callback?: SetStateCallback): void;
/** Writes a value into the states DB. */
setStateAsync(id: string, state: string | number | boolean | State | Partial<State>, ack?: boolean): Promise<CallbackReturnTypeOf<SetStateCallback>>;
setStateAsync(id: string, state: string | number | boolean | State | Partial<State>, options?: unknown): Promise<CallbackReturnTypeOf<SetStateCallback>>;
setStateAsync(id: string, state: string | number | boolean | State | Partial<State>, ack: boolean, options: unknown): Promise<CallbackReturnTypeOf<SetStateCallback>>;
/** Writes a value into the states DB only if it has changed. */
setStateChanged(id: string, state: string | number | boolean | State | Partial<State>, callback?: SetStateChangedCallback): void;
setStateChanged(id: string, state: string | number | boolean | State | Partial<State>, ack: boolean, callback?: SetStateChangedCallback): void;
setStateChanged(id: string, state: string | number | boolean | State | Partial<State>, options: unknown, callback?: SetStateChangedCallback): void;
setStateChanged(id: string, state: string | number | boolean | State | Partial<State>, ack: boolean, options: unknown, callback?: SetStateChangedCallback): void;
/** Writes a value into the states DB only if it has changed. */
setStateChangedAsync(id: string, state: string | number | boolean | State | Partial<State>, ack?: boolean): Promise<CallbackReturnTypeOf<SetStateChangedCallback>>;
setStateChangedAsync(id: string, state: string | number | boolean | State | Partial<State>, options?: unknown): Promise<CallbackReturnTypeOf<SetStateChangedCallback>>;
setStateChangedAsync(id: string, state: string | number | boolean | State | Partial<State>, ack: boolean, options: unknown): Promise<CallbackReturnTypeOf<SetStateChangedCallback>>;
/** Writes a value (which might not belong to this adapter) into the states DB. */
setForeignState(id: string, state: string | number | boolean | State | Partial<State>, callback?: SetStateCallback): void;
setForeignState(id: string, state: string | number | boolean | State | Partial<State>, ack: boolean, callback?: SetStateCallback): void;
setForeignState(id: string, state: string | number | boolean | State | Partial<State>, options: unknown, callback?: SetStateCallback): void;
setForeignState(id: string, state: string | number | boolean | State | Partial<State>, ack: boolean, options: unknown, callback?: SetStateCallback): void;
/** Writes a value (which might not belong to this adapter) into the states DB. */
setForeignStateAsync(id: string, state: string | number | boolean | State | Partial<State>, ack?: boolean): Promise<CallbackReturnTypeOf<SetStateCallback>>;
setForeignStateAsync(id: string, state: string | number | boolean | State | Partial<State>, options?: unknown): Promise<CallbackReturnTypeOf<SetStateCallback>>;
setForeignStateAsync(id: string, state: string | number | boolean | State | Partial<State>, ack: boolean, options: unknown): Promise<CallbackReturnTypeOf<SetStateCallback>>;
/** Writes a value (which might not belong to this adapter) into the states DB only if it has changed. */
setForeignStateChanged(id: string, state: string | number | boolean | State | Partial<State>, callback?: SetStateChangedCallback): void;
setForeignStateChanged(id: string, state: string | number | boolean | State | Partial<State>, ack: boolean, callback?: SetStateChangedCallback): void;
setForeignStateChanged(id: string, state: string | number | boolean | State | Partial<State>, options: unknown, callback?: SetStateChangedCallback): void;
setForeignStateChanged(id: string, state: string | number | boolean | State | Partial<State>, ack: boolean, options: unknown, callback?: SetStateChangedCallback): void;
/** Writes a value (which might not belong to this adapter) into the states DB only if it has changed. */
setForeignStateChangedAsync(id: string, state: string | number | boolean | State | Partial<State>, ack?: boolean): Promise<CallbackReturnTypeOf<SetStateChangedCallback>>;
setForeignStateChangedAsync(id: string, state: string | number | boolean | State | Partial<State>, options?: unknown): Promise<CallbackReturnTypeOf<SetStateChangedCallback>>;
setForeignStateChangedAsync(id: string, state: string | number | boolean | State | Partial<State>, ack: boolean, options: unknown): Promise<CallbackReturnTypeOf<SetStateChangedCallback>>;
// tslint:enable:unified-signatures
/** Read a value from the states DB. */
getState(id: string, callback: GetStateCallback): void;
getState(id: string, options: unknown, callback: GetStateCallback): void;
/** Read a value from the states DB. */
getStateAsync(id: string, options?: unknown): Promise<CallbackReturnTypeOf<GetStateCallback>>;
/** Read a value (which might not belong to this adapter) from the states DB. */
getForeignState(id: string, callback: GetStateCallback): void;
getForeignState(id: string, options: unknown, callback: GetStateCallback): void;
/** Read a value (which might not belong to this adapter) from the states DB. */
getForeignStateAsync(id: string, options?: unknown): Promise<CallbackReturnTypeOf<GetStateCallback>>;
/** Read all states of this adapter which match the given pattern */
getStates(pattern: string, callback: GetStatesCallback): void;
getStates(pattern: string, options: unknown, callback: GetStatesCallback): void;
/** Read all states of this adapter which match the given pattern */
getStatesAsync(pattern: string, options?: unknown): Promise<CallbackReturnTypeOf<GetStatesCallback>>;
/** Read all states (which might not belong to this adapter) which match the given pattern */
getForeignStates(pattern: string, callback: GetStatesCallback): void;
getForeignStates(pattern: string, options: unknown, callback: GetStatesCallback): void;
/** Read all states (which might not belong to this adapter) which match the given pattern */
getForeignStatesAsync(pattern: string, options?: unknown): Promise<CallbackReturnTypeOf<GetStatesCallback>>;
/** Deletes a state from the states DB, but not the associated object. Consider using @link{deleteState} instead */
delState(id: string, callback?: ErrorCallback): void;
delState(id: string, options: unknown, callback?: ErrorCallback): void;
/** Deletes a state from the states DB, but not the associated object. Consider using @link{deleteState} instead */
delStateAsync(id: string, options?: unknown): Promise<void>;
/** Deletes a state from the states DB, but not the associated object */
delForeignState(id: string, callback?: ErrorCallback): void;
delForeignState(id: string, options: unknown, callback?: ErrorCallback): void;
/** Deletes a state from the states DB, but not the associated object */
delForeignStateAsync(id: string, options?: unknown): Promise<void>;
getHistory(id: string, options: GetHistoryOptions, callback: GetHistoryCallback): void;
// TODO: getHistoryAsync
// MISSING:
// pushFifo and similar https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4105
@@ -1138,6 +1259,13 @@ declare global {
*/
setBinaryState(id: string, binary: Buffer, callback: SetStateCallback): void;
setBinaryState(id: string, binary: Buffer, options: unknown, callback: SetStateCallback): void;
/**
* Writes a binary state into Redis
* @param id The id of the state
* @param binary The data to be written
* @param options (optional) Some internal options.
*/
setBinaryStateAsync(id: string, binary: Buffer, options?: unknown): Promise<CallbackReturnTypeOf<SetStateCallback>>;
/**
* Reads a binary state from Redis
* @param id The id of the state
@@ -1146,6 +1274,12 @@ declare global {
*/
getBinaryState(id: string, callback: GetBinaryStateCallback): void;
getBinaryState(id: string, options: unknown, callback: GetBinaryStateCallback): void;
/**
* Reads a binary state from Redis
* @param id The id of the state
* @param options (optional) Some internal options.
*/
getBinaryStateAsync(id: string, options?: unknown): Promise<CallbackReturnTypeOf<GetBinaryStateCallback>>;
// ==============================
// enums
@@ -1154,27 +1288,42 @@ declare global {
getEnum(callback: GetEnumCallback): void;
getEnum(name: string, callback: GetEnumCallback): void;
getEnum(name: string, options: unknown, callback: GetEnumCallback): void;
/** Returns the enum tree, filtered by the optional enum name */
getEnumAsync(name: string, options?: unknown): Promise<{ result: Record<string, any>, requestEnum: string }>;
/** Returns the enum tree, filtered by the optional enum name */
getEnums(callback: GetEnumsCallback): void;
getEnums(enumList: EnumList, callback: GetEnumsCallback): void;
getEnums(enumList: EnumList, options: unknown, callback: GetEnumsCallback): void;
/** Returns the enum tree, filtered by the optional enum name */
getEnumsAsync(enumList: EnumList, options?: unknown): Promise<CallbackReturnTypeOf<GetEnumsCallback>>;
addChannelToEnum(enumName: string, addTo: string, parentDevice: string, channelName: string, options?: unknown, callback?: ErrorCallback): void;
deleteChannelFromEnum(enumName: string, parentDevice: string, channelName: string, options?: unknown, callback?: ErrorCallback): void;
addChannelToEnum(enumName: string, addTo: string, parentDevice: string, channelName: string, callback?: ErrorCallback): void;
addChannelToEnum(enumName: string, addTo: string, parentDevice: string, channelName: string, options: unknown, callback?: ErrorCallback): void;
addChannelToEnumAsync(enumName: string, addTo: string, parentDevice: string, channelName: string, options?: unknown): Promise<void>;
addStateToEnum(enumName: string, addTo: string, parentDevice: string, parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void;
deleteStateFromEnum(enumName: string, parentDevice: string, parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void;
deleteChannelFromEnum(enumName: string, parentDevice: string, channelName: string, callback?: ErrorCallback): void;
deleteChannelFromEnum(enumName: string, parentDevice: string, channelName: string, options: unknown, callback?: ErrorCallback): void;
deleteChannelFromEnumAsync(enumName: string, parentDevice: string, channelName: string, options?: unknown): Promise<void>;
addStateToEnum(enumName: string, addTo: string, parentDevice: string, parentChannel: string, stateName: string, callback?: ErrorCallback): void;
addStateToEnum(enumName: string, addTo: string, parentDevice: string, parentChannel: string, stateName: string, options: unknown, callback?: ErrorCallback): void;
addStateToEnumAsync(enumName: string, addTo: string, parentDevice: string, parentChannel: string, stateName: string, options?: unknown): Promise<void>;
deleteStateFromEnum(enumName: string, parentDevice: string, parentChannel: string, stateName: string, callback?: ErrorCallback): void;
deleteStateFromEnum(enumName: string, parentDevice: string, parentChannel: string, stateName: string, options: unknown, callback?: ErrorCallback): void;
deleteStateFromEnumAsync(enumName: string, parentDevice: string, parentChannel: string, stateName: string, options?: unknown): Promise<void>;
// ==============================
// subscriptions
/** Subscribe to changes of objects in this instance */
subscribeObjects(pattern: string, options?: unknown): void;
subscribeObjects(pattern: string, options?: unknown, callback?: ErrorCallback): void;
/** Subscribe to changes of objects (which might not belong to this adapter) */
subscribeForeignObjects(pattern: string, options?: unknown): void;
subscribeForeignObjects(pattern: string, options?: unknown, callback?: ErrorCallback): void;
/** Unsubscribe from changes of objects in this instance */
unsubscribeObjects(pattern: string, options?: unknown): void;
unsubscribeObjects(pattern: string, options?: unknown, callback?: ErrorCallback): void;
/** Unsubscribe from changes of objects (which might not belong to this adapter) */
unsubscribeForeignObjects(pattern: string, options?: unknown): void;
unsubscribeForeignObjects(pattern: string, options?: unknown, callback?: ErrorCallback): void;
/** Subscribe to changes of states in this instance */
subscribeStates(pattern: string, options?: unknown, callback?: ErrorCallback): void;
@@ -1194,24 +1343,80 @@ declare global {
// ==============================
// devices and channels
// tslint:disable:unified-signatures
/** creates an object with type device */
createDevice(deviceName: string, common?: any, native?: any, options?: unknown, callback?: SetObjectCallback): void;
createDevice(deviceName: string, callback?: SetObjectCallback): void;
createDevice(deviceName: string, common: Partial<ioBroker.ObjectCommon>, callback?: SetObjectCallback): void;
createDevice(deviceName: string, common: Partial<ioBroker.ObjectCommon>, native: Record<string, any>, callback?: SetObjectCallback): void;
createDevice(deviceName: string, common: Partial<ioBroker.ObjectCommon>, native: Record<string, any>, options: unknown, callback?: SetObjectCallback): void;
/** creates an object with type device */
createDeviceAsync(deviceName: string, common?: Partial<ioBroker.ObjectCommon>): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
createDeviceAsync(deviceName: string, common: Partial<ioBroker.ObjectCommon>, native?: Record<string, any>): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
createDeviceAsync(deviceName: string, common: Partial<ioBroker.ObjectCommon>, native: Record<string, any>, options?: unknown): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
/** deletes a device, its channels and states */
deleteDevice(deviceName: string, options?: unknown, callback?: ErrorCallback): void;
/** gets the devices of this instance */
deleteDevice(deviceName: string, callback?: ErrorCallback): void;
deleteDevice(deviceName: string, options: unknown, callback?: ErrorCallback): void;
/** deletes a device, its channels and states */
deleteDeviceAsync(deviceName: string, options?: unknown): Promise<void>;
/** creates an object with type channel */
createChannel(parentDevice: string, channelName: string, roleOrCommon?: string | object, native?: any, options?: unknown, callback?: SetObjectCallback): void;
/** deletes a channel and its states */
/** Creates an object with type channel. It must be located under a device */
createChannel(parentDevice: string, channelName: string, callback?: SetObjectCallback): void;
createChannel(parentDevice: string, channelName: string, roleOrCommon: string | Partial<ioBroker.ChannelCommon>, callback?: SetObjectCallback): void;
createChannel(parentDevice: string, channelName: string, roleOrCommon: string | Partial<ioBroker.ChannelCommon>, native: Record<string, any>, callback?: SetObjectCallback): void;
createChannel(
parentDevice: string, channelName: string, roleOrCommon: string | Partial<ioBroker.ChannelCommon>,
native: Record<string, any>, options: unknown, callback?: SetObjectCallback
): void;
/** Creates an object with type channel. It must be located under a device */
createChannelAsync(parentDevice: string, channelName: string, roleOrCommon?: string | Partial<ioBroker.ChannelCommon>): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
createChannelAsync(
parentDevice: string, channelName: string, roleOrCommon: string | Partial<ioBroker.ChannelCommon>, native?: Record<string, any>
): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
createChannelAsync(
parentDevice: string, channelName: string, roleOrCommon: string | Partial<ioBroker.ChannelCommon>, native: Record<string, any>,
options?: unknown
): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
/** Deletes a channel and its states. It must have been created with `createChannel` */
deleteChannel(channelName: string, options?: unknown, callback?: ErrorCallback): void;
deleteChannel(parentDevice: string, channelName: string, options?: unknown, callback?: ErrorCallback): void;
/** Deletes a channel and its states. It must have been created with `createChannel` */
deleteChannelAsync(channelName: string, options?: unknown): Promise<void>;
deleteChannelAsync(parentDevice: string, channelName: string, options?: unknown): Promise<void>;
/** creates a state and the corresponding object */
createState(parentDevice: string, parentChannel: string, stateName: string, roleOrCommon?: string | object, native?: any, options?: unknown, callback?: SetObjectCallback): void;
/** deletes a state */
/**
* Creates a state and the corresponding object. It must be located in a channel under a device
*/
createState(parentDevice: string, parentChannel: string, stateName: string, callback?: SetObjectCallback): void;
createState(parentDevice: string, parentChannel: string, stateName: string, roleOrCommon: string | Partial<ioBroker.StateCommon>, callback?: SetObjectCallback): void;
createState(
parentDevice: string, parentChannel: string, stateName: string, roleOrCommon: string | Partial<ioBroker.StateCommon>,
native: Record<string, any>, callback?: SetObjectCallback
): void;
createState(
parentDevice: string, parentChannel: string, stateName: string, roleOrCommon: string | Partial<ioBroker.StateCommon>,
native: Record<string, any>, options: unknown, callback?: SetObjectCallback
): void;
/**
* Creates a state and the corresponding object. It must be located in a channel under a device
*/
createStateAsync(parentDevice: string, parentChannel: string, stateName: string, roleOrCommon?: string | Partial<ioBroker.StateCommon>): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
createStateAsync(
parentDevice: string, parentChannel: string, stateName: string, roleOrCommon: string | Partial<ioBroker.StateCommon>,
native?: Record<string, any>
): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
createStateAsync(
parentDevice: string, parentChannel: string, stateName: string, roleOrCommon: string | Partial<ioBroker.StateCommon>,
native: Record<string, any>, options?: unknown
): Promise<CallbackReturnTypeOf<SetObjectCallback>>;
/** Deletes a state. It must have been created with `createState` */
deleteState(stateName: string, options?: unknown, callback?: ErrorCallback): void;
deleteState(parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void;
deleteState(parentDevice: string, parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void;
/** Deletes a state. It must have been created with `createState` */
deleteStateAsync(stateName: string, options?: unknown): Promise<void>;
deleteStateAsync(parentChannel: string, stateName: string, options?: unknown): Promise<void>;
deleteStateAsync(parentDevice: string, parentChannel: string, stateName: string, options?: unknown): Promise<void>;
// tslint:enable:unified-signatures
/**
* Returns a list of all devices in this adapter instance
@@ -1220,6 +1425,12 @@ declare global {
*/
getDevices(callback: GetObjectsCallback3<DeviceObject>): void;
getDevices(options: unknown, callback: GetObjectsCallback3<DeviceObject>): void;
/**
* Returns a list of all devices in this adapter instance
* @param options (optional) Some internal options.
* @param callback Is called when the operation has finished (successfully or not)
*/
getDevicesAsync(options?: unknown): Promise<Array<GetObjectsItem<DeviceObject>>>;
/**
* Returns a list of all channels in this adapter instance
@@ -1228,8 +1439,8 @@ declare global {
* @param callback Is called when the operation has finished (successfully or not)
*/
getChannels(callback: GetObjectsCallback3<ChannelObject>): void;
getChannels(parentDevice: string | null, callback: GetObjectsCallback3<ChannelObject>): void;
getChannels(parentDevice: string | null, options: unknown, callback: GetObjectsCallback3<ChannelObject>): void;
getChannels(parentDevice: string, callback: GetObjectsCallback3<ChannelObject>): void;
getChannels(parentDevice: string, options: unknown, callback: GetObjectsCallback3<ChannelObject>): void;
/**
* Returns a list of all channels in this adapter instance
* @param parentDevice (optional) Name of the parent device to filter the channels by
@@ -1237,8 +1448,16 @@ declare global {
* @param callback Is called when the operation has finished (successfully or not)
*/
getChannelsOf(callback: GetObjectsCallback3<ChannelObject>): void;
getChannelsOf(parentDevice: string | null, callback: GetObjectsCallback3<ChannelObject>): void;
getChannelsOf(parentDevice: string | null, options: unknown, callback: GetObjectsCallback3<ChannelObject>): void;
getChannelsOf(parentDevice: string, callback: GetObjectsCallback3<ChannelObject>): void;
getChannelsOf(parentDevice: string, options: unknown, callback: GetObjectsCallback3<ChannelObject>): void;
/**
* Returns a list of all channels in this adapter instance
* @param parentDevice (optional) Name of the parent device to filter the channels by
* @param options (optional) Some internal options.
*/
getChannelsOfAsync(): Promise<Array<GetObjectsItem<ChannelObject>>>;
// tslint:disable-next-line:unified-signatures
getChannelsOfAsync(parentDevice: string, options?: unknown): Promise<Array<GetObjectsItem<ChannelObject>>>;
/**
* Returns a list of all states in this adapter instance
@@ -1248,36 +1467,82 @@ declare global {
* @param callback Is called when the operation has finished (successfully or not)
*/
getStatesOf(callback: GetObjectsCallback3<StateObject>): void;
getStatesOf(parentDevice: string | null, callback: GetObjectsCallback3<StateObject>): void;
getStatesOf(parentDevice: string | null, parentChannel: string | null, callback: GetObjectsCallback3<StateObject>): void;
getStatesOf(parentDevice: string | null, parentChannel: string | null, options: unknown, callback: GetObjectsCallback3<StateObject>): void;
getStatesOf(parentDevice: string, callback: GetObjectsCallback3<StateObject>): void;
getStatesOf(parentDevice: string, parentChannel: string, callback: GetObjectsCallback3<StateObject>): void;
getStatesOf(parentDevice: string, parentChannel: string, options: unknown, callback: GetObjectsCallback3<StateObject>): void;
/**
* Returns a list of all states in this adapter instance
* @param parentDevice (optional) Name of the parent device to filter the channels by
* @param parentChannel (optional) Name of the parent channel to filter the channels by
* @param options (optional) Some internal options.
*/
// tslint:disable:unified-signatures
getStatesOfAsync(): Promise<Array<GetObjectsItem<StateObject>>>;
getStatesOfAsync(parentDevice: string, parentChannel?: string): Promise<Array<GetObjectsItem<StateObject>>>;
getStatesOfAsync(parentDevice: string, parentChannel: string, options?: unknown): Promise<Array<GetObjectsItem<StateObject>>>;
// tslint:enable:unified-signatures
// ==============================
// filesystem
/**
* reads the content of directory from DB for given adapter and path
* @param adapter - adapter name. If adapter name is null, default will be the name of the current adapter.
* @param path - path to direcory without adapter name. E.g. If you want to read "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0".
* @param adapterName - adapter name. If adapter name is null, default will be the name of the current adapter.
* @param path - path to directory without adapter name. E.g. If you want to read "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0".
*/
readDir(adapterName: string, path: string, callback: ReadDirCallback): void;
readDir(adapterName: string, path: string, options: unknown, callback: ReadDirCallback): void;
mkDir(adapterName: string, path: string, callback: ErrorCallback): void;
mkDir(adapterName: string, path: string, options: unknown, callback: ErrorCallback): void;
readDir(adapterName: string | null, path: string, callback: ReadDirCallback): void;
readDir(adapterName: string | null, path: string, options: unknown, callback: ReadDirCallback): void;
/**
* reads the content of directory from DB for given adapter and path
* @param adapterName - adapter name. If adapter name is null, default will be the name of the current adapter.
* @param path - path to directory without adapter name. E.g. If you want to read "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0".
*/
readDirAsync(adapterName: string | null, path: string, options?: unknown): Promise<CallbackReturnTypeOf<ReadDirCallback>>;
readFile(adapterName: string, path: string, callback: ReadFileCallback): void;
readFile(adapterName: string, path: string, options: unknown, callback: ReadFileCallback): void;
writeFile(adapterName: string, path: string, data: Buffer | string, callback: ErrorCallback): void;
mkDir(adapterName: string | null, path: string, callback: ErrorCallback): void;
mkDir(adapterName: string | null, path: string, options: unknown, callback: ErrorCallback): void;
mkDirAsync(adapterName: string | null, path: string, options?: unknown): Promise<void>;
readFile(adapterName: string | null, path: string, callback: ReadFileCallback): void;
readFile(adapterName: string | null, path: string, options: unknown, callback: ReadFileCallback): void;
readFileAsync(adapterName: string | null, path: string, options?: unknown): Promise<{ file: string | Buffer, mimeType: string }>;
writeFile(adapterName: string | null, path: string, data: Buffer | string, callback: ErrorCallback): void;
// options see https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/objects/objectsInMemServer.js#L599
writeFile(adapterName: string, path: string, data: Buffer | string, options: unknown, callback: ErrorCallback): void;
writeFile(adapterName: string | null, path: string, data: Buffer | string, options: unknown, callback: ErrorCallback): void;
writeFileAsync(adapterName: string | null, path: string, data: Buffer | string, options?: unknown): Promise<void>;
delFile(adapterName: string, path: string, callback: ErrorCallback): void;
delFile(adapterName: string, path: string, options: unknown, callback: ErrorCallback): void;
unlink(adapterName: string, path: string, callback: ErrorCallback): void;
unlink(adapterName: string, path: string, options: unknown, callback: ErrorCallback): void;
/**
* Deletes a given file
* @param adapterName - adapter name. If adapter name is null, default will be the name of the current adapter.
* @param path - path to directory without adapter name. E.g. If you want to delete "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0".
*/
delFile(adapterName: string | null, path: string, callback: ErrorCallback): void;
delFile(adapterName: string | null, path: string, options: unknown, callback: ErrorCallback): void;
/**
* Deletes a given file
* @param adapterName - adapter name. If adapter name is null, default will be the name of the current adapter.
* @param path - path to directory without adapter name. E.g. If you want to delete "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0".
*/
delFileAsync(adapterName: string | null, path: string, options?: unknown): Promise<void>;
rename(adapterName: string, oldName: string, newName: string, callback: ErrorCallback): void;
rename(adapterName: string, oldName: string, newName: string, options: unknown, callback: ErrorCallback): void;
/**
* Deletes a given file
* @param adapterName - adapter name. If adapter name is null, default will be the name of the current adapter.
* @param path - path to directory without adapter name. E.g. If you want to delete "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0".
*/
unlink(adapterName: string | null, path: string, callback: ErrorCallback): void;
unlink(adapterName: string | null, path: string, options: unknown, callback: ErrorCallback): void;
/**
* Deletes a given file
* @param adapterName - adapter name. If adapter name is null, default will be the name of the current adapter.
* @param path - path to directory without adapter name. E.g. If you want to delete "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0".
*/
unlinkAsync(adapterName: string | null, path: string, options?: unknown): Promise<void>;
rename(adapterName: string | null, oldName: string, newName: string, callback: ErrorCallback): void;
rename(adapterName: string | null, oldName: string, newName: string, options: unknown, callback: ErrorCallback): void;
renameAsync(adapterName: string | null, oldName: string, newName: string, options?: unknown): Promise<void>;
/**
* Changes access rights of all files in the adapter directory
@@ -1287,6 +1552,7 @@ declare global {
* @param callback Is called when the operation has finished (successfully or not)
*/
chmodFile(adapter: string | null, path: string, options: { mode: number | string } | Record<string, any>, callback: ChownFileCallback): void;
chmodFileAsync(adapter: string | null, path: string, options: { mode: number | string } | Record<string, any>): Promise<{ entries: ChownFileResult[], id: string }>;
// ==============================
// formatting
@@ -1354,6 +1620,8 @@ declare global {
// This is a version used by GetDevices/GetChannelsOf/GetStatesOf
type GetObjectsCallback3<T extends BaseObject> = (err: string | null, result?: Array<GetObjectsItem<T>>) => void;
type SecondParameterOf<T extends (...args: any[]) => any> = T extends (arg0: any, arg1: infer R, ...args: any[]) => any ? R : never;
type CallbackReturnTypeOf<T extends (...args: any[]) => any> = Exclude<SecondParameterOf<T>, null | undefined>;
type GetStateCallback = (err: string | null, state: State | null | undefined) => void;
type GetStatesCallback = (err: string | null, states: Record<string, State>) => void;
/** Version of the callback used by States.getStates */

View File

@@ -1,34 +1,7 @@
// For now, this "utils" module is necessary, as it is included in every adapter
// Once this PR is merged and @types/iobroker is available, it will become part of
// `iobroker.adapter-core`, which brings typings for it
declare const utils: {
readonly controllerDir: string;
getConfig(): string;
// tslint:disable:unified-signatures
adapter(adapterName: string): ioBroker.Adapter;
adapter(adapterOptions: ioBroker.AdapterOptions): ioBroker.Adapter;
// tslint:enable:unified-signatures
};
declare function assertNever(val: never): never;
// Let the tests begin
let adapter: ioBroker.Adapter;
// Test constructors
adapter = utils.adapter("my-adapter-name");
adapter = utils.adapter({
name: "my-adapter-name"
});
adapter = utils.adapter({
name: "my-adapter-name",
ready: readyHandler,
stateChange: stateChangeHandler,
objectChange: objectChangeHandler,
message: messageHandler,
unload: unloadHandler,
});
declare let adapter: ioBroker.Adapter;
// Test EventEmitter definitions
adapter
@@ -141,37 +114,62 @@ adapter.setState("state.name", "value", (err, id) => { });
adapter.setState("state.name", { val: "value", ack: true });
adapter.setState("state.name", { val: "value", ack: true }, (err, id) => { });
adapter.setStateAsync("state.name", "value").then(id => id.toLowerCase());
adapter.setStateAsync("state.name", "value", true).then(id => id.toLowerCase());
adapter.setStateAsync("state.name", { val: "value", ack: true }).then(id => id.toLowerCase());
adapter.setStateChanged("state.name", "value");
adapter.setStateChanged("state.name", "value", true);
adapter.setStateChanged("state.name", "value", (err, id) => { });
adapter.setStateChanged("state.name", { val: "value", ack: true });
adapter.setStateChanged("state.name", { val: "value", ack: true }, (err, id) => { });
adapter.setStateChangedAsync("state.name", "value").then(id => id.toLowerCase());
adapter.setStateChangedAsync("state.name", "value", true).then(id => id.toLowerCase());
adapter.setStateChangedAsync("state.name", { val: "value", ack: true }).then(id => id.toLowerCase());
adapter.setForeignState("state.name", "value");
adapter.setForeignState("state.name", "value", true);
adapter.setForeignState("state.name", "value", (err, id) => { });
adapter.setForeignState("state.name", { val: "value", ack: true });
adapter.setForeignState("state.name", { val: "value", ack: true }, (err, id) => { });
adapter.setForeignStateAsync("state.name", "value").then(id => id.toLowerCase());
adapter.setForeignStateAsync("state.name", "value", true).then(id => id.toLowerCase());
adapter.setForeignStateAsync("state.name", { val: "value", ack: true }).then(id => id.toLowerCase());
adapter.setForeignStateChanged("state.name", "value");
adapter.setForeignStateChanged("state.name", "value", true);
adapter.setForeignStateChanged("state.name", "value", (err, id) => { });
adapter.setForeignStateChanged("state.name", { val: "value", ack: true });
adapter.setForeignStateChanged("state.name", { val: "value", ack: true }, (err, id) => { });
adapter.setForeignStateChangedAsync("state.name", "value").then(id => id.toLowerCase());
adapter.setForeignStateChangedAsync("state.name", "value", true).then(id => id.toLowerCase());
adapter.setForeignStateChangedAsync("state.name", { val: "value", ack: true }).then(id => id.toLowerCase());
adapter.setObject("obj.id", { type: "state", common: { name: "foo" }, native: {} });
adapter.setObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { });
adapter.setForeignObject("obj.id", { type: "state", common: { name: "foo" }, native: {} });
adapter.setForeignObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { });
adapter.setObjectAsync("obj.id", { type: "state", common: { name: "foo" }, native: {} }).then(({ id }) => id.toLowerCase());
adapter.setForeignObjectAsync("obj.id", { type: "state", common: { name: "foo" }, native: {} }).then(({ id }) => id.toLowerCase());
adapter.setObjectNotExists("obj.id", { type: "state", common: { name: "foo" }, native: {} });
adapter.setObjectNotExists("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { });
adapter.setForeignObjectNotExists("obj.id", { type: "state", common: { name: "foo" }, native: {} });
adapter.setForeignObjectNotExists("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { });
adapter.setObjectNotExistsAsync("obj.id", { type: "state", common: { name: "foo" }, native: {} }).then(({ id }) => id.toLowerCase());
adapter.setForeignObjectNotExistsAsync("obj.id", { type: "state", common: { name: "foo" }, native: {} }).then(({ id }) => id.toLowerCase());
adapter.getObject("obj.id", (err, obj) => { });
adapter.getForeignObject("obj.id", (err, obj) => { });
adapter.getObjectAsync("obj.id").then(obj => obj._id.toLowerCase());
adapter.getForeignObjectAsync("obj.id").then(obj => obj._id.toLowerCase());
adapter.subscribeObjects("*");
adapter.subscribeStates("*");
adapter.subscribeForeignObjects("*");

181
types/ip/index.d.ts vendored
View File

@@ -1,11 +1,12 @@
// Type definitions for node-ip
// Type definitions for ip 1.1
// Project: https://github.com/indutny/node-ip
// Definitions by: Peter Harris <https://github.com/codeanimal>
// BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
interface SubnetInfo {
export interface SubnetInfo {
networkAddress: string;
firstAddress: string;
lastAddress: string;
@@ -17,110 +18,108 @@ interface SubnetInfo {
contains(ip: string): boolean;
}
declare module "ip" {
/**
* Check two IP address are the same.
**/
export function isEqual(ip1: string, ip2: string): boolean;
/**
* Check two IP address are the same.
*/
export function isEqual(ip1: string, ip2: string): boolean;
/**
* Convert an IP string into a buffer.
**/
export function toBuffer(ip: string, buffer?: Buffer, offset?: number): Buffer;
/**
* Convert an IP string into a buffer.
*/
export function toBuffer(ip: string, buffer?: Buffer, offset?: number): Buffer;
/**
* Convert an IP buffer into a string.
**/
export function toString(ip: Buffer, offset?: number, length?: number): string;
/**
* Convert an IP buffer into a string.
*/
export function toString(ip: Buffer, offset?: number, length?: number): string;
/**
* Get the subnet mask from a CIDR prefix length.
*
* @param family The IP family is infered from the prefixLength, but can be explicity specified as either "ipv4" or "ipv6".
**/
export function fromPrefixLen(prefixLength: number, family?:string): string;
/**
* Get the subnet mask from a CIDR prefix length.
*
* @param family The IP family is infered from the prefixLength, but can be explicity specified as either "ipv4" or "ipv6".
*/
export function fromPrefixLen(prefixLength: number, family?: 'ipv4' | 'ipv6'): string;
/**
* Get the network ID IP address from an IP address and its subnet mask.
**/
export function mask(ip: string, mask: string): string;
/**
* Get the network ID IP address from an IP address and its subnet mask.
*/
export function mask(ip: string, mask: string): string;
/**
* Get the network ID IP address from an IP address in CIDR notation.
**/
export function cidr(cidr: string): string;
/**
* Get the network ID IP address from an IP address in CIDR notation.
*/
export function cidr(cidr: string): string;
/**
* Get the bitwise inverse (NOT every octet) of an IP address or subnet mask.
**/
export function not(ip: string): string;
/**
* Get the bitwise inverse (NOT every octet) of an IP address or subnet mask.
*/
export function not(ip: string): string;
/**
* Get the bitwise OR of two IP addresses (usually an IP address and a subnet mask).
**/
export function or(ip: string, mask:string): string;
/**
* Get the bitwise OR of two IP addresses (usually an IP address and a subnet mask).
*/
export function or(ip: string, mask: string): string;
/**
* Check whether an IP is within a private IP address range.
**/
export function isPrivate(ip: string): boolean;
/**
* Check whether an IP is within a private IP address range.
*/
export function isPrivate(ip: string): boolean;
/**
* Check whether an IP is within a public IP address range.
**/
export function isPublic(ip: string): boolean;
/**
* Check whether an IP is within a public IP address range.
*/
export function isPublic(ip: string): boolean;
/**
* Check whether an IP is a loopback address.
**/
export function isLoopback(ip: string): boolean;
/**
* Check whether an IP is a loopback address.
*/
export function isLoopback(ip: string): boolean;
/**
* Check whether an IP is a IPv4 address.
**/
export function isV4Format(ip: string): boolean;
/**
* Check whether an IP is a IPv4 address.
*/
export function isV4Format(ip: string): boolean;
/**
* Check whether an IP is a IPv6 address.
**/
export function isV6Format(ip: string): boolean;
/**
* Check whether an IP is a IPv6 address.
*/
export function isV6Format(ip: string): boolean;
/**
* Get the loopback address for an IP family.
*
* @param family The family can be either "ipv4" or "ipv6". Default: "ipv4".
**/
export function loopback(family?: string): string;
/**
* Get the loopback address for an IP family.
*
* @param family The family can be either "ipv4" or "ipv6". Default: "ipv4".
*/
export function loopback(family?: 'ipv4' | 'ipv6'): string;
/**
* Get the address for the network interface on the current system with the specified 'name'.
* If no interface name is specified, the first IPv4 address or loopback address is returned.
*
* @param name The name can be any named interface, or 'public' or 'private'.
* @param family The family can be either "ipv4" or "ipv6". Default: "ipv4".
**/
export function address(name?: string, family?: string):string;
/**
* Get the address for the network interface on the current system with the specified 'name'.
* If no interface name is specified, the first IPv4 address or loopback address is returned.
*
* @param name The name can be any named interface, or 'public' or 'private'.
* @param family The family can be either "ipv4" or "ipv6". Default: "ipv4".
*/
export function address(name?: 'public' | 'private' | string, family?: 'ipv4' | 'ipv6'): string;
/**
* Convert a string IPv4 IP address to the equivalent long numeric value.
**/
export function toLong(ip: string): number;
/**
* Convert a string IPv4 IP address to the equivalent long numeric value.
*/
export function toLong(ip: string): number;
/**
* Convert an IPv4 IP address from its the long numeric value to a string.
**/
export function fromLong(ip: number): string;
/**
* Convert an IPv4 IP address from its the long numeric value to a string.
*/
export function fromLong(ip: number): string;
/**
* Get the subnet information.
* @param ip IP address.
* @param subnet Subnet address.
*/
export function subnet(ip: string, subnet: string): SubnetInfo;
/**
* Get the subnet information.
* @param ip IP address.
* @param subnet Subnet address.
*/
export function subnet(ip: string, subnet: string): SubnetInfo;
/**
* Get the subnet information.
* @param cidr CIDR address.
*/
export function cidrSubnet(cidr: string): SubnetInfo;
}
/**
* Get the subnet information.
* @param cidr CIDR address.
*/
export function cidrSubnet(cidr: string): SubnetInfo;

View File

@@ -1,26 +1,24 @@
import ip = require('ip');
var myIP = ip.address();
const myIP = ip.address();
ip.cidr("192.168.0.1/24");
ip.cidr('192.168.0.1/24');
ip.fromLong(ip.toLong(myIP));
ip.fromPrefixLen(24);
ip.isEqual("192.168.0.1", myIP);
ip.isLoopback("127.0.0.1");
ip.isEqual('192.168.0.1', myIP);
ip.isLoopback('127.0.0.1');
ip.isPrivate(myIP);
ip.isPublic(myIP);
ip.loopback("ipv6");
ip.mask("192.168.0.1", "255.255.255.0");
ip.not("255.255.255.0");
ip.or("192.168.0.1", "255.255.255.0");
var buff:any = ip.toBuffer(myIP);
ip.loopback('ipv6');
ip.mask('192.168.0.1', '255.255.255.0');
ip.not('255.255.255.0');
ip.or('192.168.0.1', '255.255.255.0');
const buff: any = ip.toBuffer(myIP);
ip.toString(buff);
ip.subnet('192.168.1.134', '255.255.255.192');
ip.cidrSubnet('192.168.1.134/26');
ip.cidrSubnet('192.168.1.134/26').contains('192.168.1.134');
var buf = new Buffer(128);
var offset = 64;
const buf = new Buffer(128);
const offset = 64;
ip.toBuffer('127.0.0.1', buf, offset);
ip.toString(buf, offset, 4);

View File

@@ -6,7 +6,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
@@ -20,4 +20,4 @@
"index.d.ts",
"ip-tests.ts"
]
}
}

View File

@@ -1,79 +1,3 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
"extends": "dtslint/dt.json"
}

8
types/is-plain-obj/index.d.ts vendored Normal file
View File

@@ -0,0 +1,8 @@
// Type definitions for is-plain-obj 1.1
// Project: https://github.com/sindresorhus/is-plain-obj
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = isPlainObj;
declare function isPlainObj(input: any): boolean;

View File

@@ -0,0 +1,3 @@
import isPlainObj = require('is-plain-obj');
isPlainObj({ foo: 'bar' }); // $ExpectType boolean

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"is-plain-obj-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

93
types/istextorbinary/index.d.ts vendored Normal file
View File

@@ -0,0 +1,93 @@
// Type definitions for istextorbinary 2.3
// Project: https://github.com/bevry/istextorbinary
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
/**
* Is Text (Synchronous)
* Determine whether or not a file is a text or binary file.
* Determined by extension checks first, then if unknown extension, will fallback on encoding detection.
* We do that as encoding detection cannot guarantee everything, especially for chars between utf8 and utf16.
* We use the extensions from https://github.com/bevry/textextensions and https://github.com/bevry/binaryextensions
* @param filename the filename for the file/buffer if available
* @param buffer the buffer for the file if available
*/
export function isTextSync(filename: string, buffer?: Buffer): boolean;
export function isTextSync(filename: undefined, buffer: Buffer): boolean;
/**
* Is Text
* Uses `isTextSync` behind the scenes.
* @param filename forwarded to `isTextSync`
* @param buffer forwarded to `isTextSync`
* @param next accepts arguments: (error: Error, result: Boolean)
*/
export function isText(
filename: string,
buffer: Buffer | undefined,
next: (err: null, result: boolean) => void
): void;
export function isText(
filename: undefined,
buffer: Buffer,
next: (err: null, result: boolean) => void
): void;
/**
* Is Binary (Synchronous)
* Uses `isTextSync` behind the scenes.
* @param filename forwarded to `isTextSync`
* @param buffer forwarded to `isTextSync`
*/
export function isBinarySync(filename: string, buffer?: Buffer): boolean;
export function isBinarySync(filename: undefined, buffer: Buffer): boolean;
/**
* Is Binary
* Uses `isText` behind the scenes.
* @param filename forwarded to `isText`
* @param buffer forwarded to `isText`
* @param next accepts arguments: (error: Error, result: Boolean)
*/
export function isBinary(
filename: string,
buffer: Buffer | undefined,
next: (err: null, result: boolean) => void
): void;
export function isBinary(
filename: undefined,
buffer: Buffer,
next: (err: null, result: boolean) => void
): void;
/**
* Get the encoding of a buffer.
* We fetch a bunch chars from the start, middle and end of the buffer.
* We check all three, as doing only start was not enough, and doing only middle was not enough, so better safe than sorry.
* @param buffer
* @param [opts]
* @param [opts.chunkLength = 24]
* @param [opts.chunkBegin = 0]
* @returns either an Error instance if something went wrong, or if successful "utf8" or "binary"
*/
export function getEncodingSync(buffer: Buffer, opts?: Options): 'utf8' | 'binary';
/**
* Get the encoding of a buffer
* Uses `getEncodingSync` behind the scenes.
* @param buffer forwarded to `getEncodingSync`
* @param opts forwarded to `getEncodingSync`
* @param next accepts arguments: (error: Error, result: Boolean)
*/
export function getEncoding(
buffer: Buffer,
opts: Options | undefined,
next: (err: null, result: 'utf8' | 'binary') => void
): void;
export interface Options {
chunkLength?: number;
chunkBegin?: number;
}

View File

@@ -0,0 +1,67 @@
import {
isTextSync,
isText,
isBinarySync,
isBinary,
getEncodingSync,
getEncoding,
} from 'istextorbinary';
isTextSync('foo.txt'); // $ExpectType boolean
isTextSync('foo.txt', new Buffer(1)); // $ExpectType boolean
isTextSync(undefined, new Buffer(1)); // $ExpectType boolean
isTextSync(); // $ExpectError
isTextSync(undefined); // $ExpectError
isTextSync(undefined, undefined); // $ExpectError
isText('foo.txt', undefined, (err, result) => {
err; // $ExpectType null
result; // $ExpectType boolean
});
isText('foo.txt', new Buffer(1), (err, result) => {
err; // $ExpectType null
result; // $ExpectType boolean
});
isText(undefined, new Buffer(1), (err, result) => {
err; // $ExpectType null
result; // $ExpectType boolean
});
isText(undefined, undefined, (err, result) => {}); // $ExpectError
isBinarySync('foo.txt'); // $ExpectType boolean
isBinarySync('foo.txt', new Buffer(1)); // $ExpectType boolean
isBinarySync(undefined, new Buffer(1)); // $ExpectType boolean
isBinarySync(); // $ExpectError
isBinarySync(undefined); // $ExpectError
isBinarySync(undefined, undefined); // $ExpectError
isBinary('foo.txt', undefined, (err, result) => {
err; // $ExpectType null
result; // $ExpectType boolean
});
isBinary('foo.txt', new Buffer(1), (err, result) => {
err; // $ExpectType null
result; // $ExpectType boolean
});
isBinary(undefined, new Buffer(1), (err, result) => {
err; // $ExpectType null
result; // $ExpectType boolean
});
isBinary(undefined, undefined, (err, result) => {}); // $ExpectError
getEncodingSync(new Buffer(1)); // $ExpectType "utf8" | "binary"
getEncodingSync(new Buffer(1), { chunkBegin: 0 }); // $ExpectType "utf8" | "binary"
getEncodingSync(new Buffer(1), { chunkLength: 10 }); // $ExpectType "utf8" | "binary"
getEncoding(new Buffer(1), undefined, (err, result) => {
err; // $ExpectType null
result; // $ExpectType "utf8" | "binary"
});
getEncoding(new Buffer(1), { chunkBegin: 0 }, (err, result) => {
err; // $ExpectType null
result; // $ExpectType "utf8" | "binary"
});
getEncoding(new Buffer(1), { chunkLength: 10 }, (err, result) => {
err; // $ExpectType null
result; // $ExpectType "utf8" | "binary"
});

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"istextorbinary-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -6,22 +6,22 @@
/// <reference types="jest" />
export interface PartialMockInstance<T> {
mockReturnValue: jest.MockInstance<T>['mockReturnValue'];
mockReturnValueOnce: jest.MockInstance<T>['mockReturnValueOnce'];
mockResolvedValue: jest.MockInstance<T>['mockResolvedValue'];
mockResolvedValueOnce: jest.MockInstance<T>['mockResolvedValueOnce'];
mockRejectedValue: jest.MockInstance<T>['mockRejectedValue'];
mockRejectedValueOnce: jest.MockInstance<T>['mockRejectedValueOnce'];
}
export interface When {
<T>(fn: jest.Mocked<T> | jest.Mock<T>): When;
// due to no-unnecessary-generics lint rule, the generics have been replaced with 'any'
// calledWith<T>(...matchers: any[]): PartialMockInstance<T>;
// expectCalledWith<T>(...matchers: any[]): PartialMockInstance<T>;
calledWith(...matchers: any[]): PartialMockInstance<any>;
expectCalledWith(...matchers: any[]): PartialMockInstance<any>;
calledWith(...matchers: any[]): When;
expectCalledWith(...matchers: any[]): When;
mockReturnValue: (value: any) => jest.MockInstance<any>['mockReturnValue'] & When;
mockReturnValueOnce: (value: any) => jest.MockInstance<any>['mockReturnValue'] & When;
mockResolvedValue: (value: any) => jest.MockInstance<any>['mockReturnValue'] & When;
mockResolvedValueOnce: (value: any) => jest.MockInstance<any>['mockReturnValue'] & When;
mockRejectedValue: (value: any) => jest.MockInstance<any>['mockReturnValue'] & When;
mockRejectedValueOnce: (value: any) => jest.MockInstance<any>['mockReturnValue'] & When;
}
export const when: When;

View File

@@ -43,6 +43,37 @@ describe('mock-when test', () => {
expect(fn(5)).toEqual(undefined);
});
it('Supports chained calls:', () => {
const fn = jest.fn();
when(fn)
.calledWith(1).mockReturnValue('no')
.calledWith(2).mockReturnValue('way?')
.calledWith(3).mockReturnValue('yes')
.calledWith(4).mockReturnValue('way!');
expect(fn(1)).toEqual('no');
expect(fn(2)).toEqual('way?');
expect(fn(3)).toEqual('yes');
expect(fn(4)).toEqual('way!');
expect(fn(5)).toEqual(undefined);
});
it('Supports chained calls with defaults:', () => {
const fn = jest.fn();
when(fn)
.mockReturnValue('nice')
.calledWith(1).mockReturnValue('no')
.calledWith(2).mockReturnValue('way?')
.calledWith(3).mockReturnValue('yes')
.calledWith(4).mockReturnValue('way!');
expect(fn(1)).toEqual('no');
expect(fn(2)).toEqual('way?');
expect(fn(3)).toEqual('yes');
expect(fn(4)).toEqual('way!');
expect(fn(5)).toEqual('nice');
});
it('Assert the args:', () => {
const fn = jest.fn();
when(fn).expectCalledWith(1).mockReturnValue('x');

View File

@@ -981,7 +981,7 @@ declare function pending(reason?: string): void;
/**
* Fails a test when called within one.
*/
declare function fail(error?: any): void;
declare function fail(error?: any): never;
declare namespace jasmine {
let DEFAULT_TIMEOUT_INTERVAL: number;
function clock(): Clock;

View File

@@ -5,6 +5,7 @@
// Philipp Gürtler <https://github.com/philippguertler>
// Daniel McGraw <https://github.com/danielmcgraw>
// Benjamin Dobson <https://github.com/bpdsw>
// Be Birchall <https://gitnub.com/bebebebebe>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -241,6 +242,31 @@ interface Region {
height: number;
}
interface CaptionOptions {
color: string;
fontSize: number;
fontFamily: string;
fontOpacity: number;
backgroundColor: string;
backgroundOpacity: number;
edgeStyle: string;
windowColor: string;
windowOpacity: number;
}
interface Level {
bitrate: number;
height: number;
width: number;
label: string;
}
interface QualityLevel {
mode: 'auto' | 'manual';
level: Level;
reason: 'auto' | 'api' | 'initial choice';
}
interface JWPlayer {
addButton(icon: string, label: string, handler: () => void, id: string): void;
getAudioTracks(): any[];
@@ -266,6 +292,7 @@ interface JWPlayer {
getContainer(): HTMLElement;
getEnvironment(): Environment;
getWidth(): number;
getVisualQuality(): QualityLevel | undefined;
load(playlist: any[]): void;
load(playlist: string): void;
on(event: 'adClick', callback: EventCallback<AdProgressParam>): void;
@@ -469,6 +496,7 @@ interface JWPlayer {
setMute(state?: boolean): void;
setup(options: any): JWPlayer;
setVolume(volume: number): void;
setCaptions(options: CaptionOptions): void;
stop(): void;
}

64
types/keyv/index.d.ts vendored
View File

@@ -1,49 +1,33 @@
// Type definitions for keyv 3.0
// Type definitions for keyv 3.1
// Project: https://github.com/lukechilds/keyv
// Definitions by: AryloYeung <https://github.com/Arylo>
// BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/// <reference types="node" />
interface KeyvOptions {
/** Namespace for the current instance. */
namespace?: string;
/** A custom serialization function. */
serialize?: (data: any) => string;
/** A custom deserialization function. */
deserialize?: (data: string) => any;
/** The connection string URI. */
uri?: string;
/** The storage adapter instance to be used by Keyv. */
store?: any;
/** Default TTL. Can be overridden by specififying a TTL on `.set()`. */
ttl?: number;
/** Specify an adapter to use. e.g `'redis'` or `'mongodb'`. */
adapter?: string;
}
// TypeScript Version: 2.3
declare class Keyv extends NodeJS.EventEmitter {
/// <reference types="node" />
declare class Keyv<TValue = any> extends NodeJS.EventEmitter {
/**
* @param opts The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options.
*/
constructor(opts?: KeyvOptions);
constructor(opts?: Keyv.Options<TValue>);
/**
* @param uri The connection string URI.
*
* Merged into the options object as options.uri.
* @param opts The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options.
*/
constructor(uri?: string, opts?: KeyvOptions);
/** Returns the namespace of a key */
_getKeyPrefix(key: string): string;
constructor(uri?: string, opts?: Keyv.Options<TValue>);
/** Returns the value. */
get(key: string): Promise<any>;
get(key: string): Promise<TValue | undefined>;
/**
* Set a value.
*
* By default keys are persistent. You can set an expiry TTL in milliseconds.
*/
set(key: string, value: any, ttl?: number): (Promise<boolean> | undefined);
set(key: string, value: TValue, ttl?: number): Promise<true>;
/**
* Deletes an entry.
*
@@ -54,4 +38,32 @@ declare class Keyv extends NodeJS.EventEmitter {
clear(): Promise<void>;
}
declare namespace Keyv {
interface Options<TValue> {
/** Namespace for the current instance. */
namespace?: string;
/** A custom serialization function. */
serialize?: (data: TValue) => string;
/** A custom deserialization function. */
deserialize?: (data: string) => TValue;
/** The connection string URI. */
uri?: string;
/** The storage adapter instance to be used by Keyv. */
store?: Store<TValue>;
/** Default TTL. Can be overridden by specififying a TTL on `.set()`. */
ttl?: number;
/** Specify an adapter to use. e.g `'redis'` or `'mongodb'`. */
adapter?: 'redis' | 'mongodb' | 'mongo' | 'sqlite' | 'postgresql' | 'postgres' | 'mysql';
[key: string]: any;
}
interface Store<TValue> {
get(key: string): TValue | Promise<TValue | undefined> | undefined;
set(key: string, value: TValue, ttl?: number): any;
delete(key: string): boolean | Promise<boolean>;
clear(): void | Promise<void>;
}
}
export = Keyv;

View File

@@ -1,11 +1,31 @@
import Keyv = require("keyv");
import Keyv = require('keyv');
import QuickLRU = require('quick-lru');
new Keyv({
uri: 'redis://user:pass@localhost:6379',
namespace: "redis"
namespace: 'redis',
});
new Keyv({ uri: 'redis://user:pass@localhost:6379' });
new Keyv({ namespace: 'redis' });
new Keyv({ ttl: 123 });
new Keyv({ adapter: 'redis' });
new Keyv({ adapter: 'mongo' });
new Keyv({ adapter: 'mongodb' });
new Keyv({ adapter: 'sqlite' });
new Keyv({ adapter: 'postgres' });
new Keyv({ adapter: 'postgresql' });
new Keyv({ adapter: 'mysql' });
new Keyv({ adapter: 'foo' }); // $ExpectError
new Keyv<boolean>({ serialize: JSON.stringify });
new Keyv<boolean>({ deserialize: JSON.parse });
new Keyv('mongodb://user:pass@localhost:27017/dbname');
new Keyv<boolean>({ store: new Map() });
const lru = new QuickLRU<string, boolean>({ maxSize: 1000 });
const opts: Keyv.Options<boolean> = { store: lru };
new Keyv(opts);
new Keyv('mongodb://user:pass@localhost:27017/dbname', { namespace: 'mongodb' });
new Keyv('redis://user:pass@localhost:6379');
new Keyv('sqlite://path/to/database.sqlite');
new Keyv('postgresql://user:pass@localhost:5432/dbname');
@@ -13,13 +33,13 @@ new Keyv('mysql://user:pass@localhost:3306/dbname');
new Keyv();
(async () => {
const keyv = new Keyv();
const keyv = new Keyv<string>();
keyv.on('error', err => console.log('Connection Error', err));
await keyv.set('foo', 'expires in 1 second', 1000); // true
await keyv.set('foo', 'never expires'); // true
await keyv.get('foo'); // 'never expires'
await keyv.delete('foo'); // true
await keyv.clear(); // undefined
await keyv.set('foo', 'expires in 1 second', 1000); // $ExpectType true
await keyv.set('foo', 'never expires'); // $ExpectType true
await keyv.get('foo'); // $ExpectType string | undefined
await keyv.delete('foo'); // $ExpectType boolean
await keyv.clear(); // $ExpectType void
})();

View File

@@ -1,4 +1,4 @@
// Type definitions for klaw-sync 5.0
// Type definitions for klaw-sync 6.0
// Project: https://github.com/manidlou/node-klaw-sync
// Definitions by: Brendan Forster <https://github.com/shiftkey>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -53,6 +53,17 @@ declare namespace klawSync {
* @since v2.0.0
*/
filter?: Filter
/**
* @description traverse all subdirectories, regardless of `filter` option.
*
* When set to true, traverseAll produces similar behavior to the default
* behavior prior to `v4.0.0`. The current default of `traverseAll: false`
* is equivalent to the old `noRecurseOnFailedFilter: true`).
*
* @since v6.0.0
*/
traverseAll?: boolean
}
}

View File

@@ -18,7 +18,8 @@ const options: klawSync.Options = {
return item.path.indexOf('node_modules') < 0
},
depthLimit: 5,
fs
fs,
traverseAll: true
}
klawSync('/some/dir', options).forEach(outputMessage)

60
types/memory-pager/index.d.ts vendored Normal file
View File

@@ -0,0 +1,60 @@
// Type definitions for memory-pager 1.4
// Project: https://github.com/mafintosh/memory-pager
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
export = Pager;
declare const Pager: Pager;
interface Pager {
/**
* Create a new pager.
* @param pageSize defaults to 1024.
*/
(pageSize?: number): Pager.PagerInstance;
/**
* Create a new pager.
* @param pageSize defaults to 1024.
*/
new (pageSize?: number): Pager.PagerInstance;
}
declare namespace Pager {
interface PagerInstance {
/**
* Get a page. The page will be allocated at first access.
* @param pageNumber
* @param noAllocate will make the method return `undefined` if no page has been allocated already
*/
get(pageNumber: number, noAllocate?: false): Page;
get(pageNumber: number, noAllocate: true): Page | undefined;
/**
* Explicitly set the buffer for a page.
*/
set(pageNumber: number, buffer: Buffer): void;
/**
* Mark a page as updated.
*/
updated(page: Page): void;
/**
* Get the last page that was updated.
*/
lastUpdate(): Page | null;
/**
* Concat all pages allocated pages into a single buffer.
*/
toBuffer(): Buffer;
}
interface Page {
offset: number;
buffer: Buffer;
}
}

View File

@@ -0,0 +1,17 @@
import Pager = require('memory-pager');
const pages = new Pager(1024);
new Pager();
Pager(1024);
Pager();
const page = pages.get(10);
page; // $ExpectType Page
page.offset; // $ExpectType number
page.buffer; // $ExpectType Buffer
pages.get(10, false); // $ExpectType Page
pages.get(10, true); // $ExpectType Page | undefined
pages.set(10, new Buffer(10));
pages.updated(page);
pages.lastUpdate(); // $ExpectType Page | null
pages.toBuffer(); // $ExpectType Buffer

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"memory-pager-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

22
types/micro-events/index.d.ts vendored Normal file
View File

@@ -0,0 +1,22 @@
// Type definitions for micro-events 1.0
// Project: https://github.com/alexanderGugel/micro-events
// Definitions by: Alexander Sychev <https://github.com/AlexanderSychev>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/** Event emitter class */
declare class MicroEventEmitter {
/** Max listeners count */
maxListeners: number;
/** Attach listener */
on(type: string, handler: MicroEventEmitter.EventHandler): MicroEventEmitter;
/** Detach listener */
off(type: string, handler?: MicroEventEmitter.EventHandler): MicroEventEmitter;
/** Trigger event */
emit(type: string, ...arguments: any[]): MicroEventEmitter;
}
declare namespace MicroEventEmitter {
/** Event handler function signature */
type EventHandler = (...args: any[]) => any;
}
export = MicroEventEmitter;

View File

@@ -0,0 +1,13 @@
import * as EventEmitter from "micro-events";
const myEventEmitter = new EventEmitter();
myEventEmitter.maxListeners; // $ExpectType number
const listener = (first: string) => {};
myEventEmitter.on('foo', listener); // $ExpectType MicroEventEmitter
myEventEmitter.emit('foo', 'bar'); // $ExpectType MicroEventEmitter
myEventEmitter.off('foo', listener); // $ExpectType MicroEventEmitter

View File

@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"micro-events-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -1,6 +1,8 @@
// Type definitions for moment-timezone.js 0.5
// Project: http://momentjs.com/timezone/
// Definitions by: Michel Salib <https://github.com/michelsalib>, Alan Brazil Lins <https://github.com/alanblins>
// Definitions by: Michel Salib <https://github.com/michelsalib>
// Alan Brazil Lins <https://github.com/alanblins>
// Agustin Carrasco <https://github.com/asermax>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import moment = require('moment');
@@ -53,7 +55,7 @@ declare module "moment" {
names(): string[];
guess(ignoreCache?: boolean): string;
setDefault(timezone: string): MomentTimezone;
setDefault(timezone?: string): MomentTimezone;
}
interface Moment {

View File

@@ -77,6 +77,8 @@ moment.tz.names();
moment.tz.setDefault('America/Los_Angeles');
moment.tz.setDefault();
moment.tz.guess();
moment.tz.guess(true);

View File

@@ -5,7 +5,7 @@
declare module 'murmurhash3js' {
export module x86 {
function hash32(val: string, seed?: number): string;
function hash32(val: string, seed?: number): number;
function hash128(val: string, seed?: number): string;
}

17
types/nedb/index.d.ts vendored
View File

@@ -5,10 +5,14 @@
// Alejandro Fernandez Haro <https://github.com/afharo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { EventEmitter } from 'events';
export = Nedb;
export as namespace Nedb;
declare class Nedb {
declare class Nedb extends EventEmitter {
constructor(pathOrOptions?: string | Nedb.DataStoreOptions);
persistence: Nedb.Persistence;
@@ -153,6 +157,17 @@ declare class Nedb {
*/
remove(query: any, options: Nedb.RemoveOptions, cb?: (err: Error, n: number) => void): void;
remove(query: any, cb?: (err: Error, n: number) => void): void;
addListener(event: 'compaction.done', listener: () => void): this;
on(event: 'compaction.done', listener: () => void): this;
once(event: 'compaction.done', listener: () => void): this;
prependListener(event: 'compaction.done', listener: () => void): this;
prependOnceListener(event: 'compaction.done', listener: () => void): this;
removeListener(event: 'compaction.done', listener: () => void): this;
off(event: 'compaction.done', listener: () => void): this;
listeners(event: 'compaction.done'): Array<() => void>;
rawListeners(event: 'compaction.done'): Array<() => void>;
listenerCount(type: 'compaction.done'): number;
}
declare namespace Nedb {

View File

@@ -514,3 +514,14 @@ db.insert({ somefield: 'nedb' }, (err: Error) => {
// Remove index on field somefield
db.removeIndex('somefield', (err: Error) => {
});
db.addListener("compaction.done", () => {});
db.on("compaction.done", () => {});
db.once("compaction.done", () => {});
db.prependListener("compaction.done", () => {});
db.prependOnceListener("compaction.done", () => {});
db.removeListener("compaction.done", () => {});
db.off("compaction.done", () => {});
db.listeners("compaction.done"); // $ExpectType (() => void)[]
db.rawListeners("compaction.done"); // $ExpectType (() => void)[]
db.listenerCount("compaction.done"); // $ExpectType number

View File

@@ -1,7 +1,8 @@
// Type definitions for node-rsa 0.4
// Type definitions for node-rsa 1.0
// Project: https://github.com/rzcoder/node-rsa
// Definitions by: Ali Taheri <https://github.com/alitaheri>
// Christian Moniz <https://github.com/xm>
// Florian Keller <https://github.com/ffflorian>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -27,12 +28,12 @@ declare class NodeRSA {
* @param bits Key size in bits. 2048 by default.
* @param exponent public exponent. 65537 by default.
*/
generateKeyPair(bits?: number, exponent?: number): void;
generateKeyPair(bits?: number, exponent?: number): NodeRSA;
/**
* Import key from PEM string, PEM/DER Buffer or components.
*/
importKey(key: NodeRSA.Key, format?: NodeRSA.Format): void;
importKey(key: NodeRSA.Key, format?: NodeRSA.Format): NodeRSA;
/**
* Export key to PEM string, PEM/DER Buffer or components.
@@ -120,8 +121,7 @@ declare namespace NodeRSA {
type HashingAlgorithm =
| 'ripemd160'
| 'md4' | 'md5'
| 'sha' | 'sha1'
| 'sha224' | 'sha256' | 'sha384' | 'sha512';
| 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512';
type SigningScheme = 'pkcs1' | 'pss';

View File

@@ -1,249 +1,141 @@
// Type definitions for objectPath v0.9.x
// Type definitions for objectPath 0.11
// Project: https://github.com/mariocasciaro/object-path
// Definitions by: Paulo Cesar <https://github.com/pocesar>
// BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
declare var objectPath: ObjectPathGlobal.IObjectPathStatic;
declare const objectPath: objectPath.ObjectPathStatic & {
withInheritedProps: objectPath.ObjectPathStatic;
create(options?: objectPath.Options): objectPath.ObjectPathStatic;
};
declare namespace ObjectPathGlobal {
declare namespace objectPath {
interface Options {
includeInheritedProps?: boolean;
}
type IPath = Array<number|string>|number|string;
type IMultiArray = Array<IPath>;
type Path = Array<number | string> | number | string;
interface IObjectPathStatic {
interface ObjectPathStatic {
/**
* Binds an object
*/
<T extends {}>(object: T): IObjectPathBound<T>;
/*======== Del =========*/
<T extends object>(object: T): ObjectPathBound<T>;
/**
* Deletes a member from object or array
* @param {object} object
* @param {string[]|string} path
* @return object
*/
del<T extends {}>(object: T, path: IPath): T;
/**
* @see objectPath.del
*/
del<T extends {}>(object: T):T;
/**
* @see objectPath.del
*/
del():void;
del(object: object, path: Path): { [key: string]: any };
/*======== Has =========*/
/**
* Tests path existence
* @param {object} object
* @param {string[]|string} path
* @return object
*/
has<T extends {}>(object: T, path: IPath): boolean;
/**
* @see objectPath.has
*/
has<T extends {}>(object: T): boolean;
/**
* @see objectPath.has
*/
has(): boolean;
has(object: object, path: Path): boolean;
/*======== Get =========*/
/**
* Get a path from an object
* @param {object} object
* @param {string|string[]|number|number[]} path
* @param {*} [defaultValue=undefined]
*/
get<T extends {}, TResult>(object: T, path: IPath, defaultValue?: TResult): TResult;
/**
* @see objectPath.get
*/
get<T extends {}>(object: T): T;
/**
* @see objectPath.get
*/
get():void;
get(object: object, path: Path): any;
get<TResult>(object: object, path: Path, defaultValue: TResult): TResult;
/*======== Set =========*/
/**
* Set a path to a value
* @param {object} object
* @param {string|string[]|number|number[]} path
* @param {*} value
* @param {boolean} [doNotReplace=false]
* @return Any existing value on the path if any
*/
set<T extends {}, TExisting>(object: T, path: IPath, value: any, doNotReplace?:boolean): TExisting;
/**
* @see objectPath.set
*/
set<T extends {}>(object: T): T;
/**
* @see objectPath.set
*/
set():void;
set<TResult = any>(
object: object,
path: Path,
value: TResult,
doNotReplace?: boolean
): TResult | undefined;
/*======== Push =========*/
/**
* Create (if path isn't an array) and push the value to it. Can push unlimited number of values
* @param {object} object
*/
push<T extends {}>(object: T, path: IPath, ...args:any[]):void;
/**
* @see objectPath.push
*/
push():void;
push(object: object, path: Path, ...items: any[]): void;
/*======== Coalesce =========*/
/**
* Get the first non undefined property
* @param {object} object
* @param {string[]|string[][]|number[]|number[][]} paths
* @param {*} defaultValue
* @return {*}
*/
coalesce<T extends {}, TResult>(object: T, paths: IMultiArray, defaultValue?: TResult):TResult;
coalesce<TResult>(object: object, paths: Path | Path[], defaultValue: TResult): TResult;
coalesce<TResult = any>(
object: object,
paths: Path | Path[],
defaultValue?: TResult
): TResult | undefined;
/*======== Empty =========*/
/**
* Empty a path. Arrays are set to length 0, objects have all elements deleted, strings
* are set to empty, numbers to 0, everything else is set to null
* @param {object} object
* @param {string|string[]|number[]} path
*/
empty<T extends {}, TResult>(object: T, path: IPath):TResult;
/**
* @see objectPath.empty
*/
empty<T extends {}>(object: T):T;
/**
* @see objectPath.empty
*/
empty():void;
empty(object: object, path: Path): any;
/*======== EnsureExists =========*/
/**
* Set a value if it doesn't exist, do nothing if it does
* @param {object} object
* @param {string|string[]|number|number[]} path
*/
ensureExists<T extends {}, TExisting>(object: T, path: IPath, value: any):TExisting;
/**
* @see objectPath.ensureExists
*/
ensureExists<T extends {}>(object: T): T;
/**
* @see objectPath.ensureExists
*/
ensureExists():void;
ensureExists<TResult>(object: object, path: Path, defaultValue: TResult): TResult;
ensureExists<TResult = any>(
object: object,
path: Path,
defaultValue?: TResult
): TResult | undefined;
/*======== Insert =========*/
/**
* Insert an item in an array path
* @param {object} object
* @param {string|string[]|number|number[]} path
* @param {*} value
* @param {number} [at=0]
*/
insert<T extends {}>(object: T, path: IPath, value: any, at?: number):void;
insert(object: object, path: Path, value: any, at?: number): void;
}
interface IObjectPathBound<T extends {}> {
/*======== Del =========*/
/**
* @see objectPath.ensureExists
*/
del(path: IPath): T;
interface ObjectPathBound<T extends object> {
/**
* @see objectPath.del
*/
del(): T;
del(path: Path): { [key: string]: any };
/*======== Has =========*/
/**
* @see objectPath.ensureExists
*/
has(path: IPath): boolean;
/**
* @see objectPath.has
*/
has(): boolean;
has(path: Path): boolean;
/*======== Get =========*/
/**
* @see objectPath.ensureExists
*/
get<TResult>(path: IPath, defaultValue?: TResult): TResult;
/**
* @see objectPath.get
*/
get(): T;
get(path: Path): any;
get<TResult>(path: Path, defaultValue: TResult): TResult;
/*======== Set =========*/
/**
* @see objectPath.ensureExists
*/
set<TExisting>(path: IPath, value: any, doNotReplace?:boolean): TExisting;
/**
* @see objectPath.set
*/
set(): T;
set<TResult = any>(path: Path, value: TResult, doNotReplace?: boolean): TResult | undefined;
/*======== Push =========*/
/**
* @see objectPath.ensureExists
*/
push(path: IPath, ...args:any[]):void;
/**
* @see objectPath.push
*/
push():void;
push(path: Path, ...items: any[]): void;
/*======== Coalesce =========*/
/**
* @see objectPath.ensureExists
* @see objectPath.coalesce
*/
coalesce<TResult>(paths: IMultiArray, defaultValue?: TResult):TResult;
coalesce<TResult>(paths: Path | Path[], defaultValue: TResult): TResult;
coalesce<TResult = any>(paths: Path | Path[], defaultValue?: TResult): TResult | undefined;
/*======== Empty =========*/
/**
* @see objectPath.ensureExists
*/
empty(path: IPath):T;
/**
* @see objectPath.empty
*/
empty():T;
empty(path: Path): any;
/*======== EnsureExists =========*/
/**
* @see objectPath.ensureExists
*/
ensureExists<TExisting>(path: IPath, value: any):TExisting;
/**
* @see objectPath.ensureExists
*/
ensureExists(): T;
ensureExists<TResult>(path: Path, defaultValue: TResult): TResult;
ensureExists<TResult = any>(path: Path, defaultValue?: TResult): TResult | undefined;
/*======== Insert =========*/
/**
* @see objectPath.insert
*/
insert(path: IPath, value: any, at?: number):void;
insert(path: Path, value: any, at?: number): void;
}
}
// browser version
declare module 'objectPath' {
export = objectPath;
}
// node version
declare module 'object-path' {
export = objectPath;
}
export = objectPath;

View File

@@ -1,111 +1,57 @@
import objectPath = require('object-path');
import ObjectPath = require('object-path');
var
object = {
const object = {
one: 1,
two: {
three: 3,
four: ['4']
}
},
array: any[] = [],
Null:any = null;
three: 3,
four: ['4'],
},
};
var obj = ObjectPath(object);
objectPath.get(object, []);
objectPath.get(object, [1, 2]);
objectPath.get(object, [1, '2']);
objectPath.get(object, 1);
objectPath.get(object, '1');
obj.del(array);
obj.coalesce([1,2]);
obj.ensureExists('1.2', 1);
obj.push(1, 'value');
obj.get(array);
obj.set(array, 'value');
obj.insert(1, 10);
objectPath.del(object, 'a'); // $ExpectType { [key: string]: any; }
objectPath.has(object, 'a'); // $ExpectType boolean
objectPath.get(object, 'a'); // $ExpectType any
objectPath.get(object, 'a', 1); // $ExpectType 1
objectPath.set(object, 'a', 1); // $ExpectType 1 | undefined
objectPath.set(object, 'a', 1, true); // $ExpectType 1 | undefined
objectPath.push(object, 'a', 1, 2); // $ExpectType void
objectPath.coalesce(object, 'a', 1); // $ExpectType 1
objectPath.coalesce(object, 'a'); // $ExpectType any
objectPath.coalesce(object, [['a']]); // $ExpectType any
objectPath.coalesce<number>(object, 'a'); // $ExpectType number | undefined
objectPath.empty(object, 'a'); // $ExpectType any
objectPath.ensureExists(object, 'a', 1); // $ExpectType 1
objectPath.ensureExists(object, 'a'); // $ExpectType any
objectPath.ensureExists<number>(object, 'a'); // $ExpectType number | undefined
objectPath.insert(object, 'a', 1); // $ExpectType void
objectPath.insert(object, 'a', 1, 2); // $ExpectType void
objectPath.del(object, array) === object;
objectPath.del(object, [1,2]) === object;
objectPath.del(object, [1,'2']) === object;
objectPath.del(object, 1) === object;
objectPath.del(object, '1') === object;
objectPath.del(object) === object;
obj.del() === object;
const obj = objectPath(object);
objectPath.has(object, ['1','2','3']) === true;
objectPath.has(object, ['1.2.3']) === false;
objectPath.has(object, [1,2,3]) === true;
objectPath.has(object, [1,'2',3]) === true;
objectPath.has(object, 1) === false;
objectPath.has(object, '1') === false;
objectPath.has() === false;
obj.del('a'); // $ExpectType { [key: string]: any; }
obj.has('a'); // $ExpectType boolean
obj.get('a'); // $ExpectType any
obj.get('a', 1); // $ExpectType 1
obj.set('a', 1); // $ExpectType 1 | undefined
obj.set('a', 1, true); // $ExpectType 1 | undefined
obj.push('a', 1, 2); // $ExpectType void
obj.coalesce('a', 1); // $ExpectType 1
obj.coalesce('a'); // $ExpectType any
obj.coalesce([['a']]); // $ExpectType any
obj.coalesce<number>('a'); // $ExpectType number | undefined
obj.empty('a'); // $ExpectType any
obj.ensureExists('a', 1); // $ExpectType 1
obj.ensureExists('a'); // $ExpectType any
obj.ensureExists<number>('a'); // $ExpectType number | undefined
obj.insert('a', 1); // $ExpectType void
obj.insert('a', 1, 2); // $ExpectType void
objectPath.del() === void 0;
objectPath.del(object, ['1','2','3']);
objectPath.del(object, [1,2,3]);
objectPath.del(object, [1,'2',3]);
objectPath.del(object, 1);
objectPath.del(object, 'one').one === 1;
obj.del('one').one === 1;
objectPath.coalesce(object, ['1','2']) === void 0;
objectPath.coalesce(object, ['1',['2','1']]) === void 0;
objectPath.coalesce(object, ['1',['2','1']], 1) === 1;
objectPath.coalesce(object, [1,1], 1) === 1;
objectPath.coalesce(object, [1,'1'], 1) === 1;
objectPath.coalesce(object, [1,[1,1],'1',[1,'1']], 1) === 1;
obj.coalesce([1,[1,1],'1',['1',1]], 1) === 1;
objectPath.ensureExists(object, '1.2', 2);
objectPath.ensureExists(object, 1, 2);
objectPath.ensureExists(object, [1,2], 2);
objectPath.ensureExists(object, ['1','2'], 2);
objectPath.ensureExists(object, ['1',2], 2);
objectPath.ensureExists<typeof object, number>(object, ['1','2'], 2) === 3;
objectPath.ensureExists<typeof object, any[][]>(object, ['1','2'], 2) === [[]];
obj.ensureExists<any[][]>(['1','2'], 2) === [[]];
objectPath.push(object, 1, 1,2,3,4);
objectPath.push(object, 1, 1,'2', 3, false);
objectPath.push(object, 'one.four', 1,'2', 3, false);
objectPath.push(object, ['one','two'], [1,'2', 3, false]);
objectPath.push(object, [1, 'two'], [1,'2', 3, false]);
obj.push(['one','two'], [1,'2', 3, false]);
obj.push(['one', 2], [1,'2', 3, false]);
objectPath.get(array) === array;
objectPath.get(Null) === Null;
objectPath.get() === void 0;
objectPath.get(object, 'one') === 1;
objectPath.get(object, ['two','three']) === 3;
objectPath.get(object, ['three'], 3) === 3;
objectPath.get(object, 'three', 3) === 3;
objectPath.get(object, 0, 3) === 3;
objectPath.get(object, 0, '3') === '3';
objectPath.get<typeof object, string[]>(object, 0, ['1','2']) === ['1','2'];
objectPath.get<typeof object, number>(object, 0) === 10;
objectPath.get<typeof object, number>(object, 0) === 10;
obj.get(0, 10) === 10;
objectPath.set(object, '1.2', true);
objectPath.set(object, ['1','2'], true);
objectPath.set(object, [1, 2], true);
objectPath.set(object, [1, '2'], true);
objectPath.set(object, '1.2', true, true);
objectPath.set(object, '1.2', true, false);
objectPath.set<typeof object, string[]>(object, '1.2', true, false) === ['string'];
objectPath.set<typeof object, typeof object>(object, '1.2', true, false) === object;
obj.set<typeof object>('1.2', true, false) === object;
obj.set<typeof object>(['1','2'], true, false) === object;
obj.set<typeof object>(['1', 2], true, false) === object;
objectPath.insert(object, '1.2', 1);
objectPath.insert(object, ['1','2'], 1);
objectPath.insert(object, 1, 1);
objectPath.insert(object, [1,2], 1);
objectPath.insert(object, '1.2', 1, 2);
objectPath.insert(object, ['1.2'], 1, 6);
objectPath.insert(object, ['1',2], 1, 6);
obj.insert(['1.2'], 1, 6);
obj.insert(1, 1, 6);
obj.insert(['1',1], 1, 6);
obj.insert('1', 1, 6);
objectPath.withInheritedProps; // $ExpectType ObjectPathStatic
objectPath.create(); // $ExpectType ObjectPathStatic
objectPath.create({ includeInheritedProps: true }); // $ExpectType ObjectPathStatic

View File

@@ -6,7 +6,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
@@ -20,4 +20,4 @@
"index.d.ts",
"object-path-tests.ts"
]
}
}

View File

@@ -1,79 +1,3 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
"extends": "dtslint/dt.json"
}

8
types/one-time/index.d.ts vendored Normal file
View File

@@ -0,0 +1,8 @@
// Type definitions for one-time 0.0
// Project: https://github.com/unshiftio/one-time
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = oneTime;
declare function oneTime<TFn extends Function>(fn: TFn): TFn; // tslint:disable-line:ban-types

View File

@@ -0,0 +1,7 @@
import one = require('one-time');
const fn = (foo: boolean) => {
return 'bar';
};
one(fn); // $ExpectType (foo: boolean) => string

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"one-time-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -4,6 +4,7 @@
// Errietta Kostala <https://github.com/errietta>
// Daniel Montesinos <https://github.com/damonpam>
// Carlos Villavicencio <https://github.com/po5i>
// Eric Camellini <https://github.com/ecamellini>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -27,6 +28,7 @@ export interface EncryptOptions {
sessionKey?: SessionKey,
compression?: enums.compression,
armor?: boolean,
streaming?: 'web' | 'node' | false
detached?: boolean,
signature?: Signature,
returnSessionKey?: boolean,
@@ -39,6 +41,8 @@ export interface EncryptOptions {
export interface EncryptedMessage {
data?: string,
message?: message.Message,
signature?: string | ReadableStream | Signature // TODO add NodeStream
sessionKey?: SessionKey
}
export interface DecryptOptions {
@@ -48,17 +52,35 @@ export interface DecryptOptions {
sessionKeys?: SessionKey | SessionKey[],
publicKeys?: key.Key | key.Key[],
format?: string,
streaming?: 'web' | 'node' | false,
signature?: Signature,
date?: Date,
}
export interface SignOptions {
message: message.Message,
privateKeys?: key.Key | key.Key[],
armor?: boolean,
streaming?: 'web' | 'node' | false,
detached?: boolean
date?: Date,
fromUserIds?: UserId[]
}
export interface SignedMessage {
signature?: string | ReadableStream | Signature, // TODO add NodeStream
data?: string | ReadableStream, // TODO add NodeStream
message?: message.Message
}
export interface KeyContainer {
key: key.Key,
}
export interface KeyPair extends KeyContainer {
privateKeyArmored: string,
publicKeyArmored: string
publicKeyArmored: string,
revocationCertificate: string
}
export interface KeyOptions {
@@ -77,13 +99,27 @@ export interface Keyid {
export interface Signature {
keyid: Keyid,
valid: boolean
valid: boolean,
verified?: boolean
}
export interface VerifyOptions {
message: message.Message,
publicKeys: key.Key | key.Key[],
streaming?: 'web' | 'node' | false,
signature?: Signature,
date?: Date
}
export interface VerifiedMessage {
data: Uint8Array | string,
data: Uint8Array | string | ReadableStream, // TODO add NodeStream
signatures: Array<Signature>,
filename: string,
}
export interface DecryptedMessage {
data: Uint8Array | string | ReadableStream, // TODO add NodeStream
signatures: Array<Signature>,
filename: string
}
export interface OpenPGPWorker {
@@ -98,7 +134,7 @@ export interface WorkerOptions {
path?: string,
n?: number,
workers?: OpenPGPWorker[],
config?: any,
config?: any
}
export class AsyncProxy {
@@ -140,16 +176,23 @@ export function destroyWorker(): void;
* @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String }
* @param {module:enums.compression} compression (optional) which compression algorithm to compress the message with, defaults to what is specified in config
* @param {Boolean} armor (optional) if the return values should be ascii armored or the message/signature objects
* @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
* @param {Boolean} detached (optional) if the signature should be detached (if true, signature will be added to returned object)
* @param {Signature} signature (optional) a detached signature to add to the encrypted message
* @param {Boolean} returnSessionKey (optional) if the unencrypted session key should be added to returned object
* @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs
* @param {Date} date (optional) override the creation date of the message and the message signature
* @param {Date} date (optional) override the creation date of the message signature
* @param {Object} fromUserId (optional) user ID to sign with, e.g. { name:'Steve Sender', email:'steve@openpgp.org' }
* @param {Object} toUserId (optional) user ID to encrypt for, e.g. { name:'Robert Receiver', email:'robert@openpgp.org' }
* @returns {Promise<Object>} encrypted (and optionally signed message) in the form:
* {data: ASCII armored message if 'armor' is true,
* message: full Message object if 'armor' is false, signature: detached signature if 'detached' is true}
* @returns {Promise<Object>} Object containing encrypted (and optionally signed) message in the form:
*
* {
* data: String|ReadableStream<String>|NodeStream, (if `armor` was true, the default)
* message: Message, (if `armor` was false)
* signature: String|ReadableStream<String>|NodeStream, (if `detached` was true and `armor` was true)
* signature: Signature (if `detached` was true and `armor` was false)
* sessionKey: { data, algorithm, aeadAlgorithm } (if `returnSessionKey` was true)
* }
* @async
* @static
*/
@@ -164,14 +207,79 @@ export function encrypt(options: EncryptOptions): Promise<EncryptedMessage>;
* @param {Object|Array<Object>} sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String }
* @param {Key|Array<Key>} publicKeys (optional) array of public keys or single key, to verify signatures
* @param {String} format (optional) return data format either as 'utf8' or 'binary'
* @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
* @param {Signature} signature (optional) detached signature for verification
* @param {Date} date (optional) use the given date for verification instead of the current time
* @returns {Promise<Object>} decrypted and verified message in the form:
* { data:Uint8Array|String, filename:String, signatures:[{ keyid:String, valid:Boolean }] }
* @returns {Promise<Object>} Object containing decrypted and verified message in the form:
*
* {
* data: String|ReadableStream<String>|NodeStream, (if format was 'utf8', the default)
* data: Uint8Array|ReadableStream<Uint8Array>|NodeStream, (if format was 'binary')
* filename: String,
* signatures: [
* {
* keyid: module:type/keyid,
* verified: Promise<Boolean>,
* valid: Boolean (if streaming was false)
* }, ...
* ]
* }
* @async
* @static
*/
export function decrypt(options: DecryptOptions): Promise<VerifiedMessage>;
export function decrypt(options: DecryptOptions): Promise<DecryptedMessage>;
/**
* Signs a cleartext message.
* @param {CleartextMessage|Message} message (cleartext) message to be signed
* @param {Key|Array<Key>} privateKeys array of keys or single key with decrypted secret key data to sign cleartext
* @param {Boolean} armor (optional) if the return value should be ascii armored or the message object
* @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
* @param {Boolean} detached (optional) if the return value should contain a detached signature
* @param {Date} date (optional) override the creation date of the signature
* @param {Array} fromUserIds (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
* @returns {Promise<Object>} Object containing signed message in the form:
*
* {
* data: String|ReadableStream<String>|NodeStream, (if `armor` was true, the default)
* message: Message (if `armor` was false)
* }
*
* Or, if `detached` was true:
*
* {
* signature: String|ReadableStream<String>|NodeStream, (if `armor` was true, the default)
* signature: Signature (if `armor` was false)
* }
* @async
* @static
*/
export function sign(options: SignOptions): Promise<SignedMessage>;
/**
* Verifies signatures of cleartext signed message
* @param {Key|Array<Key>} publicKeys array of publicKeys or single key, to verify signatures
* @param {CleartextMessage|Message} message (cleartext) message object with signatures
* @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
* @param {Signature} signature (optional) detached signature for verification
* @param {Date} date (optional) use the given date for verification instead of the current time
* @returns {Promise<Object>} Object containing verified message in the form:
*
* {
* data: String|ReadableStream<String>|NodeStream, (if `message` was a CleartextMessage)
* data: Uint8Array|ReadableStream<Uint8Array>|NodeStream, (if `message` was a Message)
* signatures: [
* {
* keyid: module:type/keyid,
* verified: Promise<Boolean>,
* valid: Boolean (if `streaming` was false)
* }, ...
* ]
* }
* @async
* @static
*/
export function verify(options: VerifyOptions): Promise<VerifiedMessage>;
/**
* Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type.
@@ -186,7 +294,7 @@ export function decrypt(options: DecryptOptions): Promise<VerifiedMessage>;
* @param {Array<Object>} subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
* sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
* @returns {Promise<Object>} The generated key object in the form:
* { key:Key, privateKeyArmored:String, publicKeyArmored:String }
* { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String }
* @async
* @static
*/
@@ -198,8 +306,9 @@ export function generateKey(options: KeyOptions): Promise<KeyPair>;
* @param {Array<Object>} userIds array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }]
* @param {String} passphrase (optional) The passphrase used to encrypt the resulting private key
* @param {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires
* @param {Boolean} revocationCertificate (optional) Whether the returned object should include a revocation certificate to revoke the public key
* @returns {Promise<Object>} The generated key object in the form:
* { key:Key, privateKeyArmored:String, publicKeyArmored:String }
* { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String }
* @async
* @static
*/
@@ -208,6 +317,29 @@ export function reformatKey(options: {
userIds?: UserId[],
passphrase?: string,
keyExpirationTime?: number,
revocationCertificate?: boolean
}): Promise<KeyPair>;
/**
* Revokes a key. Requires either a private key or a revocation certificate.
* If a revocation certificate is passed, the reasonForRevocation parameters will be ignored.
* @param {Key} key (optional) public or private key to revoke
* @param {String} revocationCertificate (optional) revocation certificate to revoke the key with
* @param {Object} reasonForRevocation (optional) object indicating the reason for revocation
* @param {module:enums.reasonForRevocation} reasonForRevocation.flag (optional) flag indicating the reason for revocation
* @param {String} reasonForRevocation.string (optional) string explaining the reason for revocation
* @returns {Promise<Object>} The revoked key object in the form:
* { privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String }
* (if private key is passed) or { publicKey:Key, publicKeyArmored:String } (otherwise)
* @static
*/
export function revokeKey(options: {
key?: key.Key,
revocationCertificate?: string
reasonForRevocation?: {
flag: enums.reasonForRevocation,
'string': string
},
}): Promise<KeyPair>;
/**
@@ -222,11 +354,20 @@ export function decryptKey(options: {
passphrase?: string | string[],
}): Promise<KeyContainer>;
/**
* Lock a private key with your passphrase.
* @param {Key} privateKey the private key that is to be decrypted
* @param {String|Array<String>} passphrase the user's passphrase(s) chosen during key generation
* @returns {Promise<Object>} the locked key object in the form: { key:Key }
* @async
*/
export function encryptKey(options: {
privateKey: key.Key,
passphrase?: string
passphrase?: string | string[],
}): Promise<KeyContainer>;
// TODO add typings for encryptSessionKey and decryptSessionKeys
export namespace armor {
/** Armor an OpenPGP binary packet block
@@ -485,6 +626,14 @@ export namespace enums {
valid,
no_self_cert
}
enum reasonForRevocation {
no_reason,
key_superseded,
key_compromised,
key_retired,
userid_invalid
}
}
export namespace key {

View File

@@ -110,6 +110,31 @@ openpgp.initWorker({ path:'openpgp.worker.js' });
})();
(async () => {
const publicKey = (await openpgp.key.readArmored(spubkey))
const privateKey = (await openpgp.key.readArmored(sprivkey))
const signOptions: openpgp.SignOptions = {
message: openpgp.message.fromText('hello world'),
privateKeys: privateKey.keys,
detached: true
};
const signed = await openpgp.sign(signOptions);
const signature = signed.signature as openpgp.Signature;
const message = signed.message;
const verifyOptions: openpgp.VerifyOptions = {
message,
signature,
publicKeys: publicKey.keys
};
let verified = await openpgp.verify(verifyOptions);
return verified.signatures[0].valid;
})();
// Open PGP Tests

View File

@@ -4,6 +4,7 @@
// Errietta Kostala <https://github.com/errietta>
// Daniel Montesinos <https://github.com/damonpam>
// Carlos Villavicencio <https://github.com/po5i>
// Eric Camellini <https://github.com/ecamellini>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace openpgp;
@@ -26,6 +27,7 @@ export interface EncryptOptions {
sessionKey?: SessionKey,
compression?: enums.compression,
armor?: boolean,
streaming?: 'web' | 'node' | false
detached?: boolean,
signature?: Signature,
returnSessionKey?: boolean,
@@ -38,6 +40,8 @@ export interface EncryptOptions {
export interface EncryptedMessage {
data?: string,
message?: message.Message,
signature?: string | ReadableStream<string> | Signature // TODO add NodeStream
sessionKey?: SessionKey
}
export interface DecryptOptions {
@@ -47,17 +51,35 @@ export interface DecryptOptions {
sessionKeys?: SessionKey | SessionKey[],
publicKeys?: key.Key | key.Key[],
format?: string,
streaming?: 'web' | 'node' | false,
signature?: Signature,
date?: Date,
}
export interface SignOptions {
message: message.Message,
privateKeys?: key.Key | key.Key[],
armor?: boolean,
streaming?: 'web' | 'node' | false,
detached?: boolean
date?: Date,
fromUserIds?: UserId[]
}
export interface SignedMessage {
signature?: string | ReadableStream<string> | Signature, // TODO add NodeStream
data?: string | ReadableStream<string>, // TODO add NodeStream
message?: message.Message
}
export interface KeyContainer {
key: key.Key,
}
export interface KeyPair extends KeyContainer {
privateKeyArmored: string,
publicKeyArmored: string
publicKeyArmored: string,
revocationCertificate: string
}
export interface KeyOptions {
@@ -76,13 +98,27 @@ export interface Keyid {
export interface Signature {
keyid: Keyid,
valid: boolean
valid: boolean,
verified?: boolean
}
export interface VerifyOptions {
message: message.Message,
publicKeys: key.Key | key.Key[],
streaming?: 'web' | 'node' | false,
signature?: Signature,
date?: Date
}
export interface VerifiedMessage {
data: Uint8Array | string,
data: Uint8Array | string | ReadableStream<string> | ReadableStream<Uint8Array>, // TODO add NodeStream
signatures: Array<Signature>,
filename: string,
}
export interface DecryptedMessage {
data: Uint8Array | string | ReadableStream<string> | ReadableStream<Uint8Array>, // TODO add NodeStream
signatures: Array<Signature>,
filename: string
}
export interface OpenPGPWorker {
@@ -97,7 +133,7 @@ export interface WorkerOptions {
path?: string,
n?: number,
workers?: OpenPGPWorker[],
config?: any,
config?: any
}
export class AsyncProxy {
@@ -139,16 +175,23 @@ export function destroyWorker(): void;
* @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String }
* @param {module:enums.compression} compression (optional) which compression algorithm to compress the message with, defaults to what is specified in config
* @param {Boolean} armor (optional) if the return values should be ascii armored or the message/signature objects
* @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
* @param {Boolean} detached (optional) if the signature should be detached (if true, signature will be added to returned object)
* @param {Signature} signature (optional) a detached signature to add to the encrypted message
* @param {Boolean} returnSessionKey (optional) if the unencrypted session key should be added to returned object
* @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs
* @param {Date} date (optional) override the creation date of the message and the message signature
* @param {Date} date (optional) override the creation date of the message signature
* @param {Object} fromUserId (optional) user ID to sign with, e.g. { name:'Steve Sender', email:'steve@openpgp.org' }
* @param {Object} toUserId (optional) user ID to encrypt for, e.g. { name:'Robert Receiver', email:'robert@openpgp.org' }
* @returns {Promise<Object>} encrypted (and optionally signed message) in the form:
* {data: ASCII armored message if 'armor' is true,
* message: full Message object if 'armor' is false, signature: detached signature if 'detached' is true}
* @returns {Promise<Object>} Object containing encrypted (and optionally signed) message in the form:
*
* {
* data: String|ReadableStream<String>|NodeStream, (if `armor` was true, the default)
* message: Message, (if `armor` was false)
* signature: String|ReadableStream<String>|NodeStream, (if `detached` was true and `armor` was true)
* signature: Signature (if `detached` was true and `armor` was false)
* sessionKey: { data, algorithm, aeadAlgorithm } (if `returnSessionKey` was true)
* }
* @async
* @static
*/
@@ -163,14 +206,79 @@ export function encrypt(options: EncryptOptions): Promise<EncryptedMessage>;
* @param {Object|Array<Object>} sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String }
* @param {Key|Array<Key>} publicKeys (optional) array of public keys or single key, to verify signatures
* @param {String} format (optional) return data format either as 'utf8' or 'binary'
* @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
* @param {Signature} signature (optional) detached signature for verification
* @param {Date} date (optional) use the given date for verification instead of the current time
* @returns {Promise<Object>} decrypted and verified message in the form:
* { data:Uint8Array|String, filename:String, signatures:[{ keyid:String, valid:Boolean }] }
* @returns {Promise<Object>} Object containing decrypted and verified message in the form:
*
* {
* data: String|ReadableStream<String>|NodeStream, (if format was 'utf8', the default)
* data: Uint8Array|ReadableStream<Uint8Array>|NodeStream, (if format was 'binary')
* filename: String,
* signatures: [
* {
* keyid: module:type/keyid,
* verified: Promise<Boolean>,
* valid: Boolean (if streaming was false)
* }, ...
* ]
* }
* @async
* @static
*/
export function decrypt(options: DecryptOptions): Promise<VerifiedMessage>;
export function decrypt(options: DecryptOptions): Promise<DecryptedMessage>;
/**
* Signs a cleartext message.
* @param {CleartextMessage|Message} message (cleartext) message to be signed
* @param {Key|Array<Key>} privateKeys array of keys or single key with decrypted secret key data to sign cleartext
* @param {Boolean} armor (optional) if the return value should be ascii armored or the message object
* @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
* @param {Boolean} detached (optional) if the return value should contain a detached signature
* @param {Date} date (optional) override the creation date of the signature
* @param {Array} fromUserIds (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
* @returns {Promise<Object>} Object containing signed message in the form:
*
* {
* data: String|ReadableStream<String>|NodeStream, (if `armor` was true, the default)
* message: Message (if `armor` was false)
* }
*
* Or, if `detached` was true:
*
* {
* signature: String|ReadableStream<String>|NodeStream, (if `armor` was true, the default)
* signature: Signature (if `armor` was false)
* }
* @async
* @static
*/
export function sign(options: SignOptions): Promise<SignedMessage>;
/**
* Verifies signatures of cleartext signed message
* @param {Key|Array<Key>} publicKeys array of publicKeys or single key, to verify signatures
* @param {CleartextMessage|Message} message (cleartext) message object with signatures
* @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
* @param {Signature} signature (optional) detached signature for verification
* @param {Date} date (optional) use the given date for verification instead of the current time
* @returns {Promise<Object>} Object containing verified message in the form:
*
* {
* data: String|ReadableStream<String>|NodeStream, (if `message` was a CleartextMessage)
* data: Uint8Array|ReadableStream<Uint8Array>|NodeStream, (if `message` was a Message)
* signatures: [
* {
* keyid: module:type/keyid,
* verified: Promise<Boolean>,
* valid: Boolean (if `streaming` was false)
* }, ...
* ]
* }
* @async
* @static
*/
export function verify(options: VerifyOptions): Promise<VerifiedMessage>;
/**
* Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type.
@@ -185,7 +293,7 @@ export function decrypt(options: DecryptOptions): Promise<VerifiedMessage>;
* @param {Array<Object>} subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
* sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
* @returns {Promise<Object>} The generated key object in the form:
* { key:Key, privateKeyArmored:String, publicKeyArmored:String }
* { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String }
* @async
* @static
*/
@@ -197,8 +305,9 @@ export function generateKey(options: KeyOptions): Promise<KeyPair>;
* @param {Array<Object>} userIds array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }]
* @param {String} passphrase (optional) The passphrase used to encrypt the resulting private key
* @param {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires
* @param {Boolean} revocationCertificate (optional) Whether the returned object should include a revocation certificate to revoke the public key
* @returns {Promise<Object>} The generated key object in the form:
* { key:Key, privateKeyArmored:String, publicKeyArmored:String }
* { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String }
* @async
* @static
*/
@@ -207,6 +316,29 @@ export function reformatKey(options: {
userIds?: UserId[],
passphrase?: string,
keyExpirationTime?: number,
revocationCertificate?: boolean
}): Promise<KeyPair>;
/**
* Revokes a key. Requires either a private key or a revocation certificate.
* If a revocation certificate is passed, the reasonForRevocation parameters will be ignored.
* @param {Key} key (optional) public or private key to revoke
* @param {String} revocationCertificate (optional) revocation certificate to revoke the key with
* @param {Object} reasonForRevocation (optional) object indicating the reason for revocation
* @param {module:enums.reasonForRevocation} reasonForRevocation.flag (optional) flag indicating the reason for revocation
* @param {String} reasonForRevocation.string (optional) string explaining the reason for revocation
* @returns {Promise<Object>} The revoked key object in the form:
* { privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String }
* (if private key is passed) or { publicKey:Key, publicKeyArmored:String } (otherwise)
* @static
*/
export function revokeKey(options: {
key?: key.Key,
revocationCertificate?: string
reasonForRevocation?: {
flag: enums.reasonForRevocation,
'string': string
},
}): Promise<KeyPair>;
/**
@@ -221,11 +353,20 @@ export function decryptKey(options: {
passphrase?: string | string[],
}): Promise<KeyContainer>;
/**
* Lock a private key with your passphrase.
* @param {Key} privateKey the private key that is to be decrypted
* @param {String|Array<String>} passphrase the user's passphrase(s) chosen during key generation
* @returns {Promise<Object>} the locked key object in the form: { key:Key }
* @async
*/
export function encryptKey(options: {
privateKey: key.Key,
passphrase?: string
passphrase?: string | string[],
}): Promise<KeyContainer>;
// TODO add typings for encryptSessionKey and decryptSessionKeys
export namespace armor {
/** Armor an OpenPGP binary packet block
@@ -484,6 +625,14 @@ export namespace enums {
valid,
no_self_cert
}
enum reasonForRevocation {
no_reason,
key_superseded,
key_compromised,
key_retired,
userid_invalid
}
}
export namespace key {

View File

@@ -109,6 +109,30 @@ openpgp.initWorker({ path:'openpgp.worker.js' });
return plain.data;
})();
(async () => {
const publicKey = (await openpgp.key.readArmored(spubkey))
const privateKey = (await openpgp.key.readArmored(sprivkey))
const signOptions: openpgp.SignOptions = {
message: openpgp.message.fromText('hello world'),
privateKeys: privateKey.keys,
detached: true
};
const signed = await openpgp.sign(signOptions);
const signature = signed.signature as openpgp.Signature;
const message = signed.message;
const verifyOptions: openpgp.VerifyOptions = {
message,
signature,
publicKeys: publicKey.keys
};
let verified = await openpgp.verify(verifyOptions);
return verified.signatures[0].valid;
})();
// Open PGP Tests

20
types/parse-passwd/index.d.ts vendored Normal file
View File

@@ -0,0 +1,20 @@
// Type definitions for parse-passwd 1.0
// Project: https://github.com/doowb/parse-passwd
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = parsePasswd;
declare function parsePasswd(passwdText: string): parsePasswd.PasswdEntry[];
declare namespace parsePasswd {
interface PasswdEntry {
username: string;
password: string;
uid: string;
gid: string;
gecos: string;
homedir: string;
shell: string;
}
}

View File

@@ -0,0 +1,14 @@
import parse = require('parse-passwd');
const entries = parse('doowb:*:123:123:Brian Woodward:/Users/doowb:/bin/bash');
entries; // $ExpectType PasswdEntry[]
const entry = entries[0];
entry.username; // $ExpectType string
entry.password; // $ExpectType string
entry.uid; // $ExpectType string
entry.gid; // $ExpectType string
entry.gecos; // $ExpectType string
entry.homedir; // $ExpectType string
entry.shell; // $ExpectType string

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