Merge branch 'master' into ali-oss

This commit is contained in:
ptrdu
2018-11-20 16:49:11 +08:00
3137 changed files with 552094 additions and 35394 deletions

556
.github/CODEOWNERS vendored

File diff suppressed because it is too large Load Diff

1
.gitignore vendored
View File

@@ -46,6 +46,7 @@ npm-debug.log
.settings/launch.json
.vs
.vscode
.history
# yarn
yarn.lock

1
.npmrc Normal file
View File

@@ -0,0 +1 @@
package-lock=false

View File

@@ -22,15 +22,15 @@ Este es el método preferido. Solo está disponible para usuarios TypeScript 2.0
npm install --save-dev @types/node
```
Los types deberían ser incluidos automaticamente por el compilador.
Los types deberían ser incluidos automáticamente por el compilador.
Vea más en el [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html).
Para un paquete NPM "foo", Estos `typings` estarán en "@types/foo".
Para un paquete NPM "foo", estos `typings` estarán en "@types/foo".
Si no puedes encontrar tu paquete, búscalo en [TypeSearch](https://microsoft.github.io/TypeSearch/).
Si aún no puedes encontrarlo, comprueba si el paquete ya [incluye](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) los typings.
Esto es provisto usualmente en el campo `"types"` o `"typings"` en el `package.json`,
o solo busca por cualquier archivo ".d.ts" en el paquete e incluyelo manualmente con un `/// <reference path="" />`.
o solo busca por cualquier archivo ".d.ts" en el paquete e inclúyelo manualmente con un `/// <reference path="" />`.
### Otros métodos
@@ -39,7 +39,7 @@ Estos pueden ser utilizados por TypeScript 1.0.
* [Typings](https://github.com/typings/typings)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use las alternativas preferidas, la publicación DT type de nuget ha sido desactivada)
* Descarguelo manualmente desde la `master` branch de este repositorio
* Descárguelo manualmente desde la `master` branch de este repositorio
Tal vez debas añadir manualmente las [referencias](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
@@ -88,7 +88,7 @@ Primero, haz un [fork](https://guides.github.com/activities/forking/) en este re
* `cd types/my-package-to-edit`
* Haz cambios. Recuerda editar las pruebas.
Si realiza cambios importantes, no olvide [actualizar una versión principal](#quiero-actualizar-un-paquete-a-una-nueva-versión-principal).
* También puede que quieras añadirte la sección "Definitions by" en el encabezado del paquete.
* También puede que quieras añadirle la sección "Definitions by" en el encabezado del paquete.
- Esto hará que seas notificado (a través de tu nombre de usuario en GitHub) cada vez que alguien haga un pull request o issue sobre el paquete.
- Haz esto añadiendo tu nombre al final de la línea, así como en `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
- O si hay más personas, puede ser multiline
@@ -109,7 +109,7 @@ Si no lo hace, puedes hacerlo en el comentario asociado con el PR.
Si eres el autor de la librería, o puedes hacer un pull request a la biblioteca, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) en vez de publicarlo en DefinitelyTyped.
Si estás agregando typings para un paquete NPM, crea un directorio con el mismo nombre.
Si el paquete al que le estás agregando typings no es para NPM, asegurate de que el nombre que escojas no genere problemas con el nombre del paquete en NPM.
Si el paquete al que le estás agregando typings no es para NPM, asegúrate de que el nombre que escojas no genere problemas con el nombre del paquete en NPM.
(Puedes usar `npm info foo` para verificar la existencia del paquete `foo`.)
Tu paquete debería tener esta estructura:
@@ -126,7 +126,7 @@ Ve todas las opciones en [dts-gen](https://github.com/Microsoft/dts-gen).
También puedes configurar el `tsconfig.json` para añadir nuevos archivos, para agregar un `"target": "es6"` (necesitado por las funciones asíncronas), para agregar a la `"lib"`, o para agregar la opción de compilación `"jsx"`.
Los miembros de DefinitelyTyped frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrian ralentizar el proceso.
Los miembros de DefinitelyTyped frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrían ralentizar el proceso.
Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
@@ -135,7 +135,7 @@ Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTy
* Primero, sigue el consejo del [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
* Formatear: Ya sea utilizar todo en tabs, o siempre utiliza 4 espacios.
* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una funcion no escribe a sus parámetros.
* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una función no escribe a sus parámetros.
* `interface Foo { new(): Foo; }`:
Este define el tipo de objeto que esten nuevos. Probablemente quieras `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
@@ -146,7 +146,7 @@ Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTy
Un ejemplo donde un tipo de parámetro es aceptable: `function id<T>(value: T): T;`.
Un ejemplo donde no es aceptable: `function parseJson<T>(json: string): T;`.
Una excepción: `new Map<string, number>()` está bien.
* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más especifico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`.
* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más específico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`.
* `var foo: string | any`:
Cuando es usado `any` en un tipo de unión, el tipo resultante todavía es `any`. Así que mientras la porción `string` de este tipo de anotación puede _verse_ útil, de hecho, no ofrece ningún typechecking adicional más que un simple `any`.
Dependiendo de la intención, una alternativa aceptable puede ser `any`, `string`, o `string | object`.
@@ -204,11 +204,11 @@ Este script utiliza [dtslint](https://github.com/Microsoft/dtslint).
#### ¿Cuál es exactamente la relación entre este repositorio y los paquetes de `@types` en NPM?
La `master` branch es automaticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher).
La `master` branch es automáticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher).
#### He enviado un pull request. ¿Cuánto tardará en ser merged?
Esto depende, pero la mayoría de los pull requests serán merged en alrededor de una semana. PRs que hayan sido aprovados por un autor listado en el encabezado de las definiciones usualmente son merged más rápidamente; PRs para nuevas definiciones tomarán más tiempo ya que requieren más revisiones de los mantenedores. Cada PR es revisado por un miembro de TypeScript o DefinitelyTyped antes de ser merged, por favor se paciente debido a que factores humanos pueden causar retrasos. Revisa el [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) para ver el progreso mientras los mantenedores trabajan on los PRs abiertos.
Esto depende, pero la mayoría de los pull requests serán merged en alrededor de una semana. PRs que hayan sido aprobados por un autor listado en el encabezado de las definiciones usualmente son merged más rápidamente; PRs para nuevas definiciones tomarán más tiempo ya que requieren más revisiones de los mantenedores. Cada PR es revisado por un miembro de TypeScript o DefinitelyTyped antes de ser merged, por favor sé paciente debido a que factores humanos pueden causar retrasos. Revisa el [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) para ver el progreso mientras los mantenedores trabajan en los PRs abiertos.
#### Mi PR ha sido merged; ¿cuándo será actualizado el paquete de `@types` NPM?
@@ -216,12 +216,12 @@ Los paquetes NPM deberán ser actualizados en unas cuantas horas. Si ha pasado m
#### Estoy escribiendo una definición que depende de otra definición. Debería utilizar `<reference types="" />` o una import?
Si el modulo al cual te estás refiriendo es un módulo externo (utiliza `export`), utilice una import.
Si el módulo al cual te estás refiriendo es un módulo externo (utiliza `export`), utilice una import.
Si el módulo al cual te refieres es un módulo ambiente (utiliza `declare module`, o simplemente declara las globales), utilice `<reference types="" />`.
#### He notado que algunos paquetes aquí tienen `package.json`.
Normalmente no lo necesitaras. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso.
Normalmente no lo necesitarás. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso.
Un `package.json` puede ser incluido por el bien de especificar dependencias. Aquí tienen un [ejemplo](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
No aceptamos otros campos, tales como `"description"`, para que sean definidos manualmente.
Además, si necesitas referencia a una versión anterior de typings, debes hacerlo añadiendo `"dependencies": { "@types/foo": "x.y.z" }` al package.json.
@@ -260,7 +260,7 @@ Cuando ya no sea un borrador, lo podremos eliminar desde DefinitelyType y hacer
Si planeas continuar actualizando la versión anterior del paquete, puedes crear una subcarpeta con la versión actual p.ej. `v2`, y copia los archivos existentes. Si es así, necesitarás:
1. Actualiza las rutas relativas en `tsconfig.json` al igual que `tslint.json`.
2. Añadir reglas de mapeo de rutas para asegurart de que la prueba se está ejecutando contra la versión prevista.
2. Añadir reglas de mapeo de rutas para asegurarte de que la prueba se está ejecutando contra la versión prevista.
Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) se ve así:
@@ -280,24 +280,24 @@ Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi
}
```
Si hay otros paquetes en DefinitelyTyped que son incompatibles con la nueva versión, necesitaras mapear las rutas a la versión anterior. También deberá hacer esto para los paquetes que dependen de paquetes que dependen de una version anterior.
Si hay otros paquetes en DefinitelyTyped que son incompatibles con la nueva versión, necesitarás mapear las rutas a la versión anterior. También deberá hacer esto para los paquetes que dependen de paquetes que dependen de una version anterior.
Por ejemplo, `react-router` depende de `history@2`, así que [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) tiene una ruta mapeada a "history": `[ "history/v2" ]`;
transitivo así mismo, `react-router-bootstrap` (que depende de `react-router`) también añade una ruta mapeada en su [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
Además, `/// <reference types=".." />` no trabajara con rutas mapeadas, así que las dependencias deberán utilizar `import`.
Además, `/// <reference types=".." />` no trabajará con rutas mapeadas, así que las dependencias deberán utilizar `import`.
#### ¿Cómo escribo definitions para paquetes que pueden ser usados globalmente y como un módulo?
El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), ademas [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada practicamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a travéz de una etiqueta script en una página web, o importada via require o imports estilo ES6.
El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), además [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada prácticamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a través de una etiqueta script en una página web, o importada vía require o imports estilo ES6.
Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas un propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js.
Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas una propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js.
Por favor tenga en cuenta que no es necesario para ejercer plenamente la definición en cada archivo de prueba - Es suficiente con probar solo los elementos globalmente accesibles en la prueba de archivos globales y ejercer la definición en el módulo del archivo de prueba, o viceversa.
#### ¿Qué pasa con paquetes scoped?
Types para un paquete scoped `@foo/bar` deberán ir en `types/foo__bar`. tenga en cuenta el doble guion bajo.
Types para un paquete scoped `@foo/bar` deberán ir en `types/foo__bar`. tenga en cuenta el doble guión bajo.
Cuando `dts-gen` es utilizado como scaffold en un paquete scoped, las propiedades `paths` deberán ser adaptadas manualmente en el paquete generado
`tsconfig.json` para referenciar correctamente el paquete scoped:

View File

@@ -144,6 +144,12 @@
"sourceRepoURL": "https://github.com/Azure/azure-mobile-apps-node/",
"asOfVersion": "3.0.0"
},
{
"libraryName": "@babel/parser",
"typingsPackageName": "babel__parser",
"sourceRepoURL": "https://github.com/babel/babel",
"asOfVersion": "7.1.0"
},
{
"libraryName": "BabylonJS",
"typingsPackageName": "babylonjs",
@@ -396,6 +402,12 @@
"sourceRepoURL": "https://github.com/MikeMcl/decimal.js",
"asOfVersion": "7.4.0"
},
{
"libraryName": "deepmerge",
"typingsPackageName": "deepmerge",
"sourceRepoURL": "git@github.com:KyleAMathews/deepmerge.git",
"asOfVersion": "2.2.0"
},
{
"libraryName": "delay",
"typingsPackageName": "delay",
@@ -534,6 +546,12 @@
"sourceRepoURL": "https://github.com/code-chris/extended-listbox",
"asOfVersion": "4.0.1"
},
{
"libraryName": "fast-diff",
"typingsPackageName": "fast-diff",
"sourceRepoURL": "https://github.com/jhchen/fast-diff",
"asOfVersion": "1.2.0"
},
{
"libraryName": "JSON-Patch",
"typingsPackageName": "fast-json-patch",
@@ -924,12 +942,24 @@
"sourceRepoURL": "https://github.com/blakeembrey/lower-case-first",
"asOfVersion": "1.0.1"
},
{
"libraryName": "mali",
"typingsPackageName": "mali",
"sourceRepoURL": "https://github.com/malijs/mali",
"asOfVersion": "0.9.2"
},
{
"libraryName": "maquette",
"typingsPackageName": "maquette",
"sourceRepoURL": "http://maquettejs.org/",
"asOfVersion": "2.1.6"
},
{
"libraryName": "maxmind",
"typingsPackageName": "maxmind",
"sourceRepoURL": "https://github.com/runk/node-maxmind",
"asOfVersion": "2.0.5"
},
{
"libraryName": "mendixmodelsdk",
"typingsPackageName": "mendixmodelsdk",
@@ -966,6 +996,12 @@
"sourceRepoURL": "https://github.com/mweststrate/mobservable-react",
"asOfVersion": "1.0.0"
},
{
"libraryName": "Mobx Cookie",
"typingsPackageName": "mobx-cookie",
"sourceRepoURL": "https://github.com/will-stone/mobx-cookie",
"asOfVersion": "1.1.1"
},
{
"libraryName": "Moment",
"typingsPackageName": "moment",
@@ -1194,6 +1230,12 @@
"sourceRepoURL": "https://github.com/react-ga/react-ga",
"asOfVersion": "2.3.0"
},
{
"libraryName": "react-i18next",
"typingsPackageName": "react-i18next",
"sourceRepoURL": "https://github.com/i18next/react-i18next",
"asOfVersion": "8.1.0"
},
{
"libraryName": "react-monaco-editor",
"typingsPackageName": "react-monaco-editor",

View File

@@ -0,0 +1,30 @@
import A11yDialog = require('a11y-dialog');
const dialogEl = new A11yDialog(document.getElementById("test"));
const dialogElTwo = new A11yDialog(document.getElementById("test"), document.getElementById("testContainer"));
const dialogElThree = new A11yDialog(document.getElementById("test"), "dummy-element");
dialogEl.show();
dialogEl.hide();
dialogElTwo.destroy();
dialogElThree.create();
// Test out interfaces that extends Element.
dialogEl.on("show", (el: HTMLElement) => {
el.textContent;
});
// Test out element and event.
dialogEl.on("create", (el: HTMLElement, evt) => {
el.textContent;
evt.target;
});
dialogEl.on('hide', () => {
const t = 5;
});
dialogEl.off("show", (el: HTMLElement) => {
el.textContent;
});

31
types/a11y-dialog/index.d.ts vendored Normal file
View File

@@ -0,0 +1,31 @@
// Type definitions for a11y-dialog 5.2
// Project: https://github.com/edenspiekermann/a11y-dialog
// Definitions by: Yuto <https://github.com/Goyatuzo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
type DialogEvents = "show" | "hide" | "destroy" | "create";
declare class A11yDialog {
constructor(el: Element | null, containers?: NodeList | Element | string | null);
/**
* Shows the dialog.
*/
show(): void;
/**
* Hides the dialog.
*/
hide(): void;
/**
* Unbind click listeners from dialog openers and closers and remove all bound custom event listeners registered with `.on()`
*/
destroy(): void;
/**
* Bind click listeners to dialog openers and closers.
*/
create(el?: Element | null, containers?: NodeList | Element | string | null): void;
on(evt: DialogEvents, callback: (dialogElement: any, event: Event) => void): void;
off(evt: DialogEvents, callback: (dialogElement: any, event: Event) => void): void;
}
export = A11yDialog;

View File

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

View File

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

View File

@@ -123,7 +123,7 @@ const aceSelectionTests = {
},
"test: moveCursor word left with umlauts": function () {
var session = new AceAjax.EditSession(" Fu<EFBFBD> F<EFBFBD><EFBFBD>e");
var session = new AceAjax.EditSession(" Fu¢ F¢¢e");
var selection = session.getSelection();
selection.moveCursorTo(0, 9)

View File

@@ -1,13 +1,15 @@
// Type definitions for ActionCable
// Project: https://github.com/rails/rails/tree/master/actioncable
// Type definitions for ActionCable 5.2
// Project: https://github.com/rails/rails/tree/master/actioncable/app/assets/javascripts
// Definitions by: Vincent Zhu <https://github.com/zhu1230>
// Jared Szechy <https://github.com/szechyjs>
// Definitions: https://github.com/zhu1230/DefinitelyTyped
// TypeScript Version: 2.3
declare module ActionCable {
interface Channel {
unsubscribe(): void;
perform(action: string, data: {}): void;
send(data: Object): boolean;
send(data: any): boolean;
}
interface Subscriptions {
@@ -16,12 +18,16 @@ declare module ActionCable {
interface Cable {
subscriptions: Subscriptions;
send(data: any): void;
connect(): void;
disconnect(): void;
ensureActiveConnection(): void;
}
interface CreateMixin {
connected(): void;
disconnected(): void;
received(obj: Object): void;
received(obj: any): void;
[key: string]: Function;
}

View File

@@ -451,7 +451,7 @@ declare namespace adone {
| encoding.Multibyte;
}
const defaultCharUnicode: "<22>";
const defaultCharUnicode: string;
const defaultCharSingleByte: "?";

View File

@@ -533,9 +533,10 @@ AFRAME.registerComponent('audioanalyser-waveform', {
rings.forEach(function transformRing(ring: THREE.Line, index: number) {
var normLevel;
normLevel = levels[RINGCOUNT - index - 1] + 0.01; // Avoid scaling by 0.
(ring.material as THREE.LineBasicMaterial).color.setHSL(colors[index], 1, normLevel);
ring.material.linewidth = normLevel * 3;
ring.material.opacity = normLevel;
const lineMaterial = ring.material as THREE.LineBasicMaterial;
lineMaterial.color.setHSL(colors[index], 1, normLevel);
lineMaterial.linewidth = normLevel * 3;
lineMaterial.opacity = normLevel;
ring.scale.z = normLevel;
});
},

View File

@@ -64,7 +64,7 @@ declare class Agenda extends EventEmitter {
defaultConcurrency(value: number): this;
/**
* Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is
* Takes a number which specifies the max number jobs that can be locked at any given moment. By default it is
* 0 for no max.
* @param value The value to set.
*/
@@ -189,7 +189,7 @@ declare namespace Agenda {
defaultLockLimit?: number;
/**
* Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is
* Takes a number which specifies the max number jobs that can be locked at any given moment. By default it is
* 0 for no max.
*/
lockLimit?: number;

View File

@@ -2,6 +2,7 @@
// Project: https://github.com/epoberezkin/ajv-errors
// Definitions by: Afshawn Lotfi <https://github.com/afshawnlotfi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
import { Ajv } from "ajv";

View File

@@ -0,0 +1,22 @@
import { parse, stringify } from 'ale-url-parser';
let url;
let urlObject;
url = stringify({});
console.log(url);
url = stringify({
protocol: 'protocol',
host: 'host',
path: ['foo', 'bar', 'baz'],
hash: 'hash',
query: {
foo: 1,
bar: [2, '3']
}
});
console.log(url);
urlObject = parse('//any.dom.ain.co.m/foo/bar?test=1&test=2#hash');
console.log(urlObject);

29
types/ale-url-parser/index.d.ts vendored Normal file
View File

@@ -0,0 +1,29 @@
// Type definitions for ale-url-parser 0.10
// Project: https://github.com/msn0/ale-url-parser#readme
// Definitions by: Michał Jezierski <https://github.com/msn0>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export interface QueryParams {
[key: string]: any;
}
export interface UrlObject {
protocol?: string;
host?: string;
path?: string[];
query?: QueryParams;
hash?: string;
}
/**
* Parse url string into url object.
* @return UrlObject
*/
export function parse(url: string): UrlObject;
/**
* Stringify url object into url string.
* @return string
*/
export function stringify(urlObject: UrlObject): string;

View File

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

View File

@@ -21,6 +21,7 @@ let _algoliaResponse: Response = {
processingTimeMS: 32,
query: '',
params: '',
index: '',
};
let _clientOptions: ClientOptions = {
@@ -103,7 +104,8 @@ let _algoliaQueryParameters: QueryParameters = {
filters: '',
attributesToRetrieve: [''],
restrictSearchableAttributes: [''],
facets: '',
facets: [''],
facetingAfterDistinct: true,
maxValuesPerFacet: 2,
attributesToHighlight: [''],
attributesToSnippet: [''],
@@ -120,28 +122,29 @@ let _algoliaQueryParameters: QueryParameters = {
typoTolerance: false,
allowTyposOnNumericTokens: false,
ignorePlurals: false,
disableTypoToleranceOnAttributes: '',
disableTypoToleranceOnAttributes: [''],
aroundLatLng: '',
aroundLatLngViaIP: '',
aroundRadius: 0,
aroundPrecision: 0,
minimumAroundRadius: 0,
insideBoundingBox: [[0]],
queryType: '',
queryType: 'prefixAll',
insidePolygon: [[0]],
removeWordsIfNoResults: '',
removeWordsIfNoResults: 'firstWords',
advancedSyntax: false,
optionalWords: [''],
removeStopWords: [''],
disableExactOnAttributes: [''],
exactOnSingleWordQuery: '',
alternativesAsExact: true,
exactOnSingleWordQuery: 'attribute',
alternativesAsExact: ["ignorePlurals"],
distinct: 0,
getRankingInfo: false,
numericAttributesToIndex: [''],
numericAttributesForFiltering: [''],
numericFilters: [''],
tagFilters: '',
facetFilters: '',
tagFilters: [''],
facetFilters: [''],
analytics: false,
analyticsTags: [''],
synonyms: true,
@@ -171,8 +174,38 @@ index.partialUpdateObjects([{}], false).then(() => {});
let indexName : string = index.indexName;
// complete copy
client.copyIndex('from', 'to').then(()=>{})
client.copyIndex('from', 'to', ()=> {})
client.copyIndex('from', 'to').then(()=>{});
client.copyIndex('from', 'to', ()=> {});
// with scope
client.copyIndex('from', 'to', ['settings']).then(()=>{})
client.copyIndex('from', 'to', ['synonyms', 'rules'], ()=> {})
client.copyIndex('from', 'to', ['settings']).then(()=>{});
client.copyIndex('from', 'to', ['synonyms', 'rules'], ()=> {});
// Browsing
const browser = index.browseAll();
index.browseAll('query');
index.browseAll('', {
filters: 'dog',
});
let hits: Object[] = [];
browser.on('result', function onResult(content) {
hits = hits.concat(content.hits);
});
browser.on('end', function onEnd() {
const _message = `We got ${hits.length} hits`
});
browser.on('error', function onError(err) {
throw err;
});
browser.stop();
index.browse("", {
advancedSyntax: false,
attributesToRetrieve: ['dogs']
});
client.copyIndex('from', 'to', ['settings']).then(()=>{});
client.copyIndex('from', 'to', ['synonyms', 'rules'], ()=> {});

View File

@@ -1,11 +1,14 @@
// Type definitions for algoliasearch-client-js 3.27.0
// Type definitions for algoliasearch-client-js 3.30.0
// Project: https://github.com/algolia/algoliasearch-client-js
// Definitions by: Baptiste Coquelle <https://github.com/cbaptiste>
// Haroen Viaene <https://github.com/haroenv>
// Aurélien Hervé <https://github.com/aherve>
// Samuel Vaillant <https://github.com/samouss>
// Kai Eichinger <https://github.com/keichinger>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// TypeScript Version: 2.8
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
declare namespace algoliasearch {
/**
@@ -611,6 +614,11 @@ declare namespace algoliasearch {
options: SearchForFacetValues.Parameters,
cb: (err: Error, res: SearchForFacetValues.Response) => void
): void;
/**
* Browse an index
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
*/
browse(query: string, parameters: BrowseParameters, cb: (err: Error, res: BrowseResponse) => void): void;
/**
* Browse an index
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
@@ -620,7 +628,7 @@ declare namespace algoliasearch {
* Browse an index
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
*/
browse(query: string): Promise<BrowseResponse>;
browse(query: string, parameters?: BrowseParameters): Promise<BrowseResponse>;
/**
* Browse an index from a cursor
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
@@ -638,7 +646,7 @@ declare namespace algoliasearch {
* Browse an entire index
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
*/
browseAll(): Promise<Response>;
browseAll(query?: string, parameters?: BrowseParameters): Browser;
/**
* Clear an index content
* https://github.com/algolia/algoliasearch-client-js#clear-index---clearindex
@@ -966,6 +974,22 @@ declare namespace algoliasearch {
query: string;
processingTimeMS: number;
}
type BrowseParameters = Omit<
QueryParameters,
| "typoTolerance"
| "distinct"
| "facets"
| "getRankingInfo"
| "attributesToHighlight"
| "attributesToSnippet"
>
interface Browser {
on(type: "error", cb: (err: Error) => void): void
on(type: "end", cb: () => void): void
on(type: "stop", cb: () => void): void
on(type: "result", cb: (content: BrowseResponse) => void): void
stop(): void
}
/**
* Describes a synonym object
*/
@@ -1099,112 +1123,121 @@ declare namespace algoliasearch {
userToken?: string;
}
interface QueryParameters {
/**
* Query string used to perform the search
* default: ''
* https://www.algolia.com/doc/api-reference/api-parameters/query/
*/
query?: string;
/**
* Filter the query with numeric, facet or/and tag filters
* default: ""
* https://www.algolia.com/doc/api-reference/api-parameters/filters/
*/
filters?: string;
/**
* A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer.
* default: *
* https://www.algolia.com/doc/api-reference/api-parameters/attributesToRetrieve/
*/
attributesToRetrieve?: string[];
/**
* List of attributes you want to use for textual search
* default: attributeToIndex
* https://www.algolia.com/doc/api-reference/api-parameters/restrictSearchableAttributes/
*/
restrictSearchableAttributes?: string[];
/**
* You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes
* default: []
* https://www.algolia.com/doc/api-reference/api-parameters/facets/
*/
facets?: string[];
/**
* Query string used to perform the search
* default: ''
* https://github.com/algolia/algoliasearch-client-js#query
*/
query?: string;
/**
* Filter the query with numeric, facet or/and tag filters
* default: ""
* https://github.com/algolia/algoliasearch-client-js#filters
*/
filters?: string;
/**
* A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer.
* default: *
* https://github.com/algolia/algoliasearch-client-js#attributestoretrieve
*/
attributesToRetrieve?: string[];
/**
* List of attributes you want to use for textual search
* default: attributeToIndex
* https://github.com/algolia/algoliasearch-client-js#restrictsearchableattributes
*/
restrictSearchableAttributes?: string[];
/**
* You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes
* default: ""
* https://github.com/algolia/algoliasearch-client-js#facets
*/
facets?: string | string[];
* Force faceting to be applied after de-duplication (via the Distinct setting).
* When using the distinct setting in combination with faceting, facet counts may be higher than expected.
* This is because the engine, by default, computes faceting before applying de-duplication (distinct).
* When facetingAfterDistinct is set to true, the engine calculates faceting after the de-duplication has been applied.
* default ""
* https://www.algolia.com/doc/api-reference/api-parameters/facetingAfterDistinct/
*/
facetingAfterDistinct?: boolean;
/**
* Limit the number of facet values returned for each facet.
* default: ""
* https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet
* default: 100
* https://www.algolia.com/doc/api-reference/api-parameters/maxValuesPerFacet/
*/
maxValuesPerFacet?: number;
/**
* Default list of attributes to highlight. If set to null, all indexed attributes are highlighted.
* default: null
* https://github.com/algolia/algoliasearch-client-js#attributestohighlight
* https://www.algolia.com/doc/api-reference/api-parameters/attributesToHighlight/
*/
attributesToHighlight?: string[];
/**
* Default list of attributes to snippet alongside the number of words to return
* default: null
* https://github.com/algolia/algoliasearch-client-js#attributestosnippet
* https://www.algolia.com/doc/api-reference/api-parameters/attributesToSnippet/
*/
attributesToSnippet?: string[];
/**
* Specify the string that is inserted before the highlighted parts in the query result
* default: <em>
* https://github.com/algolia/algoliasearch-client-js#highlightpretag
* https://www.algolia.com/doc/api-reference/api-parameters/highlightPreTag/
*/
highlightPreTag?: string;
/**
* Specify the string that is inserted after the highlighted parts in the query result
* default: </em>
* https://github.com/algolia/algoliasearch-client-js#highlightposttag
* https://www.algolia.com/doc/api-reference/api-parameters/highlightPostTag/
*/
highlightPostTag?: string;
/**
* String used as an ellipsis indicator when a snippet is truncated.
* default: …
* https://github.com/algolia/algoliasearch-client-js#snippetellipsistext
* https://www.algolia.com/doc/api-reference/api-parameters/snippetEllipsisText/
*/
snippetEllipsisText?: string;
/**
* If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets
* default: false
* https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays
* https://www.algolia.com/doc/api-reference/api-parameters/restrictHighlightAndSnippetArrays/
*/
restrictHighlightAndSnippetArrays?: boolean;
/**
* Pagination parameter used to select the number of hits per page
* default: 20
* https://github.com/algolia/algoliasearch-client-js#hitsperpage
* https://www.algolia.com/doc/api-reference/api-parameters/hitsPerPage/
*/
hitsPerPage?: number;
/**
* Pagination parameter used to select the page to retrieve.
* default: 0
* https://github.com/algolia/algoliasearch-client-js#page
* https://www.algolia.com/doc/api-reference/api-parameters/page/
*/
page?: number;
/**
* Offset of the first hit to return
* default: null
* https://github.com/algolia/algoliasearch-client-js#offset
* https://www.algolia.com/doc/api-reference/api-parameters/offset/
*/
offset?: number;
/**
* Number of hits to return.
* default: null
* https://github.com/algolia/algoliasearch-client-js#length
* https://www.algolia.com/doc/api-reference/api-parameters/length/
*/
length?: number;
/**
* The minimum number of characters needed to accept one typo.
* default: 4
* https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo
* https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor1Typo/
*/
minWordSizefor1Typo?: number;
/**
* The minimum number of characters needed to accept two typo.
* fault: 8
* https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos
* https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor2Typos/
*/
minWordSizefor2Typos?: number;
/**
@@ -1214,62 +1247,62 @@ declare namespace algoliasearch {
* 'false' The typo tolerance is disabled. All results with typos will be hidden.
* 'min' Only keep results with the minimum number of typos
* 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos.
* https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos
* https://www.algolia.com/doc/api-reference/api-parameters/typoTolerance/
*/
typoTolerance?: boolean;
/**
* If set to false, disables typo tolerance on numeric tokens (numbers).
* default:
* https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens
* https://www.algolia.com/doc/api-reference/api-parameters/allowTyposOnNumericTokens/
*/
allowTyposOnNumericTokens?: boolean;
/**
* If set to true, plural won't be considered as a typo
* default: false
* https://github.com/algolia/algoliasearch-client-js#ignoreplurals
* https://www.algolia.com/doc/api-reference/api-parameters/ignorePlurals/
*/
ignorePlurals?: boolean;
/**
* List of attributes on which you want to disable typo tolerance
* default: ""
* https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes
* default: []
* https://www.algolia.com/doc/api-reference/api-parameters/disableTypoToleranceOnAttributes/
*/
disableTypoToleranceOnAttributes?: string;
disableTypoToleranceOnAttributes?: string[];
/**
* Search for entries around a given location
* default: ""
* https://github.com/algolia/algoliasearch-client-js#aroundlatlng
* https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLng/
*/
aroundLatLng?: string;
/**
* Search for entries around a given latitude/longitude automatically computed from user IP address.
* default: ""
* https://github.com/algolia/algoliasearch-client-js#aroundlatlngviaip
* https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLngViaIP/
*/
aroundLatLngViaIP?: string;
/**
* Control the radius associated with a geo search. Defined in meters.
* default: null
* You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area
* https://github.com/algolia/algoliasearch-client-js#aroundradius
* https://www.algolia.com/doc/api-reference/api-parameters/aroundRadius/
*/
aroundRadius?: number | 'all';
/**
* Control the precision of a geo search
* default: null
* https://github.com/algolia/algoliasearch-client-js#aroundprecision
* https://www.algolia.com/doc/api-reference/api-parameters/aroundPrecision/
*/
aroundPrecision?: number;
/**
* Define the minimum radius used for a geo search when aroundRadius is not set.
* default: null
* https://github.com/algolia/algoliasearch-client-js#minimumaroundradius
* https://www.algolia.com/doc/api-reference/api-parameters/minimumAroundRadius/
*/
minimumAroundRadius?: number;
/**
* Search entries inside a given area defined by the two extreme points of a rectangle
* default: null
* https://github.com/algolia/algoliasearch-client-js#insideboundingbox
* https://www.algolia.com/doc/api-reference/api-parameters/insideBoundingBox/
*/
insideBoundingBox?: number[][];
/**
@@ -1278,13 +1311,13 @@ declare namespace algoliasearch {
* 'prefixAll' All query words are interpreted as prefixes. This option is not recommended.
* 'prefixLast' Only the last word is interpreted as a prefix (default behavior).
* 'prefixNone' No query word is interpreted as a prefix. This option is not recommended.
* https://github.com/algolia/algoliasearch-client-js#querytype
* https://www.algolia.com/doc/api-reference/api-parameters/queryType/
*/
queryType?: any;
queryType?: "prefixAll"|"prefixLast"|"prefixNone";
/**
* Search entries inside a given area defined by a set of points
* defauly: ''
* https://github.com/algolia/algoliasearch-client-js#insidepolygon
* https://www.algolia.com/doc/api-reference/api-parameters/insidePolygon/
*/
insidePolygon?: number[][];
/**
@@ -1294,19 +1327,19 @@ declare namespace algoliasearch {
* 'firstWords' When a query does not return any results, the first word will be added as optional
* 'allOptional' When a query does not return any results, a second trial will be made with all words as optional
* 'none' No specific processing is done when a query does not return any results
* https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults
* https://www.algolia.com/doc/api-reference/api-parameters/removeWordsIfNoResults/
*/
removeWordsIfNoResults?: string;
removeWordsIfNoResults?: "none"|"lastWords"|"firstWords"|"allOptional";
/**
* Enables the advanced query syntax
* default: false
* https://github.com/algolia/algoliasearch-client-js#advancedsyntax
* https://www.algolia.com/doc/api-reference/api-parameters/advancedSyntax/
*/
advancedSyntax?: boolean;
/**
* A string that contains the comma separated list of words that should be considered as optional when found in the query
* default: []
* https://github.com/algolia/algoliasearch-client-js#optionalwords
* https://www.algolia.com/doc/api-reference/api-parameters/optionalWords/
*/
optionalWords?: string[];
/**
@@ -1314,13 +1347,13 @@ declare namespace algoliasearch {
* default: false
* true|false: enable or disable stop words for all 41 supported languages; or
* a list of language ISO codes (as a comma-separated string) for which stop words should be enable
* https://github.com/algolia/algoliasearch-client-js#removestopwords
* https://www.algolia.com/doc/api-reference/api-parameters/removeStopWords/
*/
removeStopWords?: string[];
removeStopWords?: boolean|string[];
/**
* List of attributes on which you want to disable the computation of exact criteria
* default: []
* https://github.com/algolia/algoliasearch-client-js#disableexactonattributes
* https://www.algolia.com/doc/api-reference/api-parameters/disableExactOnAttributes/
*/
disableExactOnAttributes?: string[];
/**
@@ -1329,81 +1362,90 @@ declare namespace algoliasearch {
* 'none': no exact on single word query
* 'word': exact set to 1 if the query word is found in the record
* 'attribute': exact set to 1 if there is an attribute containing a string equals to the query
* https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery
* https://www.algolia.com/doc/api-reference/api-parameters/exactOnSingleWordQuery/
*/
exactOnSingleWordQuery?: string;
exactOnSingleWordQuery?: "attribute"|"none"|"word";
/**
* Specify the list of approximation that should be considered as an exact match in the ranking formula
* default: ['ignorePlurals', 'singleWordSynonym']
* 'ignorePlurals': alternative words added by the ignorePlurals feature
* 'singleWordSynonym': single-word synonym (For example "NY" = "NYC")
* 'multiWordsSynonym': multiple-words synonym
* https://github.com/algolia/algoliasearch-client-js#alternativesasexact
* https://www.algolia.com/doc/api-reference/api-parameters/alternativesAsExact/
*/
alternativesAsExact?: any;
alternativesAsExact?: Array<"ignorePlurals"|"singleWordSynonym"|"multiWordsSynonym">;
/**
* If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set.
* https://github.com/algolia/algoliasearch-client-js#distinct
* https://www.algolia.com/doc/api-reference/api-parameters/distinct/
*/
distinct?: any;
distinct?: number|boolean;
/**
* If set to true, the result hits will contain ranking information in the _rankingInfo attribute.
* default: false
* https://github.com/algolia/algoliasearch-client-js#getrankinginfo
* https://www.algolia.com/doc/api-reference/api-parameters/getRankingInfo/
*/
getRankingInfo?: boolean;
/**
* @deprecated Use `numericAttributesForFiltering` instead
* All numerical attributes are automatically indexed as numerical filters
* default: ''
* https://github.com/algolia/algoliasearch-client-js#numericattributestoindex
* https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/
*/
numericAttributesToIndex?: string[];
/**
* All numerical attributes are automatically indexed as numerical filters
* default: ''
* https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/
*/
numericAttributesForFiltering?: string[];
/**
* @deprecated please use filters instead
* A string that contains the comma separated list of numeric filters you want to apply.
* https://github.com/algolia/algoliasearch-client-js#numericfilters-deprecated
* https://www.algolia.com/doc/api-reference/api-parameters/numericFilters/
*/
numericFilters?: string[];
/**
* @deprecated
*
* Filter the query by a set of tags.
* https://github.com/algolia/algoliasearch-client-js#tagfilters-deprecated
* Default: []
* https://www.algolia.com/doc/api-reference/api-parameters/tagFilters/
*/
tagFilters?: string;
tagFilters?: string[];
/**
* @deprecated
* Filter the query by a set of facets.
* https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated
* Default: []
* https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/
*/
facetFilters?: string | string[]
facetFilters?: string[]|string[][];
/**
* If set to false, this query will not be taken into account in the analytics feature.
* default true
* https://github.com/algolia/algoliasearch-client-js#analytics
* https://www.algolia.com/doc/api-reference/api-parameters/analytics/
*/
analytics?: boolean;
/**
* If set, tag your query with the specified identifiers
* default: null
* https://github.com/algolia/algoliasearch-client-js#analyticstags
* default: []
* https://www.algolia.com/doc/api-reference/api-parameters/analyticsTags/
*/
analyticsTags?: string[];
/**
* If set to false, the search will not use the synonyms defined for the targeted index.
* default: true
* https://github.com/algolia/algoliasearch-client-js#synonyms
* https://www.algolia.com/doc/api-reference/api-parameters/synonyms/
*/
synonyms?: boolean;
/**
* If set to false, words matched via synonym expansion will not be replaced by the matched synonym in the highlighted result.
* default: true
* https://github.com/algolia/algoliasearch-client-js#replacesynonymsinhighlight
* https://www.algolia.com/doc/api-reference/api-parameters/replaceSynonymsInHighlight/
*/
replaceSynonymsInHighlight?: boolean;
/**
* Configure the precision of the proximity ranking criterion
* default: 1
* https://github.com/algolia/algoliasearch-client-js#minproximity
* https://www.algolia.com/doc/api-reference/api-parameters/minProximity/
*/
minProximity?: number;
@@ -1456,7 +1498,7 @@ declare namespace algoliasearch {
interface Task {
taskID: number;
createdAt: string;
objectID?: string;
objectID?: string;
}
interface TaskStatus {
@@ -1739,42 +1781,42 @@ declare namespace algoliasearch {
interface Response {
/**
* Contains all the hits matching the query
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
hits: any[];
/**
* Current page
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
page: number;
/**
* Number of total hits matching the query
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
nbHits: number;
/**
* Number of pages
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
nbPages: number;
/**
* Number of hits per pages
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
hitsPerPage: number;
/**
* Engine processing time (excluding network transfer)
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
processingTimeMS: number;
/**
* Query used to perform the search
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
query: string;
/**
* GET parameters used to perform the search
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
params: string;
facets?: {
@@ -1788,6 +1830,16 @@ declare namespace algoliasearch {
sum: number,
};
};
/**
* The index name is only set when searching multiple indices.
* https://www.algolia.com/doc/api-reference/api-methods/multiple-queries/?language=javascript#response
*/
index?: string;
/**
* The cursor is only set when browsing the index.
* https://www.algolia.com/doc/api-reference/api-methods/browse/
*/
cursor?: string;
}
interface MultiResponse {

View File

@@ -1,12 +1,15 @@
// Type definitions for algoliasearch-client-js 3.27.0
// Type definitions for algoliasearch-client-js 3.30.0
// Project: https://github.com/algolia/algoliasearch-client-js
// Definitions by: Baptiste Coquelle <https://github.com/cbaptiste>
// Haroen Viaene <https://github.com/haroenv>
// Aurélien Hervé <https://github.com/aherve>
// Samuel Vaillant <https://github.com/samouss>
// Claas Brüggemann <https://github.com/ClaasBrueggemann>
// Kai Eichinger <https://github.com/keichinger>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// TypeScript Version: 2.8
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
declare namespace algoliasearch {
/**
@@ -130,6 +133,11 @@ declare namespace algoliasearch {
options: SearchForFacetValues.Parameters,
cb: (err: Error, res: SearchForFacetValues.Response) => void
): void;
/**
* Browse an index
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
*/
browse(query: string, parameters: BrowseParameters, cb: (err: Error, res: BrowseResponse) => void): void;
/**
* Browse an index
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
@@ -139,7 +147,7 @@ declare namespace algoliasearch {
* Browse an index
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
*/
browse(query: string): Promise<BrowseResponse>;
browse(query: string, parameters?: BrowseParameters): Promise<BrowseResponse>;
/**
* Browse an index from a cursor
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
@@ -194,114 +202,122 @@ declare namespace algoliasearch {
query: string;
processingTimeMS: number;
}
type BrowseParameters = Omit<
QueryParameters,
| "typoTolerance"
| "distinct"
| "facets"
| "getRankingInfo"
| "attributesToHighlight"
| "attributesToSnippet"
>
interface QueryParameters {
/**
* Query string used to perform the search
* default: ''
* https://github.com/algolia/algoliasearch-client-js#query
* https://www.algolia.com/doc/api-reference/api-parameters/query/
*/
query?: string;
/**
* Filter the query with numeric, facet or/and tag filters
* default: ""
* https://github.com/algolia/algoliasearch-client-js#filters
* https://www.algolia.com/doc/api-reference/api-parameters/filters/
*/
filters?: string;
/**
* A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer.
* default: *
* https://github.com/algolia/algoliasearch-client-js#attributestoretrieve
* https://www.algolia.com/doc/api-reference/api-parameters/attributesToRetrieve/
*/
attributesToRetrieve?: string[];
/**
* List of attributes you want to use for textual search
* default: attributeToIndex
* https://github.com/algolia/algoliasearch-client-js#restrictsearchableattributes
* https://www.algolia.com/doc/api-reference/api-parameters/restrictSearchableAttributes/
*/
restrictSearchableAttributes?: string[];
/**
* You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes
* default: ""
* https://github.com/algolia/algoliasearch-client-js#facets
* default: []
* https://www.algolia.com/doc/api-reference/api-parameters/facets/
*/
facets?: string;
facets?: string[];
/**
* Limit the number of facet values returned for each facet.
* default: ""
* https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet
* default: 100
* https://www.algolia.com/doc/api-reference/api-parameters/maxValuesPerFacet/
*/
maxValuesPerFacet?: number;
/**
* Default list of attributes to highlight. If set to null, all indexed attributes are highlighted.
* default: null
* https://github.com/algolia/algoliasearch-client-js#attributestohighlight
* https://www.algolia.com/doc/api-reference/api-parameters/attributesToHighlight/
*/
attributesToHighlight?: string[];
/**
* Default list of attributes to snippet alongside the number of words to return
* default: null
* https://github.com/algolia/algoliasearch-client-js#attributestosnippet
* https://www.algolia.com/doc/api-reference/api-parameters/attributesToSnippet/
*/
attributesToSnippet?: string[];
/**
* Specify the string that is inserted before the highlighted parts in the query result
* default: <em>
* https://github.com/algolia/algoliasearch-client-js#highlightpretag
* https://www.algolia.com/doc/api-reference/api-parameters/highlightPreTag/
*/
highlightPreTag?: string;
/**
* Specify the string that is inserted after the highlighted parts in the query result
* default: </em>
* https://github.com/algolia/algoliasearch-client-js#highlightposttag
* https://www.algolia.com/doc/api-reference/api-parameters/highlightPostTag/
*/
highlightPostTag?: string;
/**
* String used as an ellipsis indicator when a snippet is truncated.
* default: …
* https://github.com/algolia/algoliasearch-client-js#snippetellipsistext
* https://www.algolia.com/doc/api-reference/api-parameters/snippetEllipsisText/
*/
snippetEllipsisText?: string;
/**
* If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets
* default: false
* https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays
* https://www.algolia.com/doc/api-reference/api-parameters/restrictHighlightAndSnippetArrays/
*/
restrictHighlightAndSnippetArrays?: boolean;
/**
* Pagination parameter used to select the number of hits per page
* default: 20
* https://github.com/algolia/algoliasearch-client-js#hitsperpage
* https://www.algolia.com/doc/api-reference/api-parameters/hitsPerPage/
*/
hitsPerPage?: number;
/**
* Pagination parameter used to select the page to retrieve.
* default: 0
* https://github.com/algolia/algoliasearch-client-js#page
* https://www.algolia.com/doc/api-reference/api-parameters/page/
*/
page?: number;
/**
* Offset of the first hit to return
* default: null
* https://github.com/algolia/algoliasearch-client-js#offset
* https://www.algolia.com/doc/api-reference/api-parameters/offset/
*/
offset?: number;
/**
* Number of hits to return.
* default: null
* https://github.com/algolia/algoliasearch-client-js#length
* https://www.algolia.com/doc/api-reference/api-parameters/length/
*/
length?: number;
/**
* The minimum number of characters needed to accept one typo.
* default: 4
* https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo
* https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor1Typo/
*/
minWordSizefor1Typo?: number;
/**
* The minimum number of characters needed to accept two typo.
* fault: 8
* https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos
* https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor2Typos/
*/
minWordSizefor2Typos?: number;
/**
@@ -311,62 +327,62 @@ declare namespace algoliasearch {
* 'false' The typo tolerance is disabled. All results with typos will be hidden.
* 'min' Only keep results with the minimum number of typos
* 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos.
* https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos
* https://www.algolia.com/doc/api-reference/api-parameters/typoTolerance/
*/
typoTolerance?: boolean;
/**
* If set to false, disables typo tolerance on numeric tokens (numbers).
* default:
* https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens
* https://www.algolia.com/doc/api-reference/api-parameters/allowTyposOnNumericTokens/
*/
allowTyposOnNumericTokens?: boolean;
/**
* If set to true, plural won't be considered as a typo
* default: false
* https://github.com/algolia/algoliasearch-client-js#ignoreplurals
* https://www.algolia.com/doc/api-reference/api-parameters/ignorePlurals/
*/
ignorePlurals?: boolean;
/**
* List of attributes on which you want to disable typo tolerance
* default: ""
* https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes
* default: []
* https://www.algolia.com/doc/api-reference/api-parameters/disableTypoToleranceOnAttributes/
*/
disableTypoToleranceOnAttributes?: string;
disableTypoToleranceOnAttributes?: string[];
/**
* Search for entries around a given location
* default: ""
* https://github.com/algolia/algoliasearch-client-js#aroundlatlng
* https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLng/
*/
aroundLatLng?: string;
/**
* Search for entries around a given latitude/longitude automatically computed from user IP address.
* default: ""
* https://github.com/algolia/algoliasearch-client-js#aroundlatlngviaip
* https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLngViaIP/
*/
aroundLatLngViaIP?: string;
/**
* Control the radius associated with a geo search. Defined in meters.
* default: null
* You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area
* https://github.com/algolia/algoliasearch-client-js#aroundradius
* https://www.algolia.com/doc/api-reference/api-parameters/aroundRadius/
*/
aroundRadius?: number | 'all';
/**
* Control the precision of a geo search
* default: null
* https://github.com/algolia/algoliasearch-client-js#aroundprecision
* https://www.algolia.com/doc/api-reference/api-parameters/aroundPrecision/
*/
aroundPrecision?: number;
/**
* Define the minimum radius used for a geo search when aroundRadius is not set.
* default: null
* https://github.com/algolia/algoliasearch-client-js#minimumaroundradius
* https://www.algolia.com/doc/api-reference/api-parameters/minimumAroundRadius/
*/
minimumAroundRadius?: number;
/**
* Search entries inside a given area defined by the two extreme points of a rectangle
* default: null
* https://github.com/algolia/algoliasearch-client-js#insideboundingbox
* https://www.algolia.com/doc/api-reference/api-parameters/insideBoundingBox/
*/
insideBoundingBox?: number[][];
/**
@@ -375,13 +391,13 @@ declare namespace algoliasearch {
* 'prefixAll' All query words are interpreted as prefixes. This option is not recommended.
* 'prefixLast' Only the last word is interpreted as a prefix (default behavior).
* 'prefixNone' No query word is interpreted as a prefix. This option is not recommended.
* https://github.com/algolia/algoliasearch-client-js#querytype
* https://www.algolia.com/doc/api-reference/api-parameters/queryType/
*/
queryType?: any;
queryType?: "prefixAll"|"prefixLast"|"prefixNone";
/**
* Search entries inside a given area defined by a set of points
* defauly: ''
* https://github.com/algolia/algoliasearch-client-js#insidepolygon
* https://www.algolia.com/doc/api-reference/api-parameters/insidePolygon/
*/
insidePolygon?: number[][];
/**
@@ -391,19 +407,19 @@ declare namespace algoliasearch {
* 'firstWords' When a query does not return any results, the first word will be added as optional
* 'allOptional' When a query does not return any results, a second trial will be made with all words as optional
* 'none' No specific processing is done when a query does not return any results
* https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults
* https://www.algolia.com/doc/api-reference/api-parameters/removeWordsIfNoResults/
*/
removeWordsIfNoResults?: string;
removeWordsIfNoResults?: "none"|"lastWords"|"firstWords"|"allOptional";
/**
* Enables the advanced query syntax
* default: false
* https://github.com/algolia/algoliasearch-client-js#advancedsyntax
* https://www.algolia.com/doc/api-reference/api-parameters/advancedSyntax/
*/
advancedSyntax?: boolean;
/**
* A string that contains the comma separated list of words that should be considered as optional when found in the query
* default: []
* https://github.com/algolia/algoliasearch-client-js#optionalwords
* https://www.algolia.com/doc/api-reference/api-parameters/optionalWords/
*/
optionalWords?: string[];
/**
@@ -411,13 +427,13 @@ declare namespace algoliasearch {
* default: false
* true|false: enable or disable stop words for all 41 supported languages; or
* a list of language ISO codes (as a comma-separated string) for which stop words should be enable
* https://github.com/algolia/algoliasearch-client-js#removestopwords
* https://www.algolia.com/doc/api-reference/api-parameters/removeStopWords/
*/
removeStopWords?: string[];
removeStopWords?: boolean|string[];
/**
* List of attributes on which you want to disable the computation of exact criteria
* default: []
* https://github.com/algolia/algoliasearch-client-js#disableexactonattributes
* https://www.algolia.com/doc/api-reference/api-parameters/disableExactOnAttributes/
*/
disableExactOnAttributes?: string[];
/**
@@ -426,81 +442,90 @@ declare namespace algoliasearch {
* 'none': no exact on single word query
* 'word': exact set to 1 if the query word is found in the record
* 'attribute': exact set to 1 if there is an attribute containing a string equals to the query
* https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery
* https://www.algolia.com/doc/api-reference/api-parameters/exactOnSingleWordQuery/
*/
exactOnSingleWordQuery?: string;
exactOnSingleWordQuery?: "attribute"|"none"|"word";
/**
* Specify the list of approximation that should be considered as an exact match in the ranking formula
* default: ['ignorePlurals', 'singleWordSynonym']
* 'ignorePlurals': alternative words added by the ignorePlurals feature
* 'singleWordSynonym': single-word synonym (For example "NY" = "NYC")
* 'multiWordsSynonym': multiple-words synonym
* https://github.com/algolia/algoliasearch-client-js#alternativesasexact
* https://www.algolia.com/doc/api-reference/api-parameters/alternativesAsExact/
*/
alternativesAsExact?: any;
alternativesAsExact?: Array<"ignorePlurals"|"singleWordSynonym"|"multiWordsSynonym">;
/**
* If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set.
* https://github.com/algolia/algoliasearch-client-js#distinct
* https://www.algolia.com/doc/api-reference/api-parameters/distinct/
*/
distinct?: any;
distinct?: number|boolean;
/**
* If set to true, the result hits will contain ranking information in the _rankingInfo attribute.
* default: false
* https://github.com/algolia/algoliasearch-client-js#getrankinginfo
* https://www.algolia.com/doc/api-reference/api-parameters/getRankingInfo/
*/
getRankingInfo?: boolean;
/**
* @deprecated Use `numericAttributesForFiltering` instead
* All numerical attributes are automatically indexed as numerical filters
* default: ''
* https://github.com/algolia/algoliasearch-client-js#numericattributestoindex
* https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/
*/
numericAttributesToIndex?: string[];
/**
* All numerical attributes are automatically indexed as numerical filters
* default: ''
* https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/
*/
numericAttributesForFiltering?: string[];
/**
* @deprecated please use filters instead
* A string that contains the comma separated list of numeric filters you want to apply.
* https://github.com/algolia/algoliasearch-client-js#numericfilters-deprecated
* https://www.algolia.com/doc/api-reference/api-parameters/numericFilters/
*/
numericFilters?: string[];
/**
* @deprecated
*
* Filter the query by a set of tags.
* https://github.com/algolia/algoliasearch-client-js#tagfilters-deprecated
* Default: []
* https://www.algolia.com/doc/api-reference/api-parameters/tagFilters/
*/
tagFilters?: string;
tagFilters?: string[];
/**
* @deprecated
* Filter the query by a set of facets.
* https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated
* Default: []
* https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/
*/
facetFilters?: string;
facetFilters?: string[]|string[][];
/**
* If set to false, this query will not be taken into account in the analytics feature.
* default true
* https://github.com/algolia/algoliasearch-client-js#analytics
* https://www.algolia.com/doc/api-reference/api-parameters/analytics/
*/
analytics?: boolean;
/**
* If set, tag your query with the specified identifiers
* default: null
* https://github.com/algolia/algoliasearch-client-js#analyticstags
* default: []
* https://www.algolia.com/doc/api-reference/api-parameters/analyticsTags/
*/
analyticsTags?: string[];
/**
* If set to false, the search will not use the synonyms defined for the targeted index.
* default: true
* https://github.com/algolia/algoliasearch-client-js#synonyms
* https://www.algolia.com/doc/api-reference/api-parameters/synonyms/
*/
synonyms?: boolean;
/**
* If set to false, words matched via synonym expansion will not be replaced by the matched synonym in the highlighted result.
* default: true
* https://github.com/algolia/algoliasearch-client-js#replacesynonymsinhighlight
* https://www.algolia.com/doc/api-reference/api-parameters/replaceSynonymsInHighlight/
*/
replaceSynonymsInHighlight?: boolean;
/**
* Configure the precision of the proximity ranking criterion
* default: 1
* https://github.com/algolia/algoliasearch-client-js#minproximity
* https://www.algolia.com/doc/api-reference/api-parameters/minProximity/
*/
minProximity?: number;
@@ -530,42 +555,42 @@ declare namespace algoliasearch {
interface Response {
/**
* Contains all the hits matching the query
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
hits: any[];
/**
* Current page
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
page: number;
/**
* Number of total hits matching the query
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
nbHits: number;
/**
* Number of pages
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
nbPages: number;
/**
* Number of hits per pages
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
hitsPerPage: number;
/**
* Engine processing time (excluding network transfer)
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
processingTimeMS: number;
/**
* Query used to perform the search
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
query: string;
/**
* GET parameters used to perform the search
* https://github.com/algolia/algoliasearch-client-js#response-format
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
*/
params: string;
facets?: {
@@ -579,6 +604,16 @@ declare namespace algoliasearch {
sum: number,
};
};
/**
* The index name is only set when searching multiple indices.
* https://www.algolia.com/doc/api-reference/api-methods/multiple-queries/?language=javascript#response
*/
index?: string;
/**
* The cursor is only set when browsing the index.
* https://www.algolia.com/doc/api-reference/api-methods/browse/
*/
cursor?: string;
}
interface MultiResponse {

File diff suppressed because it is too large Load Diff

3265
types/ali-app/index.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"esnext",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",
"ali-app-tests.ts"
],
"exclude": [
".prettierrc"
]
}

View File

@@ -0,0 +1,7 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-mergeable-namespace": false,
"no-unnecessary-generics": false
}
}

View File

@@ -17,6 +17,7 @@
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-angle-bracket-type-assertion": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,

View File

@@ -1,85 +1,110 @@
// Tests for Amplitude SDK TypeScript definitions
module Amplitude.Tests {
function all() {
amplitude.init('YOUR_API_KEY_HERE', null, {
// optional configuration options
var client: amplitude.AmplitudeClient = new amplitude.AmplitudeClient();
var identify: amplitude.Identify = new amplitude.Identify();
var revenue: amplitude.Revenue = new amplitude.Revenue();
client = amplitude.getInstance();
client = amplitude.getInstance('some name');
amplitude.__VERSION__ === '1.2.3';
amplitude.options.logLevel = 'WARN';
amplitude.init('API_KEY', 'USER_ID', {
saveEvents: true,
includeUtm: true,
includeReferrer: true,
batchEvents: true,
eventUploadThreshold: 50
});
amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE', null, () => {});
}, function () { });
amplitude.init('API_KEY', 'USER_ID', { includeReferrer: true, includeUtm: true });
amplitude.init('API_KEY', 'USER_ID');
amplitude.init('API_KEY');
amplitude.logEvent('EVENT_IDENTIFIER_HERE');
amplitude.setUserId('USER_ID_HERE');
amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE');
amplitude.setUserId(null); // not string 'null'
amplitude.setVersionName('VERSION_NAME_HERE');
amplitude.regenerateDeviceId();
amplitude.setDeviceId('CUSTOM_DEVICE_ID');
amplitude.logEvent('EVENT_IDENTIFIER_HERE', {
'color': 'blue',
'age': 20,
'key': 'value'
});
amplitude.logEvent('Clicked Homepage Button', { 'finished_flow': false, 'clicks': 15 });
amplitude.logEvent('EVENT_IDENTIFIER_HERE', { 'color': 'blue', 'age': 20, 'key': 'value' });
amplitude.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { });
amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' });
amplitude.setDeviceId('45f0954f-eb79-4463-ac8a-233a6f45a8f0');
amplitude.setDomain('.amplitude.com');
amplitude.setGroup('orgId', '15');
amplitude.setGroup('orgId', ['15', '16']);
amplitude.setUserId('joe@gmail.com');
amplitude.setUserProperties({ 'gender': 'female', 'sign_up_complete': true })
amplitude.setVersionName('1.12.3');
amplitude.isNewSession();
amplitude.getSessionId() === 123;
let identify = new amplitude.Identify().set('gender', 'female').set('age', 20);
amplitude.identify(identify);
amplitude.logRevenue(3.99, 1, 'product_1234');
amplitude.logRevenueV2(revenue);
identify = new amplitude.Identify().setOnce('sign_up_date', '08/24/2015');
amplitude.identify(identify);
identify = new amplitude.Identify().setOnce('sign_up_date', '09/14/2015');
amplitude.identify(identify);
client.init('API_KEY', 'USER_ID', {
saveEvents: true,
includeUtm: true,
includeReferrer: true,
batchEvents: true,
eventUploadThreshold: 50
}, function () { });
client.init('API_KEY', 'USER_ID', { includeReferrer: true, includeUtm: true });
client.init('API_KEY', 'USER_ID');
client.init('API_KEY');
identify = new amplitude.Identify().unset('gender').unset('age');
amplitude.identify(identify);
client.logEvent('Clicked Homepage Button', { 'finished_flow': false, 'clicks': 15 });
client.logEvent('EVENT_IDENTIFIER_HERE', { 'color': 'blue', 'age': 20, 'key': 'value' });
client.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { });
client.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' });
client.logEventWithTimestamp('EVENT_IDENTIFIER_HERE', { 'key': 'value' }, 1505430378000, (httpCode, response) => { });
client.setDeviceId('45f0954f-eb79-4463-ac8a-233a6f45a8f0');
client.setDomain('.amplitude.com');
client.setUserId('joe@gmail.com');
client.setOptOut(true);
client.setGroup('type', 'name');
client.setGroup('type', ['name', 'name2']);
client.setUserProperties({ 'gender': 'female', 'sign_up_complete': true });
client.setGlobalUserProperties({ 'gender': 'female', 'sign_up_complete': true });
client.setVersionName('1.12.3');
client.setSessionId(1505430378000);
client.options.logLevel = 'WARN';
client.getSessionId() === 123;
client.isNewSession() === true;
client.regenerateDeviceId();
client.clearUserProperties();
client.identify(identify);
client.logRevenue(3.99, 1, 'product_1234');
client.logRevenueV2(revenue);
identify = new amplitude.Identify().set('colors', ['rose', 'gold']).add('karma', 1).setOnce('sign_up_date', '2016-03-31');
identify = new amplitude.Identify().add('karma', 1).add('friends', 1);
amplitude.identify(identify);
identify = new amplitude.Identify().append('ab-tests', 'new-user-test').append('some_list', [1, 2, 3, 4, 'values']);
amplitude.identify(identify);
identify = new amplitude.Identify().prepend('ab-tests', 'new-user-test').prepend('some_list', [1, 2, 3, 4, 'values']);
amplitude.identify(identify);
identify = new amplitude.Identify()
.set('karma', 10)
.add('karma', 1)
.unset('karma');
amplitude.identify(identify);
identify = new amplitude.Identify().set('karma', 10).add('karma', 1).unset('karma');
identify = new amplitude.Identify().append('ab-tests', 'new-user-tests');
identify.append('some_list', [1, 2, 3, 4, 'values']);
identify = new amplitude.Identify().prepend('ab-tests', 'new-user-tests');
identify.prepend('some_list', [1, 2, 3, 4, 'values']);
identify = new amplitude.Identify().set('user_type', 'beta');
identify.set('name', { 'first': 'John', 'last': 'Doe' });
identify = new amplitude.Identify().setOnce('sign_up_date', '2016-04-01');
identify = new amplitude.Identify().unset('user_type').unset('age');
identify = new amplitude.Identify()
.set('colors', ['rose', 'gold'])
.append('ab-tests', 'campaign_a')
.append('existing_list', [4, 5]);
amplitude.identify(identify);
amplitude.setUserProperties({
gender: 'female',
age: 20
});
amplitude.clearUserProperties();
amplitude.setOptOut(true);
amplitude.setOptOut(false);
amplitude.setGroup('orgId', '15');
amplitude.setGroup('sport', ['soccer', 'tennis']);
// TODO: Implement those.
/*
var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3);
amplitude.logRevenueV2(revenue);
amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' });
*/
revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99);
revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99).setEventProperties({ 'city': 'San Francisco' });
revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99).setQuantity(5);
revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99).setRevenueType('purchase');
}
}

View File

@@ -1,61 +1,146 @@
// Type definitions for Amplitude SDK 2.12.1
// Type definitions for Amplitude SDK 4.4.0
// Project: https://github.com/amplitude/Amplitude-Javascript
// Definitions by: Arvydas Sidorenko <https://github.com/Asido>
// Definitions: https://github.com/Asido/DefinitelyTyped
// Dan Manastireanu <https://github.com/danmana>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module amplitude {
type Callback = (responseCode: number, responseBody: string, details?: { reason: string; }) => void;
type LogReturn = number | void;
interface Config {
apiEndpoint?: string;
batchEvents?: boolean;
cookieExpiration?: number;
cookieName?: string;
userId?: string;
deviceId?: string;
deviceIdFromUrlParam?: boolean;
domain?: string;
eventUploadPeriodMillis?: number;
eventUploadThreshold?: number;
forceHttps?: boolean;
includeGclid?: boolean;
includeReferrer?: boolean;
includeUtm?: boolean;
language?: string;
logLevel?: 'DISABLE' | 'ERROR' | 'WARN' | 'INFO';
optOut?: boolean;
platform?: string;
saveEvents?: boolean;
savedMaxCount?: number;
saveParamsReferrerOncePerSession?: boolean;
sessionTimeout?: number;
trackingOptions?: {
city?: boolean;
country?: boolean;
device_model?: boolean;
dma?: boolean;
ip_address?: boolean;
language?: boolean;
os_name?: boolean;
os_version?: boolean;
platform?: boolean;
region?: boolean;
version_name?: boolean;
},
unsentKey?: string;
unsentIdentifyKey?: string;
uploadBatchSize?: number;
}
export class Identify {
set(key: string, value: any): Identify;
setOnce(key: string, value: any): Identify;
add(key: string, value: number): Identify;
add(key: string, value: number | string): Identify;
append(key: string, value: any): Identify;
prepend(key: string, value: any): Identify;
unset(key: string): Identify;
}
export function init(apiKey: string): void;
export function init(apiKey: string, userId: string): void;
export function init(apiKey: string, userId: string, options: Config): void;
export function init(apiKey: string, userId: string, options: Config, callback: () => void): void;
export class Revenue {
setProductId(productId: string): Revenue;
setQuantity(quantity: number): Revenue;
setPrice(price: number): Revenue;
setRevenueType(revenueType: string): Revenue;
setEventProperties(eventProperties: any): Revenue;
}
export class AmplitudeClient {
constructor(instanceName?: string);
options: Config;
init(apiKey: string, userId?: string, config?: Config, callback?: (client: AmplitudeClient) => void): void;
setVersionName(versionName: string): void;
isNewSession(): boolean;
setSessionId(sessionId: number): void;
getSessionId(): number;
setDomain(domain: string): void;
setUserId(userId: string): void;
setDeviceId(id: string): void;
regenerateDeviceId(): void;
identify(identify_obj: Identify, opt_callback?: Callback): void;
setUserProperties(properties: any): void;
setGlobalUserProperties(properties: any): void;
clearUserProperties(): void;
setOptOut(enable: boolean): void;
setGroup(groupType: string, groupName: string | string[]): void;
logEvent(event: string, data?: any, callback?: Callback): LogReturn;
logEventWithGroups(event: string, data?: any, groups?: any, callback?: Callback): LogReturn;
logRevenueV2(revenue_obj: Revenue): LogReturn;
logRevenue(pric: number, quantity: number, product: string): LogReturn;
logEventWithTimestamp(event: string, data?: any, timestamp?: number, callback?: Callback): LogReturn;
}
// Proxy methods that get executed on the default AmplitudeClient instance (not all client methods are proxied)
export function init(apiKey: string, userId?: string, options?: Config, callback?: (client: AmplitudeClient) => void): void;
export function setVersionName(version: string): void;
export function isNewSession(): boolean;
export function getSessionId(): number;
export function setDomain(domain: string): void;
export function setUserId(userId: string): void;
export function setDeviceId(id: string): void;
export function regenerateDeviceId(): void;
export function identify(identify: Identify): void;
export function identify(identify: Identify, callback?: Callback): void;
export function setUserProperties(properties: Object): void;
export function setUserProperties(properties: any): void;
export function setGlobalUserProperties(properties: any): void;
export function clearUserProperties(): void;
export function setOptOut(optOut: boolean): void;
export function setGroup(groupType: string, groupName: string | string[]): void;
export function logEvent(event: string): void;
export function logEvent(event: string, data: Object): void;
export function logEvent(event: string, data: Object, callback: (httpCode: number, response: any) => void): void;
export function logEvent(event: string, data?: any, callback?: Callback): LogReturn;
export function logEventWithGroups(event: string, data?: any, groups?: any, callback?: Callback): LogReturn;
export function logRevenueV2(revenue_obj: Revenue): LogReturn;
export function logRevenue(pric: number, quantity: number, product: string): LogReturn;
export function logEventWithTimestamp(event: string, data?: any, timestamp?: number, callback?: Callback): LogReturn;
export function getInstance(instanceName?: string): AmplitudeClient;
export const __VERSION__: string;
export var options: Config;
}

View File

@@ -8,7 +8,7 @@
import * as Promise from 'bluebird';
import * as events from 'events';
import { Replies, Options, Message } from './properties';
import { Replies, Options, Message, GetMessage, ConsumeMessage } from './properties';
export * from './properties';
export interface Connection extends events.EventEmitter {
@@ -40,10 +40,10 @@ export interface Channel extends events.EventEmitter {
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message | null) => any, options?: Options.Consume): Promise<Replies.Consume>;
consume(queue: string, onMessage: (msg: ConsumeMessage | null) => any, options?: Options.Consume): Promise<Replies.Consume>;
cancel(consumerTag: string): Promise<Replies.Empty>;
get(queue: string, options?: Options.Get): Promise<Message | false>;
get(queue: string, options?: Options.Get): Promise<GetMessage | false>;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;

View File

@@ -145,12 +145,32 @@ export interface Message {
properties: MessageProperties;
}
export interface MessageFields {
export interface GetMessage extends Message {
fields: GetMessageFields;
}
export interface ConsumeMessage extends Message {
fields: ConsumeMessageFields;
}
export interface CommonMessageFields {
deliveryTag: number;
redelivered: boolean;
exchange: string;
routingKey: string;
messageCount: string;
}
export interface MessageFields extends CommonMessageFields {
messageCount?: number;
consumerTag?: string;
}
export interface GetMessageFields extends CommonMessageFields {
messageCount: number;
}
export interface ConsumeMessageFields extends CommonMessageFields {
deliveryTag: number;
}
export interface MessageProperties {

View File

@@ -2,6 +2,7 @@
"extends": "dtslint/dt.json",
"rules": {
// All are TODOs
"no-any-union": false,
"no-empty-interface": false,
"prefer-const": false
}

View File

@@ -17,6 +17,7 @@
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-angle-bracket-type-assertion": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,

View File

@@ -76,6 +76,7 @@ declare module 'angular' {
interface IConfirmDialog extends IPresetDialog<IConfirmDialog> {
cancel(cancel: string): IConfirmDialog;
multiple(multiple: boolean): IConfirmDialog;
}
interface IPromptDialog extends IPresetDialog<IPromptDialog> {
@@ -340,6 +341,7 @@ declare module 'angular' {
interface IMenuService {
hide(response?: any, options?: any): IPromise<any>;
open(event?: MouseEvent): void;
}
interface IColorPalette {

View File

@@ -17,6 +17,7 @@
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-angle-bracket-type-assertion": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,

View File

@@ -2,7 +2,8 @@
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,

View File

@@ -1,5 +1,5 @@
angular.module('promise-tracker-tests', []).run(['$q', 'promiseTracker',
($q: angular.IQService, promiseTracker: angular.promisetracker.PromiseTrackerService) => {
angular.module('promise-tracker-tests', []).run(['$q', '$http', 'promiseTracker',
($q: angular.IQService, $http: angular.IHttpService, promiseTracker: angular.promisetracker.PromiseTrackerService) => {
const trackerWithoutOptions = promiseTracker();
const options = {
@@ -19,4 +19,8 @@ angular.module('promise-tracker-tests', []).run(['$q', 'promiseTracker',
const addedPromise: angular.IDeferred<void> = trackerWithOptions.addPromise(promiseToAdd);
const trackerWithSomeOptions = promiseTracker({activationDelay: 500});
$http.post('/foo', {}, { });
$http.post('/foo', {}, { tracker: trackerWithOptions });
$http.post('/foo', {}, { tracker: [trackerWithoutOptions, trackerWithOptions] });
}]);

View File

@@ -28,4 +28,8 @@ declare module 'angular' {
(options?: PromiseTrackerOptions): PromiseTracker;
}
}
interface IRequestShortcutConfig {
tracker?: angular.promisetracker.PromiseTracker | angular.promisetracker.PromiseTracker[];
}
}

View File

@@ -6,7 +6,8 @@
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,

View File

@@ -16,6 +16,10 @@ angular
closeButton: false,
closeHtml: '<button>&times;</button>',
extendedTimeOut: 1000,
extraData: {
txt: "sample text",
action: () => {/* Do action */},
},
iconClasses: {
error: 'toast-error',
info: 'toast-info',
@@ -29,7 +33,6 @@ angular
progressBar: false,
tapToDismiss: true,
templates: {
toast: 'directives/toast/toast.html',
progressbar: 'directives/progressbar/progressbar.html'
},

View File

@@ -24,6 +24,7 @@ declare module 'angular' {
closeButton?: boolean;
closeHtml?: string;
extendedTimeOut?: number;
extraData?: any,
messageClass?: string;
onHidden?: (wasClicked: boolean, toast: angular.toastr.IToast) => void;
onShown?: (toast: angular.toastr.IToast) => void;

View File

@@ -16,6 +16,9 @@ interface SortLogInfo {
Text: string;
}
// Ensure that the jQuery-ui defined `sortable()` method is not overwritten
jQuery().sortable(); // $ExpectType JQuery<HTMLElement>
myApp.controller('sortableController', function ($scope: MySortableControllerScope) {
$scope.sortableOptions = {
activate: function(e, ui) {
@@ -84,6 +87,7 @@ myApp.controller('sortableController', function ($scope: MySortableControllerSco
update: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
ui.item.sortable; // $ExpectType UISortableProperties<SortableModelInfo>
var voidcanceled: void = ui.item.sortable.cancel();
var isCanceled: Boolean = ui.item.sortable.isCanceled();
var isCustomHelperUsed: Boolean =ui.item.sortable.isCustomHelperUsed();

View File

@@ -2,12 +2,16 @@
// Project: https://github.com/angular-ui/ui-sortable
// Definitions by: Thodoris Greasidis <https://github.com/thgreasi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 2.4
/// <reference types="angular" />
/// <reference types="jqueryui" />
import * as ng from 'angular';
// Diff / Omit taken from https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766
type Omit<T, K extends keyof T> = Pick<T, ({ [P in keyof T]: P } & { [P in K]: never } & { [x: string]: never, [x: number]: never })[keyof T]>;
declare module 'angular' {
export namespace ui {
@@ -79,11 +83,11 @@ declare module 'angular' {
isCustomHelperUsed(): Boolean;
}
interface UISortableUIItem<T> extends ng.IAugmentedJQuery {
interface UISortableUIItem<T> extends Omit<ng.IAugmentedJQuery, 'sortable'> {
sortable: UISortableProperties<T>;
}
interface UISortableUIParams<T> extends SortableUIParams {
interface UISortableUIParams<T> extends Omit<SortableUIParams, 'item'> {
item: UISortableUIItem<T>;
}

View File

@@ -2,7 +2,7 @@
// Project: https://github.com/mgonto/angular-wizard
// Definitions by: Marko Jurisic <https://github.com/mjurisic>, Ronald Wildenberg <https://github.com/rwwilden>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 2.8
import * as angular from 'angular';

View File

@@ -17,6 +17,7 @@
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-angle-bracket-type-assertion": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,

View File

@@ -4,7 +4,7 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
type FunctionBasedParamter = (element: HTMLElement, index: number, length: number) => number;
type FunctionBasedParameter = (element: HTMLElement, index: number, length: number) => number;
type AnimeCallbackFunction = (anim: anime.AnimeInstance) => void;
// Allowing null is necessary because DOM queries may not return anything.
type AnimeTarget = string | object | HTMLElement | SVGElement | NodeList | null;
@@ -55,10 +55,10 @@ declare namespace anime {
interface AnimeAnimParams {
targets: AnimeTarget | ReadonlyArray<AnimeTarget>;
duration?: number | FunctionBasedParamter;
delay?: number | FunctionBasedParamter;
elasticity?: number | FunctionBasedParamter;
round?: number | boolean | FunctionBasedParamter;
duration?: number | FunctionBasedParameter;
delay?: number | FunctionBasedParameter;
elasticity?: number | FunctionBasedParameter;
round?: number | boolean | FunctionBasedParameter;
easing?: EasingOptions | string | ReadonlyArray<number>;
@@ -106,7 +106,7 @@ declare namespace anime {
}
interface AnimeTimelineAnimParams extends AnimeAnimParams {
offset: number | string | FunctionBasedParamter;
offset: number | string | FunctionBasedParameter;
}
interface AnimeTimelineInstance extends AnimeInstance {

View File

@@ -3,7 +3,7 @@
// Definitions by: bryn austin bellomy <https://github.com/brynbellomy>
// plylrnsdy <https://github.com/plylrnsdy>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
import { EscapeCode } from './escape-code';

32
types/ansi/ansi-tests.ts Normal file
View File

@@ -0,0 +1,32 @@
import ansi = require('ansi');
const cursor = ansi(process.stdout);
Object.keys({
white: 37
, black: 30
, blue: 34
, cyan: 36
, green: 32
, magenta: 35
, red: 31
, yellow: 33
, grey: 90
, brightBlack: 90
, brightRed: 91
, brightGreen: 92
, brightYellow: 93
, brightBlue: 94
, brightMagenta: 95
, brightCyan: 96
, brightWhite: 97
}).forEach((color) => {
const cname = color.replace(/([a-z])([A-Z])/g, (_: string, l: string, u: string): string => `${l} ${u.toLowerCase()}`);
((<(...anything: any[]) => ansi.Cursor> cursor[color])()
.bold()
.bg)[color === 'blue' || color === 'brightBlue' ? 'black' : 'blue']()
.write(
`Hello, bold ${cname} world!\n`
)
.reset();
});

181
types/ansi/index.d.ts vendored Normal file
View File

@@ -0,0 +1,181 @@
// Type definitions for ansi 0.3
// Project: https://www.npmjs.com/package/ansi
// Definitions by: Gustavo6046 <https://github.com/Gustavo6046>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/**
* References:
*
* - http://en.wikipedia.org/wiki/ANSI_escape_code
* - http://www.termsys.demon.co.uk/vtansi.htm
*
*/
/// <reference types="node" />
import { Stream } from "stream";
interface CursorOptions {
enabled: boolean;
buffering: boolean;
}
declare function ansi(stream: Stream, options?: CursorOptions): ansi.Cursor;
declare namespace ansi {
class Cursor {
bg: Colorer;
fg: Colorer;
constructor(stream: Stream, options?: CursorOptions);
/**
* Helper function that calls `write()` on the underlying Stream.
* Returns `this` instead of the write() return value to keep
* the chaining going.
*/
write(data: string): Cursor;
/**
* Buffer `write()` calls into memory.
*
* @api public
*/
buffer(): Cursor;
/**
* Write out the in-memory buffer.
*
* @api public
*/
flush(): Cursor;
/**
* Makes a beep sound!
*/
beep(): Cursor;
/**
* Moves cursor to specific position
*/
goto(x?: number, y?: number): Cursor;
/**
* Resets all ANSI formatting on the stream.
*/
reset(): Cursor;
/**
* Sets the foreground color with the given RGB values.
* The closest match out of the 216 colors is picked.
*/
rgb(r: number, g: number, b: number): Cursor;
/**
* Accepts CSS color codes for use with ANSI escape codes.
* For example: `#FF000` would be bright red.
*/
hex(color: string): Cursor;
up(): Cursor;
down(): Cursor;
forward(): Cursor;
back(): Cursor;
nextLine(): Cursor;
previousLine(): Cursor;
horizontalAbsolute(): Cursor;
eraseData(): Cursor;
eraseLine(): Cursor;
scrollUp(): Cursor;
scrollDown(): Cursor;
savePosition(): Cursor;
restorePosition(): Cursor;
queryPosition(): Cursor;
hide(): Cursor;
show(): Cursor;
bold(): Cursor;
italic(): Cursor;
underline(): Cursor;
inverse(): Cursor;
resetbold(): Cursor;
resetitalic(): Cursor;
resetunderline(): Cursor;
resetinverse(): Cursor;
white(): Cursor;
black(): Cursor;
blue(): Cursor;
cyan(): Cursor;
green(): Cursor;
magenta(): Cursor;
red(): Cursor;
yellow(): Cursor;
grey(): Cursor;
brightBlack(): Cursor;
brightRed(): Cursor;
brightGreen(): Cursor;
brightYellow(): Cursor;
brightBlue(): Cursor;
brightMagenta(): Cursor;
brightCyan(): Cursor;
brightWhite(): Cursor;
}
/**
* The `Colorer` class manages both the background and foreground colors.
*/
class Colorer {
constructor(cursor: Cursor, base: string);
/**
* Write an ANSI color code, ensuring that the same code doesn't get rewritten.
*/
_setColorCode(code: string): Colorer;
/**
* Resets the color.
*/
reset(): Cursor;
/**
* Sets the foreground color with the given RGB values.
* The closest match out of the 216 colors is picked.
*/
rgb(r: number, g: number, b: number): Cursor;
/**
* Accepts CSS color codes for use with ANSI escape codes.
* For example: `#FF000` would be bright red.
*/
hex(color: string): Cursor;
white(): Cursor;
black(): Cursor;
blue(): Cursor;
cyan(): Cursor;
green(): Cursor;
magenta(): Cursor;
red(): Cursor;
yellow(): Cursor;
grey(): Cursor;
brightBlack(): Cursor;
brightRed(): Cursor;
brightGreen(): Cursor;
brightYellow(): Cursor;
brightBlue(): Cursor;
brightMagenta(): Cursor;
brightCyan(): Cursor;
brightWhite(): Cursor;
}
interface Cursor {
[key: string]: ((...anything: any[]) => Cursor) | Colorer;
}
interface Colorer {
[key: string]: (...anything: any[]) => (Cursor | Colorer);
}
}
export = ansi;

24
types/ansi/tsconfig.json Normal file
View File

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

1
types/ansi/tslint.json Normal file
View File

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

35
types/aos/aos-tests.ts Normal file
View File

@@ -0,0 +1,35 @@
import * as Aos from "aos";
const options: Aos.AosOptions = {
disable: () => true,
startEvent: "DOMContentLoaded",
initClassName: "aos-init",
animatedClassName: "aos-animate",
useClassNames: false,
offset: 120,
delay: 0,
duration: 400,
easing: "ease-in-out-back",
once: false,
mirror: false,
anchorPlacement: "center-bottom"
};
Aos.init();
Aos.init(options);
Aos.refresh();
Aos.refreshHard();
document.addEventListener("aos:in", event => {
event;
event.detail;
});
document.addEventListener("aos:out", () => {});
// aos also creates custom events for every unique id, which you can't cover in d.ts
document.addEventListener("aos:in:sectionId" as Aos.AosEventType, event => {
event.detail;
});

7
types/aos/global.d.ts vendored Normal file
View File

@@ -0,0 +1,7 @@
interface Document {
addEventListener(
type: Aos.AosEventType,
listener: (event: Aos.AosEvent) => void,
options?: boolean | AddEventListenerOptions
): void;
}

130
types/aos/index.d.ts vendored Normal file
View File

@@ -0,0 +1,130 @@
// Type definitions for aos 3.0
// Project: https://github.com/michalsnik/aos
// Definitions by: Rostislav Shermenyov <https://github.com/shermendev>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
declare namespace Aos {
type easingOptions =
| "linear"
| "ease"
| "ease-in"
| "ease-out"
| "ease-in-out"
| "ease-in-back"
| "ease-out-back"
| "ease-in-out-back"
| "ease-in-sine"
| "ease-out-sine"
| "ease-in-out-sine"
| "ease-in-quad"
| "ease-out-quad"
| "ease-in-out-quad"
| "ease-in-cubic"
| "ease-out-cubic"
| "ease-in-out-cubic"
| "ease-in-quart"
| "ease-out-quart"
| "ease-in-out-quart";
type anchorPlacementOptions =
| "top-bottom"
| "top-center"
| "top-top"
| "center-bottom"
| "center-center"
| "center-top"
| "bottom-bottom"
| "bottom-center"
| "bottom-top";
interface Aos {
/**
* Initializing AOS
* - Create options merging defaults with user defined options
* - Set attributes on <body> as global setting - css relies on it
* - Attach preparing elements to options.startEvent,
* window resize and orientation change
* - Attach function that handle scroll and everything connected to it
* to window scroll event and fire once document is ready to set initial state
* @param options options
*/
init(options?: AosOptions): void;
/**
* Refresh AOS
*/
refresh(): void;
/**
* Hard refresh
* create array with new elements and trigger refresh
*/
refreshHard(): void;
}
interface AosOptions {
// #region Global settings
/**
* Class applied on animation
*/
animatedClassName?: string;
/**
* Accepts following values: 'phone', 'tablet', 'mobile', boolean, expression or function
*/
disable?: "phone" | "tablet" | "mobile" | boolean | (() => boolean);
/**
* Class applied after initialization
*/
initClassName?: string;
/**
* Name of the event dispatched on the document, that AOS should initialize on
*/
startEvent?: string;
/**
* If true, will add content of `data-aos` as classes on scroll
*/
useClassNames?: boolean;
// #endregion
// #region Settings that can be overridden on per-element basis, by `data-aos-*` attributes
/**
* Defines which position of the element regarding to window should trigger the animation
*/
anchorPlacement?: anchorPlacementOptions;
/**
* Values from 0 to 3000, with step 50ms
*/
delay?: number;
/**
* Values from 0 to 3000, with step 50ms
*/
duration?: number;
/**
* Default easing for AOS animations
*/
easing?: easingOptions;
/**
* Whether elements should animate out while scrolling past them
*/
mirror?: boolean;
/**
* Offset (in px) from the original trigger point
*/
offset?: number;
/**
* Whether animation should happen only once - while scrolling down
*/
once?: boolean;
// #endregion
}
interface AosEvent extends Event {
detail: Element;
}
type AosEventType = "aos:in" | "aos:out";
}
declare const Aos: Aos.Aos;
export = Aos;
export as namespace Aos;

25
types/aos/tsconfig.json Normal file
View File

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

View File

@@ -12,7 +12,7 @@ type FontFamily =
| BaseCSSProperties['fontFamily']
| CSS.FontFace;
type Omit<T, K extends keyof T> = Pick<T, ({ [P in keyof T]: P } & { [P in K]: never } & { [x: string]: never, [x: number]: never })[keyof T]>;
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type CSSProperties = Omit<BaseCSSProperties, 'fontFamily' | 'transition' | 'animationName' > & {
fontFamily?: FontFamily | FontFamily[];

View File

@@ -2,7 +2,7 @@
// Project: https://github.com/apollographql/apollo-codegen
// Definitions by: Bradley Ayers <https://github.com/bradleyayers>, Maria Carrasco <https://github.com/kostspielig>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 2.6
import { Options } from 'graphql/utilities/schemaPrinter';

View File

@@ -2,7 +2,7 @@
// Project: https://github.com/jaydenseric/apollo-upload-client#readme
// Definitions by: Edward Sammut Alessi <https://github.com/Slessi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// TypeScript Version: 2.6
import { ApolloLink } from "apollo-link";
import { HttpOptions } from "apollo-link-http-common";

View File

@@ -2,7 +2,9 @@
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6", "dom"
"es6",
"dom",
"esnext.asynciterable"
],
"noImplicitAny": true,
"noImplicitThis": true,

View File

@@ -0,0 +1,27 @@
import { AposModuleOptions } from "apostrophe";
type CustomModules = "first-custom-widgets";
const firstCustomWidgetOptions: AposModuleOptions = {
extend: "apostrophe-widgets",
label: "First Custom Widget",
addFields: [
{
name: "title",
label: "Custom Widget Title",
type: "string"
}
]
};
const secondCustomWidgetOptions: AposModuleOptions<CustomModules> = {
extend: "first-custom-widgets",
label: "Second Custom Widget",
addFields: [
{
name: "title",
label: "Custom Widget Title",
type: "string"
}
]
};

328
types/apostrophe/index.d.ts vendored Normal file
View File

@@ -0,0 +1,328 @@
// Type definitions for apostrophe 2.67
// Project: https://github.com/apostrophecms/apostrophe#readme
// Definitions by: Aaron Holderman <https://github.com/afholderman>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
export = apostrophe;
export as namespace apos;
declare function apostrophe(
options: apostrophe.AposConstructor,
...args: any[]
): any;
declare namespace apostrophe {
const moogBundle: {
directory: string;
modules: string[];
};
// Pass in custom modules as first argument
// second argument is additional custom options e.g. restApi exposed by apostrophe-headless
interface AposConstructor<M = {}, O = {}> {
afterInit?: () => void;
afterListen?: () => void;
initFailed?: (error: any) => void;
baseUrl?: string;
modules: { [K in AposCoreModules & M]?: AposModuleOptions | O };
prefix?: string;
root?: string;
rootDir?: string;
shortName: string;
}
const ui: {
globalBusy: (state: any) => any;
link: (
sel: string,
verb: string,
object: object,
callback?: () => any
) => any;
};
const pages: {
page: { _id: string; type: string; _url?: string };
};
const adminBar: {
link: (name: string, callback: () => any) => void;
};
function change(arg: object | string): any;
function create(type: string, options: any, callback?: () => any): any;
const contextPiece: {
_id: string;
title: string;
slug: string;
type: string;
};
function define(
type: string | string[],
definition: any,
extending?: any
): any;
const docs: {
getManager: (type: string) => void;
setManager: (type: string, manager: any) => void;
lock: (id: string, callback?: () => any) => void;
lockAndWatch: (id: string, callback?: () => any) => void;
unlock: (_id: string, sync: any, callback?: () => any) => any;
};
function emit(name: string, arg?: any): any;
const modules: object;
const modalSupport: {
stack: any[];
initialized: boolean;
depth: number;
all: any[];
getTopModalOrBody: () => string;
getLatestModal: () => null | string;
closeTopModal: () => void;
cancelTopModal: () => void;
};
function notify(message: string | object, options: AposObject): any;
function off(eventName: string, fn?: () => any): any;
function on(eventName: string, fn?: () => any): any;
const schemas: {
convert: (
$el: HTMLElement,
schema: Schema,
data: any,
options: any,
callback?: () => any
) => any;
newInstance: (schema: Schema) => any;
populate: (
data: any,
name: string,
$field: any,
callback?: () => void,
$el?: HTMLElement,
field?: any
) => any;
returnToError: (
$el: HTMLElement,
schema: Schema,
errorPath: any,
error: any,
callback: () => any
) => void;
};
const utils: {
capitalizeFirst: (s: string) => string;
camelName: (s: string) => string;
error: (msg: string) => void;
generateId: () => string;
};
const versions: {
edit: (id: string, afterRevert?: () => void) => any;
};
interface AposObject {
[key: string]: any;
}
interface Field {
name: string;
type: string;
label: string;
help?: string;
required?: boolean;
options?: AposObject;
choices?: SelectChoice[];
widgetType?: string;
titleField?: string;
schema?: Field[];
}
interface SelectChoice {
label: string;
value: string;
}
type Fields = Field[];
interface AposType {
name: string;
converters: {
string(
req: any,
data: any,
name: string,
object: AposObject,
field: any,
callback: () => any
): void;
form(
req: any,
data: any,
name: string,
object: AposObject,
field: any,
callback: () => any
): void;
};
empty?(field: any, value: any): void;
bless?(req: any, field: any): void;
index(value: any, field: any, texts: any): void;
}
interface Schema {
createRoutes(): any[];
pushAssets(): void;
pushCreateSingleton(): void;
compose(options: AposObject): void;
refine(schema: Schema, options: AposObject): void;
toGroups(fields: Fields): void;
subset(schema: Schema, fields: Fields): Schema;
newInstance(schema: Schema): any;
subsetInstance(schema: Schema, instance: AposObject): any;
empty(schema: Schema, object: AposObject): void;
indexFields(schema: Schema, object: AposObject, texts: any): void;
convert(
req: any,
schema: Schema,
to: any,
object: AposObject,
output: any,
callback: () => any
): void;
isVisible(schema: Schema, object: AposObject, name: string): void;
export(
req: any,
schema: Schema,
to: any,
object: AposObject,
output: any,
callback: () => any
): void;
joinDriver(
req: any,
method: any,
reverse: any,
items: any,
idField: any,
relationshipsField: any,
objectField: any,
options: any,
callback: () => any
): void;
join(
req: any,
schema: Schema,
objectOrArray: any,
withJoins: any,
callback: () => any
): void;
addFieldType(type: AposType): void;
getFieldType(typeName: string): void;
addFilters(schema: Schema, options: any, cursor: any): void;
joinFilterChoices(field: any, cursor: any, valueField: any): void;
addJoinSlugFilter(field: any, cursor: any, suffix: any): void;
pageServe(req: any): void;
sortedDistinct(property: any, cursor: any, callback: () => any): void;
cursorFilterInterested(cursor: any, name: string): void;
afterInit(): void;
validate(schema: Schema, options: any): void;
}
interface AposModule {
emit(name: string): void;
on(name: string, methodName: any, fn: () => any): void;
}
type AposCoreModules =
| "apostrophe-admin-bar"
| "apostrophe-any-page-manager"
| "apostrophe-areas"
| "apostrophe-assets"
| "apostrophe-attachments"
| "apostrophe-browser-utils"
| "apostrophe-caches"
| "apostrophe-custom-pages"
| "apostrophe-db"
| "apostrophe-doc-type-manager"
| "apostrophe-docs"
| "apostrophe-email"
| "apostrophe-express"
| "apostrophe-files"
| "apostrophe-files-widgets"
| "apostrophe-global"
| "apostrophe-groups"
| "apostrophe-html-widgets"
| "apostrophe-i18n"
| "apostrophe-images"
| "apostrophe-images-widgets"
| "apostrophe-jobs"
| "apostrophe-launder"
| "apostrophe-locks"
| "apostrophe-login"
| "apostrophe-migrations"
| "apostrophe-modal"
| "apostrophe-module"
| "apostrophe-notifications"
| "apostrophe-oembed"
| "apostrophe-pager"
| "apostrophe-pages"
| "apostrophe-permissions"
| "apostrophe-pieces"
| "apostrophe-pieces-pages"
| "apostrophe-pieces-widgets"
| "apostrophe-polymorphic-manager"
| "apostrophe-push"
| "apostrophe-rich-text-widgets"
| "apostrophe-schemas"
| "apostrophe-search"
| "apostrophe-service-bridge"
| "apostrophe-soft-redirects"
| "apostrophe-tags"
| "apostrophe-tasks"
| "apostrophe-templates"
| "apostrophe-ui"
| "apostrophe-urls"
| "apostrophe-users"
| "apostrophe-utils"
| "apostrophe-versions"
| "apostrophe-video-fields"
| "apostrophe-video-widgets"
| "apostrophe-widgets";
// Pass in custom modules to AposModuleOptions to allow them in extend
interface AposModuleOptions<C = {}> {
extend: AposCoreModules | C;
name?: string;
label: string;
pluralLabel?: string;
playerData?: false | string[];
scene?: "user";
addFields?: Field[];
removeFields?: Field[];
arrangeFields?: {
name: string;
label: string;
fields: string[];
}[];
beforeConstruct?: (self: any, options: any) => any;
defer?: boolean;
filters?: {
projection?: {
[key: string]: number;
};
};
}
}

View File

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

View File

@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"array-type": [true, "array"]
}
}

View File

@@ -0,0 +1,7 @@
import { addPath, enableForDir, removePath } from 'app-module-path';
addPath('/tmp');
enableForDir('/tmp');
removePath('/tmp');

11
types/app-module-path/index.d.ts vendored Normal file
View File

@@ -0,0 +1,11 @@
// Type definitions for app-module-path 2.2
// Project: https://github.com/patrick-steele-idem/app-module-path-node
// Definitions by: Timur Manyanov <https://github.com/darkwebdev>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
export function addPath(path: string, parent?: any): void;
export function enableForDir(dir: string): void;
export function removePath(path: string): 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",
"app-module-path-tests.ts"
]
}

View File

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

View File

@@ -2,7 +2,7 @@
// Project: https://github.com/arangodb/arangodb
// Definitions by: Alan Plum <https://github.com/pluma>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 2.6
/// <reference types="node" />
@@ -1440,6 +1440,81 @@ declare module "@arangodb/foxx/router" {
export = createRouter;
}
declare module "@arangodb/foxx/queues" {
interface QueueItem {
name: string;
mount: string;
backOff?: ((failureCount: number) => number) | number;
maxFailures?: number;
schema?: Foxx.Schema;
preprocess?: (data: any) => any;
}
interface Script {
name: string;
mount: string;
}
type JobCallback = (result: any, jobData: any, job: ArangoDB.Document<Job>) => void;
interface Job {
status: string;
queue: string;
type: Script;
failures: object[];
runs: number;
data: any;
created: number;
modified: number;
delayUntil: number;
maxFailures: number;
repeatDelay: number;
repeatTimes: number;
repeatUntil: number;
success?: string;
failure?: string;
runFailures: number;
abort(): void;
}
interface JobOptions {
success?: JobCallback;
failure?: JobCallback;
delayUntil?: number | Date;
backOff?: ((failureCount: number) => number) | number;
maxFailures?: number;
repeatTimes?: number;
repeatUntil?: number | Date;
repeatDelay?: number;
}
interface Queue {
push(item: QueueItem, data: any, opts?: JobOptions): void;
get(jobId: string): ArangoDB.Document<Job>;
delete(jobId: string): boolean;
pending(script?: Script): string[];
progress(script?: Script): string[];
complete(script?: Script): string[];
failed(script?: Script): string[];
all(script?: Script): string[];
}
function createQueue(name: string, maxWorkers?: number): Queue;
function deleteQueue(name: string): boolean;
function get(name: string): Queue;
export {
createQueue as create,
deleteQueue as delete,
get,
JobOptions,
Job,
Queue,
QueueItem,
Script,
};
}
declare module "@arangodb/foxx/graphql" {
import { formatError, GraphQLSchema } from "graphql";
type GraphQLModule = object;
@@ -1698,7 +1773,7 @@ declare module "@arangodb/crypto" {
key: string | null,
token: string,
noVerify?: boolean
): string | null;
): object | null;
function md5(message: string): string;
function sha1(message: string): string;
function sha224(message: string): string;

View File

@@ -1,7 +1,7 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"lib": ["es6", "esnext.asynciterable"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,4 @@
// Type definitions for ArcGIS API for JavaScript 3.25
// Type definitions for ArcGIS API for JavaScript 3.26
// Project: https://developers.arcgis.com/javascript/3/
// Definitions by: Esri <https://github.com/Esri>
// Bjorn Svensson <https://github.com/bsvensson>
@@ -1897,6 +1897,8 @@ declare module "esri" {
export interface ReportPlayerOptions {
/** Indicates whether left and right arrows key can be used to paginate when viewMode is set to PlayerViewModes.PANELS_IN_SLIDES. */
allowKeyboardNavigation?: boolean;
/** As of version 3.26 Configuration to specify the location of the JavaScript API to use when exporting an Infographic to Dynamic HTML. */
config?: any;
/** Specifies which export options are available for the report. */
dataProvider?: DataProviderGE;
/** Specifies how the ReportPlayer should zoom by default. */
@@ -3506,7 +3508,7 @@ declare module "esri/dijit/Attribution" {
/**
* Creates a new Attribution object.
* @param options An object that defines the attribution options.
* @param srcNodeRef HTML element where the time slider should be rendered.
* @param srcNodeRef HTML element where the attribution widget should be rendered.
*/
constructor(options: esri.AttributionOptions, srcNodeRef: Node | string);
/** Destroy the attribution widget. */
@@ -7584,6 +7586,8 @@ declare module "esri/dijit/geoenrichment/ReportPlayer/ReportPlayer" {
class ReportPlayer {
/** Indicates whether left and right arrows key can be used to paginate when viewMode is set to PlayerViewModes.PANELS_IN_SLIDES. */
allowKeyboardNavigation: boolean;
/** Configuration to specify the location of the JavaScript API to use when exporting an Infographic to Dynamic HTML. */
config: any;
/** Data Provider for the ReportPlayer which allows you to specify which export options are available when running the report. */
dataProvider: DataProviderGE;
/** Specifies how the ReportPlayer should zoom by default. */
@@ -7607,7 +7611,7 @@ declare module "esri/dijit/geoenrichment/ReportPlayer/ReportPlayer" {
* @param params Various parameters that can be used to configure the ReportPlayer.
* @param srcNode Reference or id of the HTML element where the widget should be rendered.
*/
constructor(params: esri.ReportPlayerOptions, srcNode?: Node | string);
constructor(params?: esri.ReportPlayerOptions, srcNode?: Node | string);
/**
* Generates the report for the supplied parameters.
* @param dataProviderParams See the object specifications table below for the structure of the dataProviderParams object.

View File

@@ -69,6 +69,7 @@ export interface ArgumentParserOptions {
prog?: string;
usage?: string;
version?: string;
debug?: boolean;
}
export interface ArgumentGroupOptions {

View File

@@ -0,0 +1,47 @@
import flatMap = require("array.prototype.flatmap");
import "array.prototype.flatmap/auto";
import flatMapImpl = require("array.prototype.flatmap/implementation");
import getPolyfill = require("array.prototype.flatmap/polyfill");
import shim = require("array.prototype.flatmap/shim");
// infers type of the output array from the return type of the callback
flatMap(["foo"], word => word.split("")); // $ExpectType string[]
flatMapImpl(["foo"], word => word.split("")); // $ExpectType string[]
["foo"].flatMap(word => word.split("")); // $ExpectType string[]
// infers the type of the value argument to the callback
flatMap([1, 2], word => word.split("")); // $ExpectError
flatMapImpl([1, 2], word => word.split("")); // $ExpectError
[1, 2].flatMap(word => word.split("")); // $ExpectError
// the callback must return an array
flatMap([1, 2], word => word); // $ExpectError
flatMapImpl([1, 2], word => word); // $ExpectError
[1, 2].flatMap(word => word); // $ExpectError
// the callback accepts an index argument
flatMap(["foo"], (_, index) => [index]); // $ExpectType number[]
flatMapImpl(["foo"], (_, index) => [index]); // $ExpectType number[]
["foo"].flatMap((_, index) => [index]); // $ExpectType number[]
// the callback accepts an argument that refers to the original array
flatMap(["foo"], (_, __, input) => input); // $ExpectType string[]
flatMapImpl(["foo"], (_, __, input) => input); // $ExpectType string[]
["foo"].flatMap((_, __, input) => input); // $ExpectType string[]
// the third argument is used as the calling context for the callback
flatMap(["foo"], function() { return this.foo; }, { foo: [1, 2] }); // $ExpectType number[]
flatMapImpl(["foo"], function() { return this.foo; }, { foo: [1, 2] }); // $ExpectType number[]
["foo"].flatMap(function() { return this.foo; }, { foo: [1, 2] }); // $ExpectType number[]
// assumes that value of `this` in callback is `undefined` by default (this is
// accurate in strict mode)
flatMap([1], function() { return [this]; }); // $ExpectType undefined[]
flatMapImpl([1], function() { return [this]; }); // $ExpectType undefined[]
[1].flatMap(function() { return [this]; }); // $ExpectType undefined[]
// `getPolyfill` returns a flatMap implementation
getPolyfill()(["foo"], word => word.split("")); // $ExpectType string[]
// `shim` installs a flatMap implementation in `Array` prototype and returns it
shim()(["foo"], word => word.split("")); // $ExpectType string[]

View File

@@ -0,0 +1,6 @@
interface Array<T> {
flatMap<U, R extends object | undefined = undefined>(
fn: (this: R, x: T, index: number, array: this) => U[],
thisArg?: R
): U[];
}

View File

@@ -0,0 +1,7 @@
// This is the same type as the callable signature in `FlatMap` in `index.d.ts`.
declare function flatMap<A, B, T extends object | undefined = undefined>(
xs: ReadonlyArray<A>,
fn: (this: T, x: A, index: number, array: A[]) => B[],
thisArg?: T
): B[];
export = flatMap;

View File

@@ -0,0 +1,21 @@
// Type definitions for array.prototype.flatmap 1.2
// Project: https://github.com/es-shims/Array.prototype.flatMap#readme
// Definitions by: Jesse Hallett <https://github.com/hallettj>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import flatMapImpl = require("./implementation");
interface FlatMap {
<A, B, T extends object | undefined = undefined>(
xs: ReadonlyArray<A>,
fn: (this: T, x: A, index: number, array: A[]) => B[],
thisArg?: T
): B[];
getPolyfill(): typeof flatMapImpl;
implementation: typeof flatMapImpl;
shim(): typeof flatMapImpl;
}
declare const flatMap: FlatMap;
export = flatMap;

View File

@@ -0,0 +1,4 @@
import flatMap = require("./implementation");
declare function getPolyfill(): typeof flatMap;
export = getPolyfill;

View File

@@ -0,0 +1,4 @@
import flatMap = require("./implementation");
declare function shim(): typeof flatMap;
export = shim;

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"array.prototype.flatmap-tests.ts",
"auto.d.ts",
"implementation.d.ts",
"index.d.ts",
"polyfill.d.ts",
"shim.d.ts"
]
}

View File

@@ -0,0 +1,193 @@
import art from 'ascii-art';
art.font('test', 'doom').toPromise();
art.font('my text', 'Doom', (rendered: string) => {
rendered.big();
});
art.font('my text', 'Doom', '', (rendered) => {
rendered.big();
});
art.artwork({
artwork: 'textfiles.com/art/st-char.asc'
}).lines(31, 45, (rendered: string) => {
// cleanup non-unix terminators
rendered = rendered.replace(/\r/g, '');
art.image({
filepath : '~/Images/earth_in_space.jpg',
alphabet : 'ultra-wide'
}).overlay(rendered, {
x: 0,
y: -1,
style: 'red+blink',
transparent: '&'
}, (_final: any) => {});
});
art.font('Ghost Wire BBS', 'Doom', (logo) => {
art.font('No place like home', 'rusted', (subtext) => {
art.table({
verticalBar : ' ',
horizontalBar : ' ',
intersection : ' ',
data: [
{name: art.style('current users', 'red'), value: '203'},
{name: 'operator', value: 'vince.vega'},
{name: 'dial-in', value: '(917)555-4202'},
]
}).lines(2, (table: any) => {
art.image({
filepath : '~/Images/starburst_red.jpg',
alphabet : 'ultra-wide'
}).lines(2, 30).overlay(logo, {
x: 0,
y: 0,
style: 'blue',
}).overlay(subtext, {
x: 19,
y: 8,
style: 'yellow',
}).overlay(table, {
x: -1,
y: -1,
style: 'green',
}, (_final: any) => {
});
});
});
});
art.image({
width : 40,
filepath : '/Images/initech.png',
alphabet : 'wide'
}).font('INITECH', 'Doom', 'cyan', (_ascii) => {
});
art.table({
data: [
{text: ' .\'ANDRE. '},
{text: ' ..THE.GIANT\'. '},
{text: '.With.Bobby."The.Brain"'},
{text: '.Heenan.'}
],
verticalBar : ' ',
horizontalBar : ' ',
intersection : ' '
}).lines(2, (table: any) => {
art.strings([
'ANDRE',
'the',
'GIANT',
'POSSE',
'7\'4"',
'520 LB'
], 'rusted', (andre: any, the: any, giant: any, posse: any, height: any, weight: any) => {
art.strings([ 'has', 'a'], 'twopoint', (has: any, a: any) => {
art.image({
filepath : '/Images/andre_has_a_posse.jpeg',
alphabet : 'ultra-wide'
}).overlay(andre, {
x: 8, y: 4,
style: 'white'
}).overlay(the, {
x: 10, y: 7,
style: 'white',
transparent : true
}).overlay(giant, {
x: 8, y: 10,
style: 'white',
transparent : true
}).overlay(has, {
x: 10, y: 14,
style: 'white'
}).overlay(a, {
x: 13, y: 17,
style: 'white'
}).overlay(posse, {
x: 5, y: 20,
style: 'bright_black',
transparent: true
}).overlay(height, {
x: 59, y: 3,
style: 'bright_black',
transparent: true
}).overlay(weight, {
x: 59, y: 8,
style: 'bright_black',
transparent: true
}).overlay(table, {
x: 6, y: -6,
style: 'bright_black',
transparent: true
}, (_final: any) => {
});
});
});
});
art.Figlet.fontPath = 'Fonts';
const image = new art.Image({
filepath: '~/Images/metropolis.jpg',
alphabet: 'variant4'
});
image.write((_err: any, _rendered: string) => {
});
art.font('Prompt', 'Basic', 'red').font('v1', 'Doom', 'magenta', (_rendered) => {
});
art.image({
width : 40,
filepath : '/Images/initech.png',
alphabet : 'wide'
}).font('INITECH', 'Doom', 'cyan', (_ascii) => {
});
art.style('my text', 'red+underline');
art.table({
width : 80,
data : [ /* ... */ ],
verticalBar : ' ',
horizontalBar : ' ',
intersection : ' ',
columns : [
{
value : 'Product',
style : 'black+gray_bg'
}, {
value : 'Maker',
style : 'white'
}, {
value : 'Location',
style : 'white'
}
]
}, (_rendered) => {
// use rendered text
});
art.table({
width : 80,
data : [ /* ... */ ],
bars : {
ul_corner: '┏',
ur_corner: '┓',
lr_corner: '┛',
ll_corner: '┗',
bottom_t: '┻',
top_t: '┳',
right_t: '┫',
left_t: '┣',
intersection: '╋',
vertical: '┃',
horizontal: '━',
},
borderColor : 'bright_white',
}, (_rendered) => {
// use rendered text
});

43
types/ascii-art/index.d.ts vendored Normal file
View File

@@ -0,0 +1,43 @@
// Type definitions for ascii-art 1.4
// Project: https://github.com/khrome/ascii-art
// Definitions by: Lukas Elmer <https://github.com/lukaselmer>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export type StyleType = (text: string, style?: string, close?: boolean) => Art;
export type FontType = ((text: string, font?: string, styleOrCallback?: string | Cb, callback?: Cb) => Art);
export type ImageType = (options: object, callback?: Cb) => Art;
export type TableType = (options: object, callback?: Cb) => Art;
export type ArtworkType = (options: object, callback?: Cb) => Art;
export type LinesType = (...options: any[]) => Art;
export type OverlayType = (...options: any[]) => Art;
export type JoinType = (...options: any[]) => Art;
export type StringsType = (...options: any[]) => Art;
export const style: StyleType;
export const font: FontType;
export const image: ImageType;
export const table: TableType;
export const artwork: ArtworkType;
export const lines: LinesType;
export const overlay: OverlayType;
export const join: JoinType;
export const strings: StringsType;
export const Figlet: any;
export const Image: any;
export interface Art {
style: StyleType;
font: FontType;
image: ImageType;
table: TableType;
artwork: ArtworkType;
lines: LinesType;
overlay: OverlayType;
join: JoinType;
working: boolean;
toPromise: (() => Promise<string>);
}
export type Cb = (result: string) => void;

View File

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

View File

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

View File

@@ -7,29 +7,31 @@ export = A2MML;
declare var A2MML: ascii2mathml;
interface Options {
decimalMark?: string;
colSep?: string;
rowSep?: string;
display?: 'inline' | 'block';
dir?: 'ltr' | 'rtl';
bare?: boolean;
standalone?: boolean;
annotate?: boolean;
}
interface ascii2mathml {
/**
* Generates a function with default options set to convert
* ASCIIMath expression to MathML markup.
* @param options Options
*/
(options: Options): ascii2mathml;
(options: A2MML.Options): ascii2mathml;
/**
* Converts ASCIIMath expression to MathML markup.
* @param asciimath ASCIIMath expression
* @param options Options
*/
(asciimath: string, options?: Options): string;
(asciimath: string, options?: A2MML.Options): string;
}
declare namespace A2MML {
interface Options {
decimalMark?: string;
colSep?: string;
rowSep?: string;
display?: 'inline' | 'block';
dir?: 'ltr' | 'rtl';
bare?: boolean;
standalone?: boolean;
annotate?: boolean;
}
}

View File

@@ -0,0 +1,10 @@
import * as assert from 'assert';
assert(true, "it's working");
assert.ok(true, "inner functions work as well");
assert.throws(() => {});
assert.throws(() => {}, () => {}, "works wonderfully");
assert['fail'](true, true, "works like a charm");

45
types/assert/index.d.ts vendored Normal file
View File

@@ -0,0 +1,45 @@
// Type definitions for commonjs-assert 1.4
// Project: https://github.com/browserify/commonjs-assert
// Definitions by: Nico Gallinal <https://github.com/nicoabie>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function assert(value: any, message?: string): void;
declare namespace assert {
function fail(actual?: any, expected?: any, message?: string, operator?: string): void;
function ok(value: any, message?: string): void;
function equal(actual: any, expected: any, message?: string): void;
function notEqual(actual: any, expected: any, message?: string): void;
function deepEqual(actual: any, expected: any, message?: string): void;
function notDeepEqual(acutal: any, expected: any, message?: string): void;
function strictEqual(actual: any, expected: any, message?: string): void;
function notStrictEqual(actual: any, expected: any, message?: string): void;
function throws(block: () => void, message?: string): void;
function throws(block: () => void, error: () => void | ((err: any) => boolean) | RegExp, message?: string): void;
function doesNotThrow(block: () => void, message?: string): void;
function doesNotThrow(block: () => void, error: () => void | ((err: any) => boolean) | RegExp, message?: string): void;
function ifError(value: any): void;
class AssertionError implements Error {
name: string;
message: string;
actual: any;
expected: any;
operator: string;
generatedMessage: boolean;
constructor(options?: { message?: string; actual?: any; expected?: any; operator?: string; stackStartFunction?: () => void });
}
}
export = assert;

View File

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

3
types/assert/tslint.json Normal file
View File

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

50
types/astring/index.d.ts vendored Normal file
View File

@@ -0,0 +1,50 @@
// Type definitions for astring 1.3
// Project: https://github.com/davidbonnet/astring
// Definitions by: Nikolaj Kappler <https://github.com/nkappler>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import * as ESTree from 'estree';
import 'node';
import { Stream } from 'stream';
export interface Options {
/** string to use for indentation (defaults to " ") */
indent?: string;
/** string to use for line endings (defaults to "\n") */
lineEnd?: string;
/** indent level to start from (defaults to 0) */
startingIndentLevel?: number;
/** generate comments if true (defaults to false) */
comments?: boolean;
/** custom code generator (defaults to astring.baseGenerator) */
generator?: object;
/** source map generator (defaults to null), see https://github.com/mozilla/source-map#sourcemapgenerator */
sourceMap?: any;
}
/** Returns a string representing the rendered code of the provided AST `node`. However, if an `output` stream is provided in the options, it writes to that stream and returns it. */
export function generate(node: ESTree.Node, options?: Options): string;
/** Returns a string representing the rendered code of the provided AST `node`. However, if an `output` stream is provided in the options, it writes to that stream and returns it. */
export function generate(node: ESTree.Node, options: Options & {
/** output stream to write the rendered code to (defaults to null) */
output: Stream;
}): Stream;
/**
* A code generator consists of a mapping of node names and functions that take two arguments: `node` and `state`.
* The `node` points to the node from which to generate the code and the `state` exposes the `write` method that takes generated code strings.
*/
export type Generator = { [key in ESTree.Node["type"]]: (node: Extract<ESTree.Node, { type: key }>, state: { write(s: string): void }) => void };
/** Base generator that can be used to extend Astring. See https://github.com/davidbonnet/astring#extending */
export const baseGenerator: Generator;
declare global {
interface astring {
generate: typeof generate;
/** Base generator that can be used to extend Astring. See https://github.com/davidbonnet/astring#extending */
baseGenerator: Generator;
}
const astring: astring;
}

View File

@@ -0,0 +1,5 @@
// global scope function
astring.generate(null);
// global scope function
astring.baseGenerator.Program(null, { write(s: string) { return; } });

View File

@@ -0,0 +1,32 @@
import { baseGenerator, generate } from "astring";
import { FunctionExpression, MemberExpression, Program } from "estree";
import { Stream } from "stream";
const ast: Program = null;
const functionE: FunctionExpression = null;
const memberE: MemberExpression = null;
// should accept different nodes
generate(ast);
generate(functionE);
generate(memberE);
// options without output option should generate string
const string: string = generate(ast, {
comments: true,
generator: baseGenerator,
indent: "\t",
lineEnd: "\n",
startingIndentLevel: 42,
sourceMap: null
});
// options with output option should return Stream
const stream: Stream = generate(ast, {
output: new Stream()
});
// Generator should map node types to functions whose first parameter is same node type
baseGenerator.Program(ast, { write(s: string) { return; } });
baseGenerator.FunctionExpression(functionE, { write(s: string) { return; } });
baseGenerator.MemberExpression(memberE, { write(s: string) { return; } });

View File

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

View File

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

154
types/async/index.d.ts vendored
View File

@@ -2,34 +2,34 @@
// Project: https://github.com/caolan/async
// Definitions by: Boris Yankov <https://github.com/borisyankov>, Arseniy Maximov <https://github.com/kern0>, Joe Herman <https://github.com/Penryn>, Angus Fenying <https://github.com/fenying>, Pascal Martin <https://github.com/pascalmartin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
// TypeScript Version: 2.3
export as namespace async;
export interface Dictionary<T> { [key: string]: T; }
export type IterableCollection<T> = T[] | IterableIterator<T> | Dictionary<T>
export interface ErrorCallback<T> { (err?: T): void; }
export interface AsyncBooleanResultCallback<E> { (err?: E, truthValue?: boolean): void; }
export interface AsyncResultCallback<T, E> { (err?: E, result?: T): void; }
export interface AsyncResultArrayCallback<T, E> { (err?: E, results?: Array<T | undefined>): void; }
export interface AsyncResultObjectCallback<T, E> { (err: E | undefined, results: Dictionary<T | undefined>): void; }
export interface ErrorCallback<E = Error> { (err?: E | null): void; }
export interface AsyncBooleanResultCallback<E = Error> { (err?: E | null, truthValue?: boolean): void; }
export interface AsyncResultCallback<T, E = Error> { (err?: E | null, result?: T): void; }
export interface AsyncResultArrayCallback<T, E = Error> { (err?: E | null, results?: Array<T | undefined>): void; }
export interface AsyncResultObjectCallback<T, E = Error> { (err: E | undefined, results: Dictionary<T | undefined>): void; }
export interface AsyncFunction<T, E> { (callback: (err?: E, result?: T) => void): void; }
export interface AsyncFunctionEx<T, E> { (callback: (err?: E, ...results: T[]) => void): void; }
export interface AsyncIterator<T, E> { (item: T, callback: ErrorCallback<E>): void; }
export interface AsyncForEachOfIterator<T, E> { (item: T, key: number|string, callback: ErrorCallback<E>): void; }
export interface AsyncResultIterator<T, R, E> { (item: T, callback: AsyncResultCallback<R, E>): void; }
export interface AsyncMemoIterator<T, R, E> { (memo: R | undefined, item: T, callback: AsyncResultCallback<R, E>): void; }
export interface AsyncBooleanIterator<T, E> { (item: T, callback: AsyncBooleanResultCallback<E>): void; }
export interface AsyncFunction<T, E = Error> { (callback: (err?: E | null, result?: T) => void): void; }
export interface AsyncFunctionEx<T, E = Error> { (callback: (err?: E | null, ...results: T[]) => void): void; }
export interface AsyncIterator<T, E = Error> { (item: T, callback: ErrorCallback<E>): void; }
export interface AsyncForEachOfIterator<T, E = Error> { (item: T, key: number|string, callback: ErrorCallback<E>): void; }
export interface AsyncResultIterator<T, R, E = Error> { (item: T, callback: AsyncResultCallback<R, E>): void; }
export interface AsyncMemoIterator<T, R, E = Error> { (memo: R | undefined, item: T, callback: AsyncResultCallback<R, E>): void; }
export interface AsyncBooleanIterator<T, E = Error> { (item: T, callback: AsyncBooleanResultCallback<E>): void; }
export interface AsyncWorker<T, E> { (task: T, callback: ErrorCallback<E>): void; }
export interface AsyncVoidFunction<E> { (callback: ErrorCallback<E>): void; }
export interface AsyncWorker<T, E = Error> { (task: T, callback: ErrorCallback<E>): void; }
export interface AsyncVoidFunction<E = Error> { (callback: ErrorCallback<E>): void; }
export type AsyncAutoTasks<R extends Dictionary<any>, E> = { [K in keyof R]: AsyncAutoTask<R[K], R, E> }
export type AsyncAutoTask<R1, R extends Dictionary<any>, E> = AsyncAutoTaskFunctionWithoutDependencies<R1, E> | (keyof R | AsyncAutoTaskFunction<R1, R, E>)[];
export interface AsyncAutoTaskFunctionWithoutDependencies<R1, E> { (cb: AsyncResultCallback<R1, E> | ErrorCallback<E>): void; }
export interface AsyncAutoTaskFunction<R1, R extends Dictionary<any>, E> { (results: R, cb: AsyncResultCallback<R1, E> | ErrorCallback<E>): void; }
export interface AsyncAutoTaskFunctionWithoutDependencies<R1, E = Error> { (cb: AsyncResultCallback<R1, E> | ErrorCallback<E>): void; }
export interface AsyncAutoTaskFunction<R1, R extends Dictionary<any>, E = Error> { (results: R, cb: AsyncResultCallback<R1, E> | ErrorCallback<E>): void; }
export interface AsyncQueue<T> {
length(): number;
@@ -37,9 +37,8 @@ export interface AsyncQueue<T> {
running(): number;
idle(): boolean;
concurrency: number;
push<E>(task: T | T[], callback?: ErrorCallback<E>): void;
push<R,E>(task: T, callback?: AsyncResultCallback<R, E>): void;
unshift<E>(task: T | T[], callback?: ErrorCallback<E>): void;
push<R,E = Error>(task: T | T[], callback?: AsyncResultCallback<R, E>): void;
unshift<E = Error>(task: T | T[], callback?: ErrorCallback<E>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
@@ -61,7 +60,7 @@ export interface AsyncPriorityQueue<T> {
concurrency: number;
started: boolean;
paused: boolean;
push<R,E>(task: T | T[], priority: number, callback?: AsyncResultArrayCallback<R, E>): void;
push<R,E = Error>(task: T | T[], priority: number, callback?: AsyncResultArrayCallback<R, E>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
@@ -94,112 +93,113 @@ export interface AsyncCargo {
}
// Collections
export function each<T, E>(arr: IterableCollection<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export function each<T, E = Error>(arr: IterableCollection<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export const eachSeries: typeof each;
export function eachLimit<T, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export function eachLimit<T, E = Error>(arr: IterableCollection<T>, limit: number, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export const forEach: typeof each;
export const forEachSeries: typeof each;
export const forEachLimit: typeof eachLimit;
export function forEachOf<T, E>(obj: IterableCollection<T>, iterator: AsyncForEachOfIterator<T, E>, callback?: ErrorCallback<E>): void;
export function forEachOf<T, E = Error>(obj: IterableCollection<T>, iterator: AsyncForEachOfIterator<T, E>, callback?: ErrorCallback<E>): void;
export const forEachOfSeries: typeof forEachOf;
export function forEachOfLimit<T, E>(obj: IterableCollection<T>, limit: number, iterator: AsyncForEachOfIterator<T, E>, callback?: ErrorCallback<E>): void;
export function forEachOfLimit<T, E = Error>(obj: IterableCollection<T>, limit: number, iterator: AsyncForEachOfIterator<T, E>, callback?: ErrorCallback<E>): void;
export const eachOf: typeof forEachOf;
export const eachOfSeries: typeof forEachOf;
export const eachOfLimit: typeof forEachOfLimit;
export function map<T, R, E>(arr: T[] | IterableIterator<T>, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function map<T, R, E>(arr: Dictionary<T>, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function map<T, R, E = Error>(arr: T[] | IterableIterator<T>, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function map<T, R, E = Error>(arr: Dictionary<T>, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export const mapSeries: typeof map;
export function mapLimit<T, R, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function mapValuesLimit<T, R, E>(obj: Dictionary<T>, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback<R, E>) => void, callback: AsyncResultObjectCallback<R, E>): void;
export function mapValues<T, R, E>(obj: Dictionary<T>, iteratee: (value: T, key: string, callback: AsyncResultCallback<R, E>) => void, callback: AsyncResultObjectCallback<R, E>): void;
export function mapLimit<T, R, E = Error>(arr: IterableCollection<T>, limit: number, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function mapValuesLimit<T, R, E = Error>(obj: Dictionary<T>, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback<R, E>) => void, callback: AsyncResultObjectCallback<R, E>): void;
export function mapValues<T, R, E = Error>(obj: Dictionary<T>, iteratee: (value: T, key: string, callback: AsyncResultCallback<R, E>) => void, callback: AsyncResultObjectCallback<R, E>): void;
export const mapValuesSeries: typeof mapValues;
export function filter<T, E>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export function filter<T, E = Error>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export const filterSeries: typeof filter;
export function filterLimit<T, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export function filterLimit<T, E = Error>(arr: IterableCollection<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export const select: typeof filter;
export const selectSeries: typeof filter;
export const selectLimit: typeof filterLimit;
export const reject: typeof filter;
export const rejectSeries: typeof filter;
export const rejectLimit: typeof filterLimit;
export function reduce<T, R, E>(arr: T[] | IterableIterator<T>, memo: R, iterator: AsyncMemoIterator<T, R, E>, callback?: AsyncResultCallback<R, E>): void;
export function reduce<T, R, E = Error>(arr: T[] | IterableIterator<T>, memo: R, iterator: AsyncMemoIterator<T, R, E>, callback?: AsyncResultCallback<R, E>): void;
export const inject: typeof reduce;
export const foldl: typeof reduce;
export const reduceRight: typeof reduce;
export const foldr: typeof reduce;
export function detect<T, E>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultCallback<T, E>): void;
export function detect<T, E = Error>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultCallback<T, E>): void;
export const detectSeries: typeof detect;
export function detectLimit<T, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultCallback<T, E>): void;
export function detectLimit<T, E = Error>(arr: IterableCollection<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultCallback<T, E>): void;
export const find: typeof detect;
export const findSeries: typeof detect;
export const findLimit: typeof detectLimit;
export function sortBy<T, V, E>(arr: T[] | IterableIterator<T>, iterator: AsyncResultIterator<T, V, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export function some<T, E>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export function sortBy<T, V, E = Error>(arr: T[] | IterableIterator<T>, iterator: AsyncResultIterator<T, V, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export function some<T, E = Error>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export const someSeries: typeof some;
export function someLimit<T, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export function someLimit<T, E = Error>(arr: IterableCollection<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export const any: typeof some;
export const anySeries: typeof someSeries;
export const anyLimit: typeof someLimit;
export function every<T, E>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export function every<T, E = Error>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export const everySeries: typeof every;
export function everyLimit<T, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export function everyLimit<T, E = Error>(arr: IterableCollection<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export const all: typeof every;
export const allSeries: typeof every;
export const allLimit: typeof everyLimit;
export function concat<T, R, E>(arr: IterableCollection<T>, iterator: AsyncResultIterator<T, R[], E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function concatLimit<T, R, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncResultIterator<T, R[], E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function concat<T, R, E = Error>(arr: IterableCollection<T>, iterator: AsyncResultIterator<T, R[], E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function concatLimit<T, R, E = Error>(arr: IterableCollection<T>, limit: number, iterator: AsyncResultIterator<T, R[], E>, callback?: AsyncResultArrayCallback<R, E>): void;
export const concatSeries: typeof concat;
// Control Flow
export function series<T, E>(tasks: AsyncFunction<T, E>[], callback?: AsyncResultArrayCallback<T, E>): void;
export function series<T, E>(tasks: Dictionary<AsyncFunction<T, E>>, callback?: AsyncResultObjectCallback<T, E>): void;
export function parallel<T, E>(tasks: Array<AsyncFunction<T, E>>, callback?: AsyncResultArrayCallback<T, E>): void;
export function parallel<T, E>(tasks: Dictionary<AsyncFunction<T, E>>, callback?: AsyncResultObjectCallback<T, E>): void;
export function parallelLimit<T, E>(tasks: Array<AsyncFunction<T, E>>, limit: number, callback?: AsyncResultArrayCallback<T, E>): void;
export function parallelLimit<T, E>(tasks: Dictionary<AsyncFunction<T, E>>, limit: number, callback?: AsyncResultObjectCallback<T, E>): void;
export function whilst<E>(test: () => boolean, fn: AsyncVoidFunction<E>, callback: ErrorCallback<E>): void;
export function doWhilst<T, E>(fn: AsyncFunctionEx<T, E>, test: (...results: T[]) => boolean, callback: ErrorCallback<E>): void;
export function until<E>(test: () => boolean, fn: AsyncVoidFunction<E>, callback: ErrorCallback<E>): void;
export function doUntil<T, E>(fn: AsyncFunctionEx<T, E>, test: (...results: T[]) => boolean, callback: ErrorCallback<E>): void;
export function during<E>(test: (testCallback : AsyncBooleanResultCallback<E>) => void, fn: AsyncVoidFunction<E>, callback: ErrorCallback<E>): void;
export function doDuring<E>(fn: AsyncVoidFunction<E>, test: (testCallback: AsyncBooleanResultCallback<E>) => void, callback: ErrorCallback<E>): void;
export function forever<E>(next: (next : ErrorCallback<E>) => void, errBack: ErrorCallback<E>) : void;
export function waterfall<T, E>(tasks: Function[], callback?: AsyncResultCallback<T, E | Error>): void;
export function series<T, E = Error>(tasks: AsyncFunction<T, E>[], callback?: AsyncResultArrayCallback<T, E>): void;
export function series<T, E = Error>(tasks: Dictionary<AsyncFunction<T, E>>, callback?: AsyncResultObjectCallback<T, E>): void;
export function parallel<T, E = Error>(tasks: Array<AsyncFunction<T, E>>, callback?: AsyncResultArrayCallback<T, E>): void;
export function parallel<T, E = Error>(tasks: Dictionary<AsyncFunction<T, E>>, callback?: AsyncResultObjectCallback<T, E>): void;
export function parallelLimit<T, E = Error>(tasks: Array<AsyncFunction<T, E>>, limit: number, callback?: AsyncResultArrayCallback<T, E>): void;
export function parallelLimit<T, E = Error>(tasks: Dictionary<AsyncFunction<T, E>>, limit: number, callback?: AsyncResultObjectCallback<T, E>): void;
export function whilst<E = Error>(test: () => boolean, fn: AsyncVoidFunction<E>, callback: ErrorCallback<E>): void;
export function doWhilst<T, E = Error>(fn: AsyncFunctionEx<T, E>, test: (...results: T[]) => boolean, callback: ErrorCallback<E>): void;
export function until<E = Error>(test: () => boolean, fn: AsyncVoidFunction<E>, callback: ErrorCallback<E>): void;
export function doUntil<T, E = Error>(fn: AsyncFunctionEx<T, E>, test: (...results: T[]) => boolean, callback: ErrorCallback<E>): void;
export function during<E = Error>(test: (testCallback : AsyncBooleanResultCallback<E>) => void, fn: AsyncVoidFunction<E>, callback: ErrorCallback<E>): void;
export function doDuring<E = Error>(fn: AsyncVoidFunction<E>, test: (testCallback: AsyncBooleanResultCallback<E>) => void, callback: ErrorCallback<E>): void;
export function forever<E = Error>(next: (next : ErrorCallback<E>) => void, errBack: ErrorCallback<E>) : void;
export function waterfall<T, E = Error>(tasks: Function[], callback?: AsyncResultCallback<T, E>): void;
export function compose(...fns: Function[]): Function;
export function seq(...fns: Function[]): Function;
export function applyEach(fns: Function[], ...argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
export function applyEachSeries(fns: Function[], ...argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
export function queue<T, E>(worker: AsyncWorker<T, E>, concurrency?: number): AsyncQueue<T>;
export function queue<T, R, E>(worker: AsyncResultIterator<T, R, E>, concurrency?: number): AsyncQueue<T>;
export function priorityQueue<T, E>(worker: AsyncWorker<T, E>, concurrency: number): AsyncPriorityQueue<T>;
export function cargo<E>(worker : (tasks: any[], callback : ErrorCallback<E>) => void, payload? : number) : AsyncCargo;
export function auto<R extends Dictionary<any>, E>(tasks: AsyncAutoTasks<R, E>, concurrency?: number, callback?: AsyncResultCallback<R, E>): void;
export function autoInject<E>(tasks: any, callback?: AsyncResultCallback<any, E>): void;
export function retry<T, E>(opts: number, task: (callback : AsyncResultCallback<T, E>, results: any) => void, callback: AsyncResultCallback<any, E | Error>): void;
export function retry<T, E>(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback<T, E>, results : any) => void, callback: AsyncResultCallback<any, E | Error>): void;
export function retryable<T, E>(opts: number | {times: number, interval: number}, task: AsyncFunction<T, E>): AsyncFunction<T, E | Error>;
export function apply<E>(fn: Function, ...args: any[]): AsyncFunction<any,E | Error>;
export function queue<T, E = Error>(worker: AsyncWorker<T, E>, concurrency?: number): AsyncQueue<T>;
export function queue<T, R, E = Error>(worker: AsyncResultIterator<T, R, E>, concurrency?: number): AsyncQueue<T>;
export function priorityQueue<T, E = Error>(worker: AsyncWorker<T, E>, concurrency: number): AsyncPriorityQueue<T>;
export function cargo<E = Error>(worker : (tasks: any[], callback : ErrorCallback<E>) => void, payload? : number) : AsyncCargo;
export function auto<R extends Dictionary<any>, E = Error>(tasks: AsyncAutoTasks<R, E>, concurrency?: number, callback?: AsyncResultCallback<R, E>): void;
export function auto<R extends Dictionary<any>, E = Error>(tasks: AsyncAutoTasks<R, E>, callback?: AsyncResultCallback<R, E>): void;
export function autoInject<E = Error>(tasks: any, callback?: AsyncResultCallback<any, E>): void;
export function retry<T, E = Error>(opts: number, task: (callback : AsyncResultCallback<T, E>, results: any) => void, callback: AsyncResultCallback<any, E>): void;
export function retry<T, E = Error>(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback<T, E>, results : any) => void, callback: AsyncResultCallback<any, E>): void;
export function retryable<T, E = Error>(opts: number | {times: number, interval: number}, task: AsyncFunction<T, E>): AsyncFunction<T, E>;
export function apply<E = Error>(fn: Function, ...args: any[]): AsyncFunction<any,E>;
export function nextTick(callback: Function, ...args: any[]): void;
export const setImmediate: typeof nextTick;
export function reflect<T, E>(fn: AsyncFunction<T, E>) : (callback: (err: null, result: {error?: E, value?: T}) => void) => void;
export function reflectAll<T, E>(tasks: AsyncFunction<T, E>[]): ((callback: (err: null, result: {error?: E, value?: T}) => void) => void)[];
export function reflect<T, E = Error>(fn: AsyncFunction<T, E>) : (callback: (err: null, result: {error?: E, value?: T}) => void) => void;
export function reflectAll<T, E = Error>(tasks: AsyncFunction<T, E>[]): ((callback: (err: null, result: {error?: E, value?: T}) => void) => void)[];
export function timeout<T, E>(fn: AsyncFunction<T, E>, milliseconds: number, info?: any): AsyncFunction<T, E | Error>;
export function timeout<T, R, E>(fn: AsyncResultIterator<T, R, E>, milliseconds: number, info?: any): AsyncResultIterator<T, R, E | Error>;
export function timeout<T, E = Error>(fn: AsyncFunction<T, E>, milliseconds: number, info?: any): AsyncFunction<T, E>;
export function timeout<T, R, E = Error>(fn: AsyncResultIterator<T, R, E>, milliseconds: number, info?: any): AsyncResultIterator<T, R, E>;
export function times<T, E> (n: number, iterator: AsyncResultIterator<number, T, E>, callback: AsyncResultArrayCallback<T, E>): void;
export function timesSeries<T, E>(n: number, iterator: AsyncResultIterator<number, T, E>, callback: AsyncResultArrayCallback<T, E>): void;
export function timesLimit<T, E>(n: number, limit: number, iterator: AsyncResultIterator<number, T, E>, callback: AsyncResultArrayCallback<T, E>): void;
export function timesSeries<T, E = Error>(n: number, iterator: AsyncResultIterator<number, T, E>, callback: AsyncResultArrayCallback<T, E>): void;
export function timesLimit<T, E = Error>(n: number, limit: number, iterator: AsyncResultIterator<number, T, E>, callback: AsyncResultArrayCallback<T, E>): void;
export function transform<T, R, E>(arr: T[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback<T, E>): void;
export function transform<T, R, E>(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback<T, E>): void;
export function transform<T, R, E = Error>(arr: T[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback<T, E>): void;
export function transform<T, R, E = Error>(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback<T, E>): void;
export function transform<T, R, E>(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback<T, E>): void;
export function transform<T, R, E>(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback<T, E>): void;
export function transform<T, R, E = Error>(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback<T, E>): void;
export function transform<T, R, E = Error>(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback<T, E>): void;
export function race<T, E>(tasks: (AsyncFunction<T, E>)[], callback: AsyncResultCallback<T, E | Error>) : void;
export function race<T, E = Error>(tasks: (AsyncFunction<T, E>)[], callback: AsyncResultCallback<T, E>) : void;
// Utils
export function memoize(fn: Function, hasher?: Function): Function;

View File

@@ -114,7 +114,7 @@ async.series([
],
function (err, results) { });
async.series<string,Error>([
async.series<string>([
function (callback) {
callback(undefined, 'one');
},
@@ -138,7 +138,7 @@ async.series({
},
function (err, results) { });
async.series<number,Error>({
async.series<number>({
one: function (callback) {
setTimeout(function () {
callback(undefined, 1);
@@ -178,7 +178,7 @@ async.parallel([
],
function (err, results) { });
async.parallel<string,Error>([
async.parallel<string>([
function (callback) {
setTimeout(function () {
callback(undefined, 'one');
@@ -207,7 +207,7 @@ async.parallel({
},
function (err, results) { });
async.parallel<number,Error>({
async.parallel<number>({
one: function (callback) {
setTimeout(function () {
callback(undefined, 1);
@@ -273,7 +273,7 @@ async.waterfall([
], function (err, result) { });
var q = async.queue<any,Error>(function (task: any, callback: (err?:Error,msg?:string) => void) {
var q = async.queue<any>(function (task: any, callback: (err?:Error,msg?:string) => void) {
console.log('hello ' + task.name);
callback(undefined,'a message.');
}, 2);
@@ -293,7 +293,7 @@ q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) {
console.log('finished processing bar');
});
q.push<string,Error>({name: 'foo'}, function (err,msg) {
q.push<string>({name: 'foo'}, function (err, msg) {
console.log('foo finished with a message "'+ msg! + '"');
});
@@ -330,7 +330,7 @@ q.resume();
q.kill();
// tests for strongly typed tasks
var q2 = async.queue<string,Error>(function (task: string, callback: () => void) {
var q2 = async.queue<string>(function (task: string, callback: () => void) {
console.log('Task: ' + task);
callback();
}, 1);
@@ -356,7 +356,7 @@ q2.unshift(['task3', 'task4', 'task5'], function (error) {
});
var aq = async.queue<number, number, Error>(function (level: number, callback: (error?: Error, newLevel?: number) => void) {
var aq = async.queue<number, number>(function (level: number, callback: (error?: Error, newLevel?: number) => void) {
console.log('hello ' + level);
callback(undefined, level+1);
});
@@ -387,14 +387,47 @@ cargo.push({ name: 'baz' }, function (err: Error) {
var filename = '';
async.auto({
get_data: function (callback: any) { },
make_folder: function (callback: any) { },
get_data: function (callback: AsyncResultCallback<any>) { },
make_folder: function (callback: AsyncResultCallback<any>) { },
//arrays with different types are not accepted by TypeScript.
write_file: ['get_data', 'make_folder', <any>function (callback: any) {
write_file: ['get_data', 'make_folder', <any>function (callback: AsyncResultCallback<any>) {
callback(null, filename);
}],
//arrays with different types are not accepted by TypeScript.
email_link: ['write_file', <any>function (callback: any, results: any) { }]
email_link: ['write_file', <any>function (callback: AsyncResultCallback<any>, results: any) { }]
});
async.auto({
get_data: function (callback: AsyncResultCallback<any>) { },
make_folder: function (callback: AsyncResultCallback<any>) { },
//arrays with different types are not accepted by TypeScript.
write_file: ['get_data', 'make_folder', <any>function (callback: AsyncResultCallback<any>) {
callback(null, filename);
}],
//arrays with different types are not accepted by TypeScript.
email_link: ['write_file', <any>function (callback: AsyncResultCallback<any>, results: any) { }]
}, function (err, results) {
console.log('finished auto');
});
interface A {
get_data: any;
make_folder: any;
write_file: any;
email_link: any;
}
async.auto<A>({
get_data: function (callback: AsyncResultCallback<any>) { },
make_folder: function (callback: AsyncResultCallback<any>) { },
//arrays with different types are not accepted by TypeScript.
write_file: ['get_data', 'make_folder', <any>function (callback: AsyncResultCallback<any>) {
callback(null, filename);
}],
//arrays with different types are not accepted by TypeScript.
email_link: ['write_file', <any>function (callback: AsyncResultCallback<any>, results: any) { }]
}, 1, function (err, results) {
console.log('finished auto');
});
async.retry(3, function (callback, results) { }, function (err, result) { });
@@ -459,10 +492,10 @@ async.dir(function (name: string, callback: any) {
// each
async.each<number,Error>({
async.each<number>({
"a": 1,
"b": 2
}, function(val: number, next: ErrorCallback<Error>): void {
}, function(val: number, next: ErrorCallback): void {
setTimeout(function(): void {
@@ -478,10 +511,10 @@ async.each<number,Error>({
});
async.eachSeries<number, Error>({
async.eachSeries<number>({
"a": 1,
"b": 2
}, function(val: number, next: ErrorCallback<Error>): void {
}, function(val: number, next: ErrorCallback): void {
setTimeout(function(): void {
@@ -497,14 +530,14 @@ async.eachSeries<number, Error>({
});
async.eachLimit<number, Error>({
async.eachLimit<number>({
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6
}, 2, function(val: number, next: ErrorCallback<Error>): void {
}, 2, function(val: number, next: ErrorCallback): void {
setTimeout(function(): void {
@@ -522,10 +555,10 @@ async.eachLimit<number, Error>({
// forEachOf/eachOf
async.eachOf<number, Error>({
async.eachOf<number>({
"a": 1,
"b": 2
}, function(val: number, key: string, next: ErrorCallback<Error>): void {
}, function(val: number, key: string, next: ErrorCallback): void {
setTimeout(function(): void {
@@ -541,10 +574,10 @@ async.eachOf<number, Error>({
});
async.forEachOfSeries<number, Error>({
async.forEachOfSeries<number>({
"a": 1,
"b": 2
}, function(val: number, key: string, next: ErrorCallback<Error>): void {
}, function(val: number, key: string, next: ErrorCallback): void {
setTimeout(function(): void {
@@ -560,14 +593,14 @@ async.forEachOfSeries<number, Error>({
});
async.forEachOfLimit<number, Error>({
async.forEachOfLimit<number>({
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6
}, 2, function(val: number, key: string, next: ErrorCallback<Error>): void {
}, 2, function(val: number, key: string, next: ErrorCallback): void {
setTimeout(function(): void {
@@ -585,11 +618,11 @@ async.forEachOfLimit<number, Error>({
// map
async.map<number, string, Error>({
async.map<number, string>({
"a": 1,
"b": 2,
"c": 3
}, function(val: number, next: AsyncResultCallback<string, Error>): void {
}, function(val: number, next: AsyncResultCallback<string>): void {
setTimeout(function(): void {
@@ -605,11 +638,11 @@ async.map<number, string, Error>({
});
async.mapSeries<number, string, Error>({
async.mapSeries<number, string>({
"a": 1,
"b": 2,
"c": 3
}, function(val: number, next: AsyncResultCallback<string, Error>): void {
}, function(val: number, next: AsyncResultCallback<string>): void {
setTimeout(function(): void {
@@ -625,14 +658,14 @@ async.mapSeries<number, string, Error>({
});
async.mapLimit<number, string, Error>({
async.mapLimit<number, string>({
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6
}, 2, function(val: number, next: AsyncResultCallback<string, Error>): void {
}, 2, function(val: number, next: AsyncResultCallback<string>): void {
setTimeout(function(): void {
@@ -650,11 +683,11 @@ async.mapLimit<number, string, Error>({
// mapValues
async.mapValues<number, string, Error>({
async.mapValues<number, string>({
"a": 1,
"b": 2,
"c": 3
}, function(val: number, key: string, next: AsyncResultCallback<string, Error>): void {
}, function(val: number, key: string, next: AsyncResultCallback<string>): void {
setTimeout(function(): void {
@@ -670,11 +703,11 @@ async.mapValues<number, string, Error>({
});
async.mapValuesSeries<number, string, Error>({
async.mapValuesSeries<number, string>({
"a": 1,
"b": 2,
"c": 3
}, function(val: number, key: string, next: AsyncResultCallback<string, Error>): void {
}, function(val: number, key: string, next: AsyncResultCallback<string>): void {
setTimeout(function(): void {
@@ -692,11 +725,11 @@ async.mapValuesSeries<number, string, Error>({
// filter/select/reject
async.filter<number, Error>({
async.filter<number>({
"a": 1,
"b": 2,
"c": 3
}, function(val: number, next: AsyncBooleanResultCallback<Error>): void {
}, function(val: number, next: AsyncBooleanResultCallback): void {
setTimeout(function(): void {
@@ -712,11 +745,11 @@ async.filter<number, Error>({
});
async.reject<number, Error>({
async.reject<number>({
"a": 1,
"b": 2,
"c": 3
}, function(val: number, next: AsyncBooleanResultCallback<Error>): void {
}, function(val: number, next: AsyncBooleanResultCallback): void {
setTimeout(function(): void {
@@ -734,11 +767,11 @@ async.reject<number, Error>({
// concat
async.concat<string, string, Error>({
async.concat<string, string>({
"a": "1",
"b": "2",
"c": "3"
}, function(item: string, next: AsyncResultCallback<string[], Error>): void {
}, function(item: string, next: AsyncResultCallback<string[]>): void {
console.log(`async.concat: ${item}`);
@@ -752,11 +785,11 @@ async.concat<string, string, Error>({
// detect/find
async.detect<number, Error>({
async.detect<number>({
"a": 1,
"b": 2,
"c": 3
}, function(item: number, next: AsyncBooleanResultCallback<Error>): void {
}, function(item: number, next: AsyncBooleanResultCallback): void {
console.log(`async.detect/find: ${item}`);
@@ -777,11 +810,11 @@ async.detect<number, Error>({
// every/all
async.every<number,Error>({
async.every<number>({
"a": 1,
"b": 2,
"c": 3
}, function(item: number, next: AsyncBooleanResultCallback<Error>): void {
}, function(item: number, next: AsyncBooleanResultCallback): void {
console.log(`async.every/all: ${item}`);
@@ -795,11 +828,11 @@ async.every<number,Error>({
// some/any
async.some<number, Error>({
async.some<number>({
"a": 1,
"b": 2,
"c": 3
}, function(item: number, next: AsyncBooleanResultCallback<Error>): void {
}, function(item: number, next: AsyncBooleanResultCallback): void {
console.log(`async.some/any: ${item}`);

View File

@@ -1 +1,6 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json",
"rules": {
"no-angle-bracket-type-assertion": false
}
}

784
types/athenajs/index.d.ts vendored Normal file
View File

@@ -0,0 +1,784 @@
// Type definitions for athenajs 0.1
// Project: https://github.com/AthenaJS/athenajs
// Definitions by: Nicolas Ramz <https://github.com/warpdesign>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace AthenaJS;
export function Dom(sel?: string | HTMLElement): _Dom<HTMLElement>;
export class Scene {
constructor(options?: SceneOptions);
map: Map;
hudScene: Scene | null;
running: boolean;
opacity: number;
addObject(object: Drawable | Drawable[], layer?: number): Scene;
animate(fxName: string, options: EffectOptions): Promise;
bindEvents(eventList: string): void;
debug(bool?: boolean): void;
fadeIn(duration: number): Promise;
fadeOut(duration: number): Promise;
fadeInAndOut(inDuration: number, delay: number, outDuration: number): Promise;
getOpacity(): number;
getPlayTime(): number;
load(type: string, src: string, id?: string): void;
loadAudio(src: string, id?: string): void;
loadImage(src: string, id?: string): void;
loadMap(src: string, id?: string): void;
notify(name: string, data?: JSObject): void;
removeObject(obj: Drawable): void;
setBackgroundImage(image: string|HTMLImageElement): void;
setLayerPriority(layer: number, background: boolean): void;
setMap(map: Map | JSObject, x?: number, y?: number): void;
setOpacity(opacity: number): void;
setup(): void;
start(): void;
stop(): void;
}
export class Game {
constructor(options: GameOptions);
bindEvents(eventList: string): void;
setScene(scene: Scene): void;
toggleFullscreen(): void;
toggleSound(bool: boolean): void;
toggleTileInspector(bool: boolean): void;
togglePause(): void;
scene: Scene;
sound: boolean;
}
export class Drawable {
constructor(type: string, options: DrawableOptions);
addChild(child: Drawable): void;
animate(name: string, options: JSObject): Promise;
center(): Drawable;
destroy(data?: any): void;
moveTo(x: number, y: number, duration?: number): Drawable;
notify(id: string, data?: JSObject): void;
onCollision(object: Drawable): void;
onEvent(eventType: string, data?: JSObject): void;
playSound(id: string, options?: { pan?: boolean, loop?: false }): void;
setBehavior(behavior: string | { new(sprite: Drawable, options?: JSObject): Behavior }, options?: JSObject): void;
setScale(scale: number): void;
getCurrentWidth(): number;
getCurrentHeight(): number;
getProperty(prop: string): any;
setProperty(prop: string, value: any): void;
setMask(mask: MaskOptions | null, exclude?: boolean): void;
stopAnimate(endValue?: number): void;
reset(): void;
show(): void;
hide(): void;
type: string;
width: number;
height: number;
x: number;
y: number;
vx: number;
vy: number;
canCollide: boolean;
currentMovement: string;
running: boolean;
movable: boolean;
behavior: Behavior;
currentMap: Map;
data: JSObject;
visible: boolean;
}
export interface MaskOptions {
x: number;
y: number;
width: number;
height: number;
}
export interface MenuItem {
text: string;
selectable: boolean;
visible: boolean;
active?: boolean;
}
export interface MenuOptions {
title: string;
color: string;
menuItems: MenuItem[];
}
export class Menu extends Drawable {
constructor(id: string, options: MenuOptions);
nextItem(): void;
getSelectedItemIndex(): number;
}
export class SimpleText extends Drawable {
constructor(type: string, simpleTextOptions: SimpleTextOptions);
getCurrentOffsetX(): number;
getCurrentOffsetY(): number;
setColor(color: string): void;
setSize(width: number, height: number): void;
setText(text: string): void;
}
export class Paint extends Drawable {
constructor(type: string, paintOptions: PaintOptions);
arc(cx: number, cy: number, r: number, starteAngle: number, endAngle: number, fillStyle: string, borderSize: number): void;
fill(color?: string): void;
circle(cx: number, cy: number, r: number, fillStyle?: string, borderWidth?: number, borderStyle?: string): void;
rect(x: number, y: number, width: number, height: number, color: string): void;
name: string;
color: string;
}
export class BitmapText extends Drawable {
constructor(type: string, textOptions: BitmapTextOptions);
setText(text: string): void;
}
export class Sprite extends Drawable {
constructor(type: string, spriteOptions: SpriteOptions);
addAnimation(name: string, imgPath: string, options: AnimOptions): void;
setAnimation(name: string, fn?: Callback, frameNum?: number, revert?: boolean): void;
clearMove(): void;
}
export interface pixelPos {
x: number;
y: number;
}
export class Map {
constructor(options: MapOptions);
addObject(obj: Drawable, layerIndex?: number): void;
addTileSet(tiles: TileDesc[]): void;
checkMatrixForCollision(buffer: number[], matrixWidth: number, x: number, y: number, behavior: number): boolean;
clear(tileNum?: number, behavior?: number): void;
getTileBehaviorAtIndex(col: number, row: number): number;
getTileIndexFromPixel(x: number, y: number): pixelPos;
moveTo(x: number, y: number): void;
respawn(): void;
setData(map: Uint8Array, behaviors: Uint8Array): void;
setEasing(easing: string): void;
shift(startLine: number, height: number): void;
updateTile(col: number, row: number, tileNum?: number, behavior?: number): void;
duration: number;
numRows: number;
numCols: number;
width: number;
height: number;
tileWidth: number;
tileHeight: number;
}
export class Tile {
constructor(options: JSObject);
static TYPE: {
AIR: 1;
WALL: 2;
LADDER: 3;
};
offsetX: number;
offsetY: number;
width: number;
height: number;
inertia: number;
upCollide: boolean;
downCollide: boolean;
}
export interface TileDesc {
offsetX: number;
offsetY: number;
width: number;
height: number;
}
export interface MapOptions {
src: string;
tileWidth: number;
tileHeight: number;
width: number;
height: number;
viewportW?: number;
viewportH?: number;
buffer?: ArrayBuffer;
}
export interface FXInstance {
addFX(fxName: string, FxClass: { new(options: EffectOptions, display: Display): Effect }): void;
}
export const FX: FXInstance;
export class _FX {
/**
* Creates the FX class, adding the linear easing
*/
constructor();
/**
* Add a new Effect
*/
addFX(fxName: string, FxClass: { new(): Effect }): void;
/**
* Retrieve an effect Class by its name
*
*/
getEffect(fxName: string): Effect;
/**
* Add a new easing function for other objects to use
*
*/
addEasing(easingName: string, easingFn: (x?: number, t?: number, b?: number, c?: number, d?: number) => void): void;
/**
* Retrieves an easing function
*
*/
getEasing(easingName: string): (x?: number, t?: number, b?: number, c?: number, d?: number) => void;
}
export interface EffectOptions {
easing?: string;
when?: string;
startValue?: number;
endValue?: number;
duration?: number;
}
export class Effect {
width: number;
height: number;
buffer: RenderingContext;
animProgress: number;
startValue: number;
ended: boolean;
/**
* This the class constructor. Default options are:
*
*/
constructor(options: EffectOptions, display: Display);
/**
* Changes the easing function used for the ffect
*
*/
setEasing(easing: (x?: number, t?: number, b?: number, c?: number, d?: number) => void): void;
/**
* Called when the ffect is started.
*
* This method can be overriden but the super should always be called
*/
start(): Promise;
/**
* called when the effect is stopped
*/
stop(object: any, setEndValue: any): void;
/**
* Calculates current animation process
*
* This method can be overridden but the super should always be calle first
*/
process(ctx: RenderingContext, fxCtx?: RenderingContext, obj?: any): boolean;
}
// why do we need this ?
export type RenderingContext = CanvasRenderingContext2D;
export interface DisplayOptions {
width: number;
height: number;
type: string;
layers?: boolean[];
name: string;
}
export class Display {
/**
* Creates a new Display instance
*
*/
constructor(options: DisplayOptions, target: string | HTMLElement);
/**
* Creates a new (offscreen) drawing buffer
*
*/
getBuffer(width: number, height: number): RenderingContext;
/**
* Toggles fullscreen display scaling
*/
toggleFullscreen(): void;
/**
* Changes the zIndex property of the specified layer canvas
*
*/
setLayerZIndex(layer: number, zIndex: number): void;
/**
* Clears a canvas display buffer
*
*/
clearScreen(ctx: RenderingContext): void;
/**
* Clears every rendering buffer, including the special fxCtx one
*/
clearAllScreens(): void;
/**
* Changes the (CSS) opacity of a canvas
*
*/
setCanvasOpacity(canvas: HTMLElement, opacity: number): void;
/**
* Renders the specified scene
*
*/
renderScene(scene: Scene): void;
/**
* Prepares the canvas before rendering images.
*
* Explanation: during development, I noticed that the very first time
* the ctx.drawImage() was used to draw onto a canvas, it took a very long time,
* like at least 10ms for a very small 32x32 pixels drawImage.
*
* Subsequent calls do not have this problem and are instant.
* Maybe some ColorFormat conversion happens.
*
* This method makes sure that when the game starts rendering, we don't have
* any of these delays that can impact gameplay and alter the gameplay experience
* in a negative way.
*/
prepareCanvas(resources: JSObject[]): void;
/**
* Starts an animation on the display
*
*/
animate(fxName: string, options: EffectOptions, context: RenderingContext): Promise;
/**
* stops current animation
*
* TODO
*/
stopAnimate(fxName?: string): void;
/**
* Executes an effect on a frame at a given time
*
*/
executeFx(ctx: RenderingContext, fxCtx: RenderingContext, obj: Drawable, time: number, when: string): void;
/**
* Clears every display layer and clears fx queues
*/
clearDisplay(): void;
}
export const InputManager: _InputManager;
export class MapEvent {
/**
* Creates a new MapEvent
*
*/
constructor(map: Map);
/**
* Resets the MapEvent switches, events and items
*/
reset(): void;
/**
* Adds a new [`Drawable`]{#item} onto the map
*
*/
addItem(id: string, item: Drawable): void;
/**
* Returns an item
*
*/
getItem(id: string): Drawable | undefined;
// TODO: ability to trigger an event once a switch has been modified
setSwitch(id: string, bool: boolean): void;
toggleSwitch(id: string): void;
/**
* Retrieves a switch from the map using its id
*
*/
getSwitch(id: string): any;
/**
* checks of conditions of specified trigger are valid
*
*/
checkConditions(trigger: JSObject): boolean;
handleAction(options: JSObject): void;
handleEvent(options: JSObject): boolean;
/**
* Schedule adding a new object to the map
*/
scheduleSprite(spriteId: string, spriteOptions: JSObject, delay: number): Drawable;
/**
* Add a new wave of objects to the map
* Used for example when the player triggers apparition of several enemies or bonuses
*
* @related {Wave}
*/
handleWave(options: JSObject): boolean;
endWave(): void;
triggerEvent(id: string): void;
isEventTriggered(id: string): boolean;
}
export class Behavior {
vx: number;
vy: number;
gravity: number;
sprite: Drawable;
constructor(sprite: Drawable, options?: JSObject);
onUpdate(timestamp: number): void;
onVXChange?(vx: number): void;
onVYChange?(vy: number): void;
/**
* Returns current mapEvent
*
*/
getMapEvent(): MapEvent;
reset(): void;
}
export interface _AudioManager {
audioCache: JSObject;
enabled: boolean;
/**
* Adds a new sound element to the audio cache.
* *Note* if a sound with the same id has already been added, it will be replaced
* by the new one.
*
*/
addSound(id: string, element: HTMLAudioElement): void;
/**
* Toggles global sound playback
*
*/
toggleSound(bool: boolean): void;
/**
* Plays the specified sound with `id`.
*
*/
play(id: string, loop?: boolean, volume?: number, panning?: number): any;
/**
* Stops playing the sound id
*
*/
stop(id: string, instanceId: any): void;
}
export const AudioManager: _AudioManager;
export interface Res {
id: string;
type: string;
src: string;
}
export type Callback = (...args: any[]) => void;
export interface _NotificationManager {
notify(name: string, data?: JSObject): void;
}
export const NotificationManager: _NotificationManager;
export interface _ResourceManager {
addResources(resource: Res, group?: string): Promise;
getCanvasFromImage(image: HTMLImageElement): HTMLCanvasElement;
getResourceById(id: string, group?: string, fullObject?: boolean): any;
loadResources(group: string, progressCb?: Callback, errorCb?: Callback): void;
loadImage(res: Res, group?: string): Promise;
loadAudio(res: Res, group?: string): Promise;
newResourceFromPool(id: string): any;
registerScript(id: string, elt: any, poolSize?: number): void;
}
export const ResourceManager: _ResourceManager;
export interface _InputManager {
/**
* A list of common keyCodes
*/
KEYS: {
'UP': 38,
'DOWN': 40,
'LEFT': 37,
'RIGHT': 39,
'SPACE': 32,
'ENTER': 13,
'ESCAPE': 27,
'CTRL': 17
};
/**
* List of common pad buttons
*/
PAD_BUTTONS: {
32: 1, // Face (main) buttons
FACE_0: 1,
FACE_3: 2,
FACE_4: 3,
LEFT_SHOULDER: 4, // Top shoulder buttons
RIGHT_SHOULDER: 5,
LEFT_SHOULDER_BOTTOM: 6, // Bottom shoulder buttons
RIGHT_SHOULDER_BOTTOM: 7,
SELECT: 8,
START: 9,
LEFT_ANALOGUE_STICK: 10, // Analogue sticks (if depressible)
RIGHT_ANALOGUE_STICK: 11,
38: 12, // Directional (discrete) pad
40: 13,
37: 14,
39: 15
};
axes: JSObject;
newGamepadPollDelay: number;
gamepadSupport: boolean;
recording: boolean;
playingEvents: boolean;
playingPos: number;
/*recordedEvents: Array,*/
pad: null;
latches: JSObject;
keyPressed: JSObject;
padPressed: JSObject;
keyCb: JSObject;
enabled: boolean;
inputMode: string;
// virtual joystick instance
dPadJoystick: null;
jPollInterval: number;
/**
* Initializes the InputManager with a reference to the game.
*
* This method prepares the InputManager by reseting keyboard states/handlers and
* set current inputMode
*
*/
init(): void;
/**
* Starts recording input events. They are stored into `InputManager.recordedEvents`
*/
startRecordingEvents(): void;
/**
* Stops recording events.
*/
stopRecordingEvents(): void;
/**
* After events have been reccorded they can be played back using this method.
*/
playRecordedEvents(): void;
/**
* Sets next key states using recorded events
*
* TODO: add an optional callback to be called at the end of the playback
* so that demo can be looped.
*/
nextRecordedEvents(): void;
/**
* Saves current event state onto the recordedEvents stack
*/
/**
* Changes input mode
*
*/
setInputMode(mode: string): void;
/**
* Returns an object with the state of all keys
*/
getAllKeysStatus(): JSObject;
getKeyStatus(key: string, latch: boolean): boolean;
isKeyDown(key: string|number, latch?: boolean): boolean;
/**
* Install callback that gets called when a key is pressed/released
*
*/
installKeyCallback(key: string, event: string, callback: (key: string, event: string) => void): void;
removeKeyCallback(key: string, event: string, callback: () => void): void;
clearEvents(): void;
}
export interface Promise {
then(val?: () => any): Promise;
catch(val?: () => any): Promise;
}
/* Deferred */
export class Deferred {
constructor();
/**
* Creates and immediately resolves a new deferred.
*
*/
static resolve(val?: any): Promise;
promise: Promise;
reject(val: any): void;
resolve(val: any): void;
}
/* Dom support */
export interface _Dom<TElement> extends Iterable<TElement> {
[key: number]: TElement;
length: number;
css(prop: string, val: string): _Dom<TElement>;
css(prop: JSObject): _Dom<TElement>;
css(prop: string): string|null;
find(selector: string): _Dom<TElement>;
appendTo(selector: string | _Dom<TElement> | HTMLElement): _Dom<TElement>;
attr(att: string, val: string): _Dom<TElement>;
attr(att: JSObject): _Dom<TElement>;
addClass(classes: string): _Dom<TElement>;
removeClass(classes: string): _Dom<TElement>;
html(str: string): _Dom<TElement>;
show(): _Dom<TElement>;
hide(): _Dom<TElement>;
}
/* Game Support */
export interface GameOptions {
name: string;
showFps: boolean;
width: number;
height: number;
debug: boolean;
scene?: Scene;
target?: string | HTMLElement;
sound?: boolean;
}
export interface SceneOptions {
name?: string;
resources?: Res[];
opacity?: number;
layers?: number;
hudScene?: Scene;
}
export interface DrawableOptions {
x?: number;
y?: number;
behavior?: { new(sprite: Drawable, options?: JSObject): Behavior };
canCollide?: boolean;
canCollideFriendBullet?: boolean;
collideGroup?: number;
objectId?: string;
layer?: number;
map?: Map;
visible?: boolean;
pool?: number;
}
export interface SimpleTextOptions extends DrawableOptions {
text?: string;
width?: number;
height?: number;
fontFace?: string;
fontSize?: string;
fontStyle?: string;
fontWeight?: string;
align?: string;
color?: string;
}
export interface PaintOptions extends DrawableOptions {
width?: number;
height?: number;
color?: string;
lineHeight?: number;
}
export interface BitmapTextOptions extends DrawableOptions {
width?: number;
height?: number;
offsetX: number;
startY: number;
charWidth: number;
charHeight: number;
imageId?: string;
imageSrc?: string;
scrollOffsetX?: number;
scrollOffsetY?: number;
text?: string;
size?: string;
}
export interface SpriteOptions extends DrawableOptions {
easing?: string;
imageId?: string;
animations?: Animations;
data?: JSObject;
}
export interface AnimOptions {
numFrames: number;
frameWidth: number;
frameHeight: number;
frameDuration: number;
offsetX?: number;
offsetY?: number;
frameSpacing?: number;
}
export interface AnimationObject {
frameDuration?: number;
frames: Array<{
offsetX: number;
offsetY: number;
width: number;
height: number;
hitBox?: {
x: number;
y: number;
x2: number;
y2: number;
},
plane?: number;
}>;
loop?: number;
speed?: number;
}
export interface JSObject {
[key: string]: any;
}
export interface Animations {
[key: string]: AnimationObject;
}
export interface GameEvent {
type: string;
data: JSObject;
}

View File

@@ -0,0 +1,18 @@
import { BitmapText } from 'athenajs';
const bitmap: BitmapText = new BitmapText('myBitmap', {
size: 'big',
width: 180,
height: 32,
visible: false,
scrollOffsetX: 0,
scrollOffsetY: 0,
text: 'pause',
offsetX: 34,
startY: 36,
charWidth: 18,
charHeight: 18,
imageId: 'font'
});
bitmap.center();

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