Merge pull request #1 from DefinitelyTyped/master

Merge upstream
This commit is contained in:
ficristo
2019-03-26 21:52:39 +01:00
committed by GitHub
18295 changed files with 1114695 additions and 182896 deletions

View File

@@ -5,5 +5,5 @@ indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
[{*.json,*.yml}]
[{*.json,*.yml,*.ts,*.tsx,*.md}]
indent_style = space

10525
.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

@@ -2,7 +2,9 @@ language: node_js
node_js:
- 8
sudo: false
notifications:
email: false
script:
- npm run test
- if [[ $TRAVIS_EVENT_TYPE == "cron" ]]; then npm run update-codeowners || travis_terminate 1; fi

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:

196
README.md
View File

@@ -1,12 +1,23 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
# DefinitelyTyped
> The repository for *high quality* TypeScript type definitions.
Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date.
*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) and [Korean!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md)*
*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md), and [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)!*
## Current status
This section tracks the health of the repository and publishing process.
It may be helpful for contributors experiencing any issues with their PRs and packages.
* All packages are [type-checking/linting](https://github.com/Microsoft/dtslint) cleanly: [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
* All packages are being [published to npm](https://github.com/Microsoft/types-publisher) in under an hour: [![Publish Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13)
* [typescript-bot](https://github.com/typescript-bot) has been active on DefinitelyTyped [![Activity Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14)
If anything here seems wrong, or any of the above are failing, please raise an issue in [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped).
[![Join the chat at https://gitter.im/DefinitelyTyped/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/DefinitelyTyped/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## What are declaration files?
@@ -46,7 +57,7 @@ You may need to add manual [references](http://www.typescriptlang.org/docs/handb
## How can I contribute?
DefinitelyTyped only works because of contributions by users like you!
Definitely Typed only works because of contributions by users like you!
### Test
@@ -78,7 +89,7 @@ then follow the instructions to [edit an existing package](#edit-an-existing-pac
### Make a pull request
Once you've tested your package, you can share it on DefinitelyTyped.
Once you've tested your package, you can share it on Definitely Typed.
First, [fork](https://guides.github.com/activities/forking/) this repository, install [node](https://nodejs.org/), and run `npm install`.
@@ -106,7 +117,7 @@ If it doesn't, you can do so yourself in the comment associated with the PR.
#### Create a new package
If you are the library author and your package is written in TypeScript, [bundle the autogenerated declaration files](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) in your package instead of publishing to DefinitelyTyped.
If you are the library author and your package is written in TypeScript, [bundle the autogenerated declaration files](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) in your package instead of publishing to Definitely Typed.
If you are adding typings for an NPM package, create a directory with the same name.
If the package you are adding typings for is not on NPM, make sure the name you choose for it does not conflict with the name of a package on NPM.
@@ -126,7 +137,7 @@ See all options at [dts-gen](https://github.com/Microsoft/dts-gen).
You may edit the `tsconfig.json` to add new files, to add `"target": "es6"` (needed for async functions), to add to `"lib"`, or to add the `"jsx"` compiler option.
DefinitelyTyped members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down.
Definitely Typed members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down.
For a good example package, see [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
@@ -154,23 +165,42 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D
#### Removing a package
When a package [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) its own types, types should be removed from DefinitelyTyped to avoid confusion.
When a package [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) its own types, types should be removed from Definitely Typed to avoid confusion.
You can remove it by running `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`.
- `typingsPackageName`: This is the name of the directory to delete.
- `asOfVersion`: A stub will be published to `@types/foo` with this version. Should be higher than any currently published version.
- `sourceRepoURL`: This should point to the repository that contains the typings.
- `libraryName`: Descriptive name of the library, e.g. "Angular 2" instead of "angular2". (If ommitted, will be identical to "typingsPackageName".)
- `libraryName`: Name of npm package that replaces the Definitely Typed types. Usually this is identical to "typingsPackageName", in which case you can omit it.
Any other packages in DefinitelyTyped that referenced the deleted package should be updated to reference the bundled types. To do this, add a `package.json` with `"dependencies": { "foo": "x.y.z" }`.
Any other packages in Definitely Typed that referenced the deleted package should be updated to reference the bundled types.
You can get this list by looking at the errors from `npm run test`.
To fix the errors, add a `package.json` with `"dependencies": { "foo": "x.y.z" }`.
For example:
If a package was never on DefinitelyTyped, it does not need to be added to `notNeededPackages.json`.
```json
{
"private": true,
"dependencies": {
"foo": "^2.6.0"
}
}
```
When you add a `package.json` to dependents of `foo`, you will also need to open a PR to add `foo` [to dependenciesWhitelist.txt in types-publisher](https://github.com/Microsoft/types-publisher/blob/master/dependenciesWhitelist.txt).
If a package was never on Definitely Typed, it does not need to be added to `notNeededPackages.json`.
#### Lint
To lint a package, just add a `tslint.json` to that package containing `{ "extends": "dtslint/dt.json" }`. All new packages must be linted.
If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example:
All new packages must be linted. To lint a package, add a `tslint.json` to that package containing
```js
{
"extends": "dtslint/dt.json"
}
```
This should be the only content in a finished project's `tslint.json` file. If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example:
```js
{
@@ -208,11 +238,11 @@ The `master` branch is automatically published to the `@types` scope on NPM than
#### I've submitted a pull request. How long until it is merged?
It depends, but most pull requests will be merged within a week. PRs that have been approved by an author listed in the definition's header are usually merged more quickly; PRs for new definitions will take more time as they require more review from maintainers. Each PR is reviewed by a TypeScript or DefinitelyTyped team member before being merged, so please be patient as human factors may cause delays. Check the [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) to see progress as maintainers work through the open PRs.
It depends, but most pull requests will be merged within a week. PRs that have been approved by an author listed in the definition's header are usually merged more quickly; PRs for new definitions will take more time as they require more review from maintainers. Each PR is reviewed by a TypeScript or Definitely Typed team member before being merged, so please be patient as human factors may cause delays. Check the [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) to see progress as maintainers work through the open PRs.
#### My PR is merged; when will the `@types` NPM package be updated?
NPM packages should update within a few hours. If it's been more than 24 hours, ping @RyanCavanaugh and @andy-ms on the PR to investigate.
NPM packages should update within a few minutes. If it's been more than an hour, mention the PR number on [the Definitely Typed Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped) and the current maintainer will get the correct team member to investigate.
#### I'm writing a definition that depends on another definition. Should I use `<reference types="" />` or an import?
@@ -238,32 +268,132 @@ Here are the [currently requested definitions](https://github.com/DefinitelyType
If types are part of a web standard, they should be contributed to [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) so that they can become part of the default `lib.dom.d.ts`.
#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports?
Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function.
Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error:
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged.
This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter.
It is more appropriate to import the module using the `import foo = require("foo");` syntax.
Nevertheless, if you want to use a default import like `import foo from "foo";` you have two options:
- you can use the [`--allowSyntheticDefaultImports` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) if your module runtime supports an interop scheme for non-ECMAScript modules, i.e. if default imports work in your environment (e.g. Webpack, SystemJS, esm).
- you can use the [`--esModuleInterop` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop) if you want TypeScript to take care of non-ECMAScript interop (since Typescript 2.7).
#### A package uses `export =`, but I prefer to use default imports. Can I change `export =` to `export default`?
If you are using TypeScript 2.7 or later, use `--esModuleInterop` in your project.
Otherwise, if default imports work in your environment (e.g. Webpack, SystemJS, esm), consider turning on the [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) compiler option.
Like in the previous question, refer to using either the [`--allowSyntheticDefaultImports`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs)
or [`--esModuleInterop`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop)
compiler options.
Do not change the type definition if it is accurate.
For an NPM package, `export =` is accurate if `node -p 'require("foo")'` is the export, and `export default` is accurate if `node -p 'require("foo").default'` is the export.
For an NPM package, `export =` is accurate if `node -p 'require("foo")'` works to import a module, and `export default` is accurate if `node -p 'require("foo").default'` works to import a module.
#### I want to use features from TypeScript 2.1 or above.
Then you will have to add a comment to the last line of your definition header (after `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
#### I want to use features from TypeScript 3.1 or above.
You can use the same `// TypeScript Version: 3.1` comment as above.
However, if your project needs to maintain types that are compatible with 3.1 and above *at the same time as* types that are compatible with 3.0 or below, you will need to use the `typesVersions` feature, which is available in TypeScript 3.1 and above.
You can find a detailed explanation of this feature in the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#version-selection-with-typesversions).
Here's a short explanation to get you started:
1. You'll have to add a `package.json` file to your package definition, with the following contents:
```json
{
"private": true,
"types": "index",
"typesVersions": {
">=3.1.0-0": { "*": ["ts3.1/*"] }
}
}
```
2. Create the sub-directory mentioned in the `typesVersions` field inside your types directory (`ts3.1/` in this example)
and add the types and tests specific for the new TypeScript version. You don't need the typical definition header
in any of the files from the `ts3.1/` directory.
3. Set the `baseUrl` and `typeRoots` options in `ts3.1/tsconfig.json` to the correct paths, they should look something like this:
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"]
}
}
```
You can look [here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/debounce-promise) and [here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/create-html-element) for examples.
#### I want to add a DOM API not present in TypeScript by default.
This may belong in [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). See the guidelines there.
If the standard is still a draft, it belongs here.
Use a name beginning with `dom-` and include a link to the standard as the "Project" link in the header.
When it graduates draft mode, we may remove it from DefinitelyTyped and deprecate the associated `@types` package.
When it graduates draft mode, we may remove it from Definitely Typed and deprecate the associated `@types` package.
#### I want to update a package to a new major version
#### How do Definitely Typed package versions relate to versions of the corresponding library?
If you intend to continue updating the older version of the package, you may create a new subfolder with the current version e.g. `v2`, and copy existing files to it. If so, you will need to:
_NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_
Each Definitely Typed package is versioned when published to NPM.
The [types-publisher](https://github.com/Microsoft/types-publisher) (the tool that publishes `@types` packages to npm) will set the declaration package's version by using the `major.minor` version number listed in the first line of its `index.d.ts` file.
For example, here are the first few lines of [Node's type declarations](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1253faabf5e0d2c5470db6ea87795d7f96fef7e2/types/node/index.d.ts) for version `10.12.x` at the time of writing:
```js
// Type definitions for Node.js 10.12
// Project: http://nodejs.org/
// Definitions by: Microsoft TypeScript <https://github.com/Microsoft>
// Definitely Typed <https://github.com/DefinitelyTyped>
// Alberto Schiabel <https://github.com/jkomyno>
```
Because `10.12` is at the end the first line, the npm version of the `@types/node` package will also be `10.12.x`.
Note that the first-line comment in the `index.d.ts` file should only contain the `major.minor` version (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`).
This is because only the major and minor release numbers are aligned between library packages and type declaration packages.
The patch release number of the type declaration package (e.g. `.0` in `10.12.0`) is initialized to zero by Definitely Typed and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library.
Sometimes type declaration package versions and library package versions can get out of sync.
Below are a few common reasons why, in order of how much they inconvenience users of a library.
Only the last case is typically problematic.
* As noted above, the patch version of the type declaration package is unrelated to the library patch version.
This allows Definitely Typed to safely update type declarations for the same major/minor version of a library.
* If updating a package for new functionality, don't forget to update the version number to line up with that version of the library.
If users make sure versions correspond between JavaScript packages and their respective `@types` packages, then `npm update` should typically just work.
* It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update Definitely Typed when new library features are released.
So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release.
If you're impacted by this, you can be the change you want to see in the world and you can be that helpful community member!
:exclamation: If you're updating type declarations for a library, always set the `major.minor` version in the first line of `index.d.ts` to match the library version that you're documenting! :exclamation:
#### If a library is updated to a new major version with breaking changes, how should I update its type declaration package?
[Semantic versioning](https://semver.org/) requires that versions with breaking changes must increment the major version number.
For example, a library that removes a publicly exported function after its `3.5.8` release must bump its version to `4.0.0` in its next release.
Furthermore, when the library's `4.0.0` release is out, its Definitely Typed type declaration package should also be updated to `4.0.0`, including any breaking changes to the library's API.
Many libraries have a large installed base of developers (including maintainers of other packages using that library as a dependency) who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version.
In the meantime, users of old library versions still may want to update type declarations for older versions.
If you intend to continue updating the older version of a library's type declarations, you may create a new subfolder (e.g. `/v2/`) named for the current (soon to be "old") version, and copy existing files from the current version to it.
Because the root folder should always contain the type declarations for the latest ("new") version, you'll need to make a few changes to the files in your old-version subdirectory to ensure that relative path references point to the subdirectory, not the root.
1. Update the relative paths in `tsconfig.json` as well as `tslint.json`.
2. Add path mapping rules to ensure that tests are running against the intended version.
For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like:
For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`.
Because many users still consumed the older `2.x` version, a maintainer who wanted to update the type declarations for this library to `3.x` added a `v2` folder inside the history repository that contains type declarations for the older version.
At the time of writing, the [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1253faabf5e0d2c5470db6ea87795d7f96fef7e2/types/history/v2/tsconfig.json) looks roughly like:
```json
{
@@ -281,10 +411,11 @@ For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi
}
```
If there are other packages on DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this for packages depending on packages depending on the old version.
If there are other packages in Definitely Typed that are incompatible with the new version, you will need to add path mappings to the old version.
You will also need to do this recursively for packages depending on packages depending on the old version.
For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`;
transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/v2/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`.
Transitively, `react-router-bootstrap` (which depends on `react-router`) also needed to add the same path mapping (`"history": [ "history/v2" ]`) in its `tsconfig.json` until its `react-router` dependency was updated to the latest version.
Also, `/// <reference types=".." />` will not work with path mapping, so dependencies must use `import`.
@@ -316,19 +447,6 @@ When `dts-gen` is used to scaffold a scoped package, the `paths` property has to
GitHub doesn't [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) file history for renamed files. Use [`git log --follow`](https://www.git-scm.com/docs/git-log) instead.
#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports?
Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function.
Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error:
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged.
This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter.
It is more appropriate to import the module using the `import foo = require("foo");` syntax, or to use a default import like `import foo from "foo";` if using the `--allowSyntheticDefaultImports` flag if your module runtime supports an interop scheme for non-ECMAScript modules as such.
## License
This project is licensed under the MIT license.

353
README.ru.md Normal file
View File

@@ -0,0 +1,353 @@
<!-- markdownlint-disable MD001 MD012 MD026 -->
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
> Репозиторий для *высококачественных* определений типов TypeScript.
Также посетите веб-сайт [definitelytyped.org](http://definitelytyped.org), хотя информация в этом README более свежая.
*Вы также можете прочитать этот README на [английском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md), [испанском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) и [корейском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md).*
## Что такое файлы декларации (файлы описания/объявления типов)?
Смотрите [руководство по TypeScript](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
## Как их получить?
### npm
Это предпочтительный метод. Это доступно только для пользователей TypeScript 2.0+. Например:
```sh
npm install --save-dev @types/node
```
Затем типы должны автоматически включаться компилятором.
Подробнее смотрите в [справочнике](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html).
Для пакета NPM "foo", описания будут находиться в "@types/foo".
Если вы не можете найти свой пакет, ищите его в [TypeSearch](https://microsoft.github.io/TypeSearch/).
Если вы все еще не можете найти его, проверьте [включает](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) ли пакет собственную типизацию.
Обычно это отражается в поле `"types"` или `"typings"` файла `package.json`, или просто ищите любые файлы ".d.ts" в пакете и вручную включайте их в `/// <reference path="" />`.
### Другие методы
Эти методы могут быть использованы TypeScript 1.0.
* [Typings](https://github.com/typings/typings)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (используйте предпочтительные альтернативы, публикация типа nuget DT отключена)
* Вручную загрузите из ветки `master` этого репозитория
Возможно, вам придется добавить ручные [ссылки](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
## Как я могу внести свой вклад?
DefinitelyTyped работает только благодаря вкладу таких пользователей, как вы!
### Тестирование
Прежде чем поделиться своим улучшением с миром, используйте его сами.
#### Тестирование редактирования существующего пакета
Для добавления новых функций вы можете использовать [разрешение модулей](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation).
Вы также можете напрямую редактировать типы в `node_modules/@types/foo/index.d.ts`, или скопировать их оттуда и выполнить следующие шаги.
#### Тестирование ногово пакета
Добавьте к вашему `tsconfig.json`:
```json
"baseUrl": "types",
"typeRoots": ["types"],
```
(Вы также можете использовать `src/types`.)
Создайте `types/foo/index.d.ts` содержащие объявления для модуля "foo".
Теперь вы сможете импортировать из `"foo"` в свой код, и он будет направлен к новому определению типа.
Затем запустите сборку (build) *и* запустите код, чтобы убедиться, что ваше определение типа действительно соответствует тому, что происходит во время выполнения.
После того как вы проверили свои определения с реальным кодом, создайте [Запрос на принятие изменений (PR)](#make-a-pull-request)
и следуйте инструкциям [чтобы отредактировать существующий](#edit-an-existing-package) или
[создать новый пакет](#create-a-new-package).
### Запрос на принятие изменений (PR)
После того, как вы проверили ваш пакет, вы можете поделиться им с DefinitelyTyped.
Во-первых, [разветвите](https://guides.github.com/activities/forking/) этот репозиторий, установите [node](https://nodejs.org/), и запустите `npm install`.
#### Изменение существующего пакета
* `cd types/my-package-to-edit`
* Внесите изменения. Не забудьте отредактировать тесты.
Если вы вносите критические изменения, не забудьте [обновить основную версию](#i-want-to-update-a-package-to-a-new-major-version).
* Вы также можете добавить себя в раздел "Definitions by" заголовка пакета.
* Это приведет к тому, что вы будете уведомлены (через ваше имя пользователя GitHub) о том, что кто-то делает запрос на принятие изменений (PR) или проблему с пакетом.
* Сделайте это, добавив свое имя в конец строки, например `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
* Или, если есть больше людей, это может быть многострочным
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* Если есть `tslint.json`, запустите `npm run lint package-name`. В противном случае запустите `tsc` в директории пакета.
Когда вы создаете PR для редактирования существующего пакета, `dt-bot` должен @-уведомить
предыдущих авторов. Если этого не произойдет, вы можете сделать это самостоятельно в комментарии, связанном с PR.
#### Созданое нового пакета
Если вы являетесь автором библиотеки и ваш пакет написан на TypeScript, [свяжите автоматически сгенерированные файлы объявлений](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) в вашем пакете, а не публикуйте в DefinitelyTyped.
Если вы добавляете типизацию для пакета NPM, создайте директорию с тем же именем.
Если пакет, для которого вы добавляете типизацию, отсутствует в NPM, убедитесь, что выбранное вами имя не конфликтует с именем пакета в NPM.
(Вы можете использовать `npm info foo` чтобы проверить наличие пакета `foo`.)
Ваш пакет должен иметь такую ​​структуру:
| Файл | Назначение |
| ------------- | ---------------------------------------------------------------------------------------------------- |
| index.d.ts | Содержит типизацию для пакета. |
| foo-tests.ts | Содержит пример кода, который проверяет типизацию. Этот код *не* запускается, но он проверен на тип. |
| tsconfig.json | Позволяет вам запускать `tsc` внутри пакета. |
| tslint.json | Включает linting. |
Создайте их, запустив `npx dts-gen --dt --name my-package-name --template module` если у вас npm ≥ 5.2.0, `npm install -g dts-gen` и `dts-gen --dt --name my-package-name --template module` в противном случае.
Посмотреть все варианты на [dts-gen](https://github.com/Microsoft/dts-gen).
Вы можете отредактировать `tsconfig.json` чтобы добавить новые файлы, добавить `"target": "es6"` (необходимо для асинхронных функций), добавить в `"lib"`, или добавить опцию компилятора `"jsx"`.
Члены группы DefinitelyTyped регулярно следят за новыми PR, но имейте в виду, что количество других PR может замедлить ход событий.
Хороший пример пакета смотрите [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
#### Распространенные ошибки
* Сначала следуйте советам из справочника [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
* Форматирование: либо используйте все табы, либо всегда используйте 4 пробела.
* `function sum(nums: number[]): number`: используйте `ReadonlyArray` если функция не записывает свои параметры.
* `interface Foo { new(): Foo; }`:
Это определяет тип объектов, с методом `new`. Вы, вероятно, хотите объявить `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
Предпочитайте использовать объявление класса `class Class { constructor(); }` вместо `new`.
* `getMeAT<T>(): T`:
Если параметр типа не отображается в типах каких-либо параметров, у вас нет универсальной функции, а просто замаскированное утверждение типа.
Предпочитайте использовать утверждение реального типа, например, `getMeAT() as number`.
Пример, где допустим параметр типа: `function id<T>(value: T): T;`.
Пример, где это недопустимо: `function parseJson<T>(json: string): T;`.
Исключение: `new Map<string, number>()` все ОК.
* Использование типов `Function` and `Object` почти никогда не является хорошей идеей. В 99% случаев можно указать более конкретный тип. Примеры: `(x: number) => number` для [функций](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` для объектов. Если нет никакой уверенности в типе, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) является правильным выбором, а не `Object`. Если единственным известным фактом о типе является то, что это какой-то объект, используйте тип [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), а не `Object` или `{ [key: string]: any }`.
* `var foo: string | any`:
когда `any` используется в типе объединения, результирующий тип все еще `any`. Таким образом, хотя `string` часть аннотации этого типа может _выглядеть_ полезной, на самом деле она не предлагает никакой дополнительной проверки типов по сравнению с простым использованием `any`.
В зависимости от намерения, приемлемыми альтернативами могут быть `any`, `string`, или `string | object`.
#### Удаление пакета
Когда пакет [объединяет](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) свои собственные типы, типы должны быть удалены из DefinitelyTyped чтобы избежать путаницы.
Вы можете удалить его, запустив `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`.
* `typingsPackageName`: название директории, который нужно удалить.
* `asOfVersion`: заглушка будет опубликована в `@types/foo` с этой версией. Должна быть выше, чем любая опубликованная на данный момент версия
* `sourceRepoURL`: Это должно указывать на репозиторий, который содержит типизации.
* `libraryName`: описательное имя библиотеки, например, "Angular 2" вместо "angular2". (Если опущено, будет идентично "typingsPackageName".)
Любые другие пакеты в DefinitelyTyped которые ссылаются на удаленный пакет, должны быть обновлены для ссылки на связанные типы. Для этого добавьте в `package.json` ссыклу `"dependencies": { "foo": "x.y.z" }`.
Если пакет никогда не был в DefinitelyTyped, его не нужно добавлять в `notNeededPackages.json`.
#### Lint
Все новые пакеты должны быть проанализированы lint. Для этого добавьте `tslint.json` в этот пакет, содержащий
```js
{
"extends": "dtslint/dt.json"
}
```
Это должно быть единственным содержимым в файле `tslint.json` готового проекта. Если `tslint.json` отключает правила, это потому, что это еще не исправлено. Например:
```js
{
"extends": "dtslint/dt.json",
"rules": {
// This package uses the Function type, and it will take effort to fix.
"ban-types": false
}
}
```
(Чтобы указать, что правило lint действительно не применяется, используйте `// tslint:disable rule-name` или лучше, `//tslint:disable-next-line rule-name`.)
Чтобы проверить, что выражение имеет заданный тип, используйте `$ExpectType`. Чтобы проверить, что выражение вызывает ошибку компиляции, используйте `$ExpectError`.
```js
// $ExpectType void
f(1);
// $ExpectError
f("one");
```
Для получения дополнительной информации см. [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.
Протестируйте, запустив `npm run lint package-name` где `package-name` - это имя вашего пакета.
Этот скрипт использует [dtslint](https://github.com/Microsoft/dtslint).
## Часто задаваемые вопросы
#### Какая связь между этим репозиторием и пакетами `@types` в NPM?
Ветвь `master` автоматически публикуется в область `@types` на NPM благодаря [types-publisher](https://github.com/Microsoft/types-publisher).
#### Я отправил PR. Когда он сольется?
Это зависит, но большинство запросов на получение данных будут объединены в течение недели. PR, утвержденные автором, указанным в заголовке определения, обычно объединяются быстрее; PR для новых определений займет больше времени, так как они требуют большего количества проверок от сопровождающих. Каждый PR проверяется членом команды TypeScript или DefinitelyTyped перед объединением, поэтому будьте терпеливы, так как человеческий фактор может вызвать задержки. Посмотрите на [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) чтобы увидеть, как сопровождающие работают через открытые PR.
#### Мой PR слит; когда будет обновлен пакет `@types` NPM?
Пакеты NPM должны обновиться в течение нескольких часов. Если прошло более 24 часов, пингуйте @RyanCavanaugh и @andy-ms в PR, чтобы расследовать.
#### Я пишу определение, которое зависит от другого определения. Должен ли я использовать `<reference types="" />` или import?
Если модуль, на который вы ссылаетесь, является внешним модулем (использует `export`), используйте import.
Если модуль, на который вы ссылаетесь, является окружающим модулем (использует `declare module`, или просто объявляет глобальные переменные), используйте `<reference types="" />`.
#### Я заметил, что у некоторых пакетов есть `package.json`.
Обычно вам это не нужно. При публикации пакета мы обычно автоматически создаем `package.json`.
`package.json` может быть включен для определения зависимостей. Вот [пример](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
Мы не разрешаем определять другие поля, такие как "description", вручную.
Кроме того, если вам нужно сослаться на более старую версию типизаций, вы должны сделать это, добавив в `package.json` строки `"dependencies": { "@types/foo": "x.y.z" }`.
#### В некоторых пакетах отсутствует `tslint.json`, а в некоторых `tsconfig.json` отсутствует `"noImplicitAny": true`, `"noImplicitThis": true`, или `"strictNullChecks": true`.
Тогда они не правы. Вы можете помочь, отправив PR, чтобы исправить их.
#### Могу ли я запросить определение?
Вот [текущие запрошенные определения](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).
#### Как насчет определений типов для DOM?
Если типы являются частью веб-стандарта, они должны быть добавлены в [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) чтобы они могли стать частью `lib.dom.d.ts` по умолчанию.
#### Пакет использует export `export =`, но я предпочитаю использовать импорт по умолчанию. Могу ли я изменить `export =` на `export default`?
Если вы используете TypeScript 2.7 или более позднюю версию, используйте `--esModuleInterop` в вашем проекте.
В противном случае, если импорт по умолчанию работает в вашей среде (например, Webpack, SystemJS, esm), рассмотрите возможность включения опции компилятора [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html).
Не меняйте определение типа, если оно точное.
Для пакета NPM, `export =` является точным, если `node -p 'require("foo")'` является экспортом, а `export default` является точным, если `node -p 'require("foo").default'` является экспортом.
#### Я хочу использовать функции из TypeScript 2.1 или выше.
В таком случае вам нужно будет добавить комментарий к последней строке заголовка вашего определения (после `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
#### Я хочу добавить DOM API, отсутствующий в TypeScript по умолчанию.
Это может принадлежать [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). Смотрите инструкции там.
Если стандарт все еще является черновиком, добавляйте сюда.
Используйте имя, начинающееся с `dom-` и включите ссылку на стандарт в качестве ссылки "Project" в заголовке.
Когда он завершает черновой режим, мы можем удалить его из DefinitelyTyped и объявить устаревшим связанный пакет `@types`.
#### Я хочу обновить пакет новой старшей версии
Если вы намерены продолжить обновление старой версии пакета, вы можете создать новую подпапку с текущей версией, например, `v2` и скопируйте в него существующие файлы. Если это так, вам необходимо:
1. Обновите относительные пути в `tsconfig.json` а также в `tslint.json`.
2. Добавьте правила сопоставления путей, чтобы убедиться, что тесты выполняются для предполагаемой версии.
Например [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like:
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": [ "history/v2" ]
}
},
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
Если в DefinitelyTyped есть другие пакеты, несовместимые с новой версией, вам нужно будет добавить сопоставления путей к старой версии. Вам также нужно будет сделать это для пакетов в зависимости от пакетов в зависимости от старой версии.
Например, `react-router` зависит от `history@2`, поэтому [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) есть сопоставление пути с `"history": [ "history/v2" ]`;
транзитивно `react-router-bootstrap` (который зависит от `react-router`) также добавляет отображение пути в свой [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
Также, `/// <reference types=".." />` не будет работать с отображением пути, поэтому зависимости должны использовать `import`.
#### Как мне написать определения для пакетов, которые могут использоваться и глобально и в качестве модуля?
Руководство TypeScript содержит отличную [общую информацию о написании определений](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), а также [этот пример файла определения](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) , в котором показано, как создать определение с использованием синтаксиса модуля в стиле ES6, а также указаны объекты, доступные для глобальной области. Этот метод демонстрируется практически в определении для [definition for big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), библиотекой, которую можно загружать глобально с помощью тега скрипта на веб-странице или импортировать с помощью импорта по требованию или в стиле ES6.
Чтобы проверить, как ваше определение может использоваться как при глобальных ссылках, так и в качестве импортированного модуля, создайте тестовую папку `test`, и поместите туда два тестовых файла. Назовите один `YourLibraryName-global.test.ts` а другой `YourLibraryName-module.test.ts`. *Глобальный* тестовый файл должен использовать определение в соответствии с тем, как он будет использоваться в скрипте, загруженном на веб-страницу, где библиотека доступна в глобальной области видимости - в этом сценарии не следует указывать оператор импорта. Тестовый файл *модуля* должен использовать определение в соответствии с тем, как оно будет использоваться при импорте (включая оператор(ы) `import`). Если вы указали свойство `files` в файле `tsconfig.json`, обязательно включите оба тестовых файла. [Практический пример этого](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) также доступен в определении big.js.
Обратите внимание, что не требуется полностью использовать определение в каждом тестовом файле - достаточно протестировать только глобально доступные элементы в глобальном тестовом файле и полностью выполнить определение в тестовом файле модуля, или наоборот.
#### А как насчет областных пакетов?
Типы для пакета с областью `@foo/bar` должны указываться в `types/foo__bar`. Обратите внимание на двойное подчеркивание.
Когда `dts-gen` используется для компоновки пакета с областью действия, свойство `paths` должно быть вручную адаптировано в сгенерированном файле
`tsconfig.json` для правильной ссылки на пакет с областью действия:
```json
{
"paths":{
"@foo/bar": ["foo__bar"]
}
}
```
#### История файлов в GitHub выглядит неполной.
GitHub не [поддерживает](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) историю файлов для переименованных файлов. Вместо этого используйте [`git log --follow`](https://www.git-scm.com/docs/git-log).
#### Должен ли я добавить пустой namespace в пакет, который не экспортирует модуль для использования импорта в стиле ES6?
Некоторые пакеты, такие как [chai-http](https://github.com/chaijs/chai-http), экспортируют функцию.
Импорт этого модуля с импортом в стиле ES6 в форме `import * as foo from "foo";` приводит к ошибке:
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
Эту ошибку можно устранить, объединив объявление функции с пустым namespace'ом с тем же именем, но это не рекомендуется.
Это часто цитируемый [ответ с Stack Overflow](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) по этому вопросу.
Более целесообразно импортировать модуль, используя `import foo = require("foo");` синтаксис или использовать импорт по умолчанию, такой как `import foo from "foo";` при использовании флага `--allowSyntheticDefaultImports`, если среда выполнения вашего модуля поддерживает схему взаимодействия для модулей не-ECMAScript как таковых.
## Лицензия
Этот проект лицензирован по лицензии MIT.
Авторские права на файлы определений принадлежат каждому участнику, указанному в начале каждого файла определения.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) В среднем пакеты публикуются на npm менее чем за 10000 секунд?
[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Был ли typescript-bot активным на DefinitelyTyped в последние два часа?

24
azure-pipelines.yml Normal file
View File

@@ -0,0 +1,24 @@
# Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml
jobs:
- job: npmRunTest
pool:
vmImage: 'Ubuntu 16.04'
demands: npm
timeoutInMinutes: 360
steps:
- task: Npm@1
displayName: 'npm install'
inputs:
verbose: false
- script: 'git checkout -- . && npm run test'
displayName: 'npm run test'
trigger:
- master

File diff suppressed because it is too large Load Diff

View File

@@ -17,11 +17,13 @@
"scripts": {
"compile-scripts": "tsc -p scripts",
"not-needed": "node scripts/not-needed.js",
"update-codeowners": "node scripts/update-codeowners.js",
"test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed",
"lint": "dtslint types"
},
"devDependencies": {
"dtslint": "github:Microsoft/dtslint#production",
"types-publisher": "Microsoft/types-publisher#production"
}
"dtslint": "latest",
"types-publisher": "github:Microsoft/types-publisher#production"
},
"dependencies": {}
}

View File

@@ -1,13 +1,10 @@
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true,
"baseUrl": "../types",
"typeRoots": [
"../types"
@@ -15,4 +12,4 @@
"types": [],
"forceConsistentCasingInFileNames": true
}
}
}

View File

@@ -0,0 +1,126 @@
/// <reference lib="esnext.asynciterable" />
// Must reference esnext.asynciterable lib, since octokit uses AsyncIterable internally
const cp = require("child_process");
const Octokit = require("@octokit/rest");
const { AllPackages, getDefinitelyTyped, loggerWithErrors,
parseDefinitions, parseNProcesses, clean } = require("types-publisher");
const { writeFile } = require("fs-extra");
async function main() {
const options = { definitelyTypedPath: ".", progress: false, parseInParallel: true };
const log = loggerWithErrors()[0];
clean();
const dt = await getDefinitelyTyped(options, log);
await parseDefinitions(dt, { nProcesses: parseNProcesses(), definitelyTypedPath: "." }, log);
const allPackages = await AllPackages.read(dt);
const typings = allPackages.allTypings();
const maxPathLen = Math.max(...typings.map(t => t.subDirectoryPath.length));
const entries = mapDefined(typings, t => getEntry(t, maxPathLen));
await writeFile([options.definitelyTypedPath, ".github", "CODEOWNERS"].join("/"), `${header}\n\n${entries.join("\n")}\n`, { encoding: "utf-8" });
}
const token = /** @type {string} */(process.env.GH_TOKEN);
const gh = new Octokit();
const reviewers = ["weswigham", "sandersn", "RyanCavanaugh"]
const now = new Date();
const branchName = `codeowner-update-${now.getFullYear()}${padNum(now.getMonth())}${padNum(now.getDay())}`;
const remoteUrl = `https://${token}@github.com/DefinitelyTyped/DefinitelyTyped.git`;
runSequence([
["git", ["checkout", "."]], // reset any changes
]);
main().then(() => {
runSequence([
["git", ["checkout", "-b", branchName]], // create a branch
["git", ["add", ".github/CODEOWNERS"]], // Add CODEOWNERS
["git", ["commit", "-m", `"Update CODEOWNERS"`]], // Commit all changes
["git", ["remote", "add", "fork", remoteUrl]], // Add the remote fork
["git", ["push", "--set-upstream", "fork", branchName, "-f"]] // push the branch
]);
gh.authenticate({
type: "token",
token,
});
return gh.pulls.create({
owner: "DefinitelyTyped",
repo: "DefinitelyTyped",
maintainer_can_modify: true,
title: `🤖 CODEOWNERS has changed`,
head: `DefinitelyTyped:${branchName}`,
base: "master",
body:
`Please review the diff and merge if no changes are unexpected.
cc ${reviewers.map(r => "@" + r).join(" ")}`,
})
}).then(r => {
const num = r.data.number;
console.log(`Pull request ${num} created.`);
return gh.pulls.createReviewRequest({
owner: "DefinitelyTyped",
repo: "DefinitelyTyped",
number: num,
reviewers,
});
}).then(() => {
console.log(`Reviewers requested, done.`);
}).catch(e => {
console.error(e);
process.exit(1);
});
/** @param {[string, string[]][]} tasks */
function runSequence(tasks) {
for (const task of tasks) {
console.log(`${task[0]} ${task[1].join(" ")}`);
const result = cp.spawnSync(task[0], task[1], { timeout: 100000, shell: true, stdio: "inherit" });
if (result.status !== 0) throw new Error(`${task[0]} ${task[1].join(" ")} failed: ${result.stderr && result.stderr.toString()}`);
}
}
/** @param {number} number */
function padNum(number) {
const str = "" + number;
return str.length >= 2 ? str : "0" + str;
}
const header =
`# This file is generated.
# Add yourself to the "Definitions by:" list instead.
# See https://github.com/DefinitelyTyped/DefinitelyTyped#edit-an-existing-package`;
/**
* @param { { contributors: ReadonlyArray<{githubUsername?: string }>, subDirectoryPath: string} } pkg
* @param {number} maxPathLen
* @return {string | undefined}
*/
function getEntry(pkg, maxPathLen) {
const users = mapDefined(pkg.contributors, c => c.githubUsername);
if (!users.length) {
return undefined;
}
const path = `${pkg.subDirectoryPath}/`.padEnd(maxPathLen);
return `/types/${path} ${users.map(u => `@${u}`).join(" ")}`;
}
/**
* @template T,U
* @param {ReadonlyArray<T>} arr
* @param {(t: T) => U | undefined} mapper
* @return U[]
*/
function mapDefined(arr, mapper) {
const out = [];
for (const a of arr) {
const res = mapper(a);
if (res !== undefined) {
out.push(res);
}
}
return out;
}

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

@@ -1,5 +1,5 @@
// Type definitions for abs 1.3
// Project: https://github.com/IonicaBizau/node-abs
// Project: https://github.com/ionicabizau/abs
// Definitions by: Aya Morisawa <https://github.com/AyaMorisawa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -8,6 +8,7 @@
"callable-types": false,
"comment-format": false,
"dt-header": false,
"npm-naming": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,

View File

@@ -0,0 +1,17 @@
import { AbstractLevelDOWN } from 'abstract-leveldown';
const test = (levelDown: AbstractLevelDOWN<any, string>) => {
levelDown.put("key", "value", (err?) => { });
levelDown.put(1, "value", { something: true }, (err?) => { });
levelDown.get("key", (err?) => { });
levelDown.get(1, { something: true }, (err?) => { });
};
// $ExpectType void
test(new AbstractLevelDOWN('here'));
// $ExpectType void
test(AbstractLevelDOWN('there'));
// $ExpectType void
test(new AbstractLevelDOWN<any, string>('here'));
// $ExpectType void
test(AbstractLevelDOWN<any, string>('there'));

114
types/abstract-leveldown/index.d.ts vendored Normal file
View File

@@ -0,0 +1,114 @@
// Type definitions for abstract-leveldown 5.0
// Project: https://github.com/Level/abstract-leveldown
// Definitions by: Meirion Hughes <https://github.com/MeirionHughes>
// Daniel Byrne <https://github.com/danwbyrne>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
export interface AbstractOptions {
readonly [k: string]: any;
}
export type ErrorCallback = (err: Error | undefined) => void;
export type ErrorValueCallback<V> = (err: Error | undefined, value: V) => void;
export type ErrorKeyValueCallback<K, V> = (err: Error | undefined, key: K, value: V) => void;
export interface AbstractOpenOptions extends AbstractOptions {
createIfMissing?: boolean;
errorIfExists?: boolean;
}
export interface AbstractGetOptions extends AbstractOptions {
asBuffer?: boolean;
}
export interface AbstractLevelDOWN<K = any, V = any> extends AbstractOptions {
open(cb: ErrorCallback): void;
open(options: AbstractOpenOptions, cb: ErrorCallback): void;
close(cb: ErrorCallback): void;
get(key: K, cb: ErrorValueCallback<V>): void;
get(key: K, options: AbstractGetOptions, cb: ErrorValueCallback<V>): void;
put(key: K, value: V, cb: ErrorCallback): void;
put(key: K, value: V, options: AbstractOptions, cb: ErrorCallback): void;
del(key: K, cb: ErrorCallback): void;
del(key: K, options: AbstractOptions, cb: ErrorCallback): void;
batch(): AbstractChainedBatch<K, V>;
batch(array: ReadonlyArray<AbstractBatch<K, V>>, cb: ErrorCallback): AbstractChainedBatch<K, V>;
batch(
array: ReadonlyArray<AbstractBatch<K, V>>,
options: AbstractOptions,
cb: ErrorCallback,
): AbstractChainedBatch<K, V>;
iterator(options?: AbstractIteratorOptions<K>): AbstractIterator<K, V>;
}
export interface AbstractLevelDOWNConstructor {
// tslint:disable-next-line no-unnecessary-generics
new <K = any, V = any>(location: string): AbstractLevelDOWN<K, V>;
// tslint:disable-next-line no-unnecessary-generics
<K = any, V = any>(location: string): AbstractLevelDOWN<K, V>;
}
export interface AbstractIteratorOptions<K = any> extends AbstractOptions {
gt?: K;
gte?: K;
lt?: K;
lte?: K;
reverse?: boolean;
limit?: number;
keys?: boolean;
values?: boolean;
keyAsBuffer?: boolean;
valueAsBuffer?: boolean;
}
export type AbstractBatch<K = any, V = any> = PutBatch<K, V> | DelBatch<K, V>;
export interface PutBatch<K = any, V = any> {
readonly type: 'put';
readonly key: K;
readonly value: V;
}
export interface DelBatch<K = any, V = any> {
readonly type: 'del';
readonly key: K;
}
export interface AbstractChainedBatch<K = any, V = any> extends AbstractOptions {
put: (key: K, value: V) => this;
del: (key: K) => this;
clear: () => this;
write(cb: ErrorCallback): any;
write(options: any, cb: ErrorCallback): any;
}
export interface AbstractChainedBatchConstructor {
// tslint:disable-next-line no-unnecessary-generics
new <K = any, V = any>(db: any): AbstractChainedBatch<K, V>;
// tslint:disable-next-line no-unnecessary-generics
<K = any, V = any>(db: any): AbstractChainedBatch<K, V>;
}
export interface AbstractIterator<K, V> extends AbstractOptions {
db: AbstractLevelDOWN<K, V>;
next(cb: ErrorKeyValueCallback<K, V>): this;
end(cb: ErrorCallback): void;
}
export interface AbstractIteratorConstructor {
// tslint:disable-next-line no-unnecessary-generics
new <K = any, V = any>(db: any): AbstractIterator<K, V>;
// tslint:disable-next-line no-unnecessary-generics
<K = any, V = any>(db: any): AbstractIterator<K, V>;
}
export const AbstractLevelDOWN: AbstractLevelDOWNConstructor;
export const AbstractIterator: AbstractIteratorConstructor;
export const AbstractChainedBatch: AbstractChainedBatchConstructor;

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",
"abstract-leveldown-tests.ts"
]
}

View File

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

View File

@@ -8,6 +8,7 @@
"callable-types": false,
"comment-format": false,
"dt-header": false,
"npm-naming": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,

View File

@@ -20,11 +20,17 @@ const l3: AcceptLanguageParser.Language = {
quality: 0.9
};
type Lang = "en-US" | "ko-KR";
const enUs: Lang = "en-US";
const koKr: Lang = "ko-KR";
const parsed1: AcceptLanguageParser.Language[] = AcceptLanguageParser.parse('');
const pick1: string | null = AcceptLanguageParser.pick([''], '');
const pick2: string | null = AcceptLanguageParser.pick([''], [l1, l2, l3]);
const pick3: string | null = AcceptLanguageParser.pick([''], '', {});
const pick4: string | null = AcceptLanguageParser.pick([''], '', { loose: true });
const pick5: Lang | null = AcceptLanguageParser.pick<Lang>([enUs, koKr], [l1, l2, l3]);
const pick6: Lang | null = AcceptLanguageParser.pick([enUs, koKr], [l1, l2, l3]);
const pickOptions: AcceptLanguageParser.PickOptions = {
loose: true

View File

@@ -1,17 +1,18 @@
// Type definitions for accept-language-parser 1.5
// Project: https://github.com/opentable/accept-language-parser
// Definitions by: Niklas Wulf <https://github.com/kampfgnom>
// Wooram Jun <https://github.com/chatoo2412>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
// https://github.com/opentable/accept-language-parser/blob/v1.4.1/index.js
// https://github.com/opentable/accept-language-parser/blob/v1.5.0/index.js
export function parse(acceptLanguage: string): Language[];
export function pick(
supportedLanguages: string[],
export function pick<T extends string>(
supportedLanguages: T[],
acceptLanguage: string | Language[],
options?: PickOptions
): string | null;
): T | null;
export interface Language {
code: string;

View File

@@ -0,0 +1,31 @@
import * as accept from 'accept';
accept.charsets("iso-8859-5, unicode-1-1;q=0.8"); // charset === "iso-8859-5"
accept.charset("iso-8859-5, unicode-1-1;q=0.8", ["unicode-1-1"]); // charset === "unicode-1-1"
accept.encoding("gzip, deflate, sdch"); // encoding === "gzip"
accept.encoding("gzip, deflate, sdch", ["deflate", "identity"]);
const encodings = accept.encodings("compress;q=0.5, gzip;q=1.0"); // encodings === ["gzip", "compress", "identity"]
encodings.lastIndexOf('');
accept.language("en;q=0.7, en-GB;q=0.8");
accept.language("en;q=0.7, en-GB;q=0.8", ["en-gb"]); // language === "en-GB"
const languages = accept.languages("da, en;q=0.7, en-GB;q=0.8"); // languages === ["da", "en-GB", "en"]
languages.lastIndexOf('');
accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1");
accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1", ["application/json", "text/html"]);
const mediaTypes = accept.mediaTypes("text/plain, application/json;q=0.5, text/html, */*;q=0.1");
// mediaTypes === ["text/plain", "text/html", "application/json", "*/*"]
mediaTypes.lastIndexOf('');
const headers = {
accept: 'text/plain, application/json;q=0.5, text/html, */*;q=0.1',
'accept-language': 'da, en;q=0.7, en-GB;q=0.8'
};
const all = accept.parseAll(headers);
all.charsets.length;
all.encodings.length;
all.languages.length;
all.mediaTypes.length;

22
types/accept/index.d.ts vendored Normal file
View File

@@ -0,0 +1,22 @@
// Type definitions for accept 3.1
// Project: https://github.com/hapijs/accept#readme
// Definitions by: feinoujc <https://github.com/feinoujc>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export function charset(charsetHeader?: string, preferences?: string[]): string;
export function charsets(charsetHeader?: string): string[];
export function encoding(encodingHeader?: string, preferences?: string[]): string;
export function encodings(encodingHeader?: string): string[];
export function language(languageHeader?: string, preferences?: string[]): string;
export function languages(languageHeader?: string): string[];
export function mediaType(mediaTypeHeader?: string, preferences?: string[]): string;
export function mediaTypes(mediaTypeHeader?: string): string[];
export function parseAll(
headers: Record<string, string | string[] | undefined>
): {
charsets: string[];
encodings: string[];
languages: string[];
mediaTypes: string[];
};

View File

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

12
types/ace/index.d.ts vendored
View File

@@ -549,6 +549,16 @@ declare namespace AceAjax {
getFoldsInRange(range: Range): any;
highlight(text: string): void;
/**
* Highlight lines from `startRow` to `EndRow`.
* @param startRow Define the start line of the highlight
* @param endRow Define the end line of the highlight
* @param clazz Set the CSS class for the marker
* @param inFront Set to `true` to establish a front marker
**/
highlightLines(startRow:number, endRow: number, clazz: string, inFront: boolean): Range;
/**
* Sets the `EditSession` to point to a new `Document`. If a `BackgroundTokenizer` exists, it also points to `doc`.
@@ -1223,7 +1233,7 @@ declare namespace AceAjax {
/**
* Returns `true` if the current `textInput` is in focus.
**/
isFocused(): void;
isFocused(): boolean;
/**
* Blurs the current `textInput`.

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

@@ -8,6 +8,7 @@
"callable-types": false,
"comment-format": false,
"dt-header": false,
"npm-naming": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,

289
types/acl/index.d.ts vendored
View File

@@ -1,150 +1,179 @@
// Type definitions for node_acl 0.4.8
// Type definitions for acl 0.4
// Project: https://github.com/optimalbits/node_acl
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
/// <reference types="node"/>
/// <reference types="express"/>
import http = require('http');
import Promise = require("bluebird");
import express = require("express");
import Promise = require('bluebird');
import express = require('express');
import redis = require('redis');
import mongo = require('mongodb');
type strings = string|string[];
type Value = string|number;
type Values = Value|Value[];
export = AclStatic;
declare const AclStatic: AclStatic;
type strings = string | string[];
type Value = string | number;
type Values = Value | Value[];
type Action = () => any;
type Callback = (err: Error) => any;
type Callback = (err?: Error) => any;
type AnyCallback = (err: Error, obj: any) => any;
type AllowedCallback = (err: Error, allowed: boolean) => any;
type GetUserId = (req: http.IncomingMessage, res: http.ServerResponse) => Value;
interface AclStatic {
new (backend: Backend<any>, logger: Logger, options: Option): Acl;
new (backend: Backend<any>, logger: Logger): Acl;
new (backend: Backend<any>): Acl;
memoryBackend: MemoryBackendStatic;
new (
backend: AclStatic.Backend<any>,
logger?: AclStatic.Logger,
options?: AclStatic.Option
): AclStatic.Acl;
readonly memoryBackend: AclStatic.MemoryBackendStatic;
readonly mongodbBackend: AclStatic.MongodbBackendStatic;
readonly redisBackend: AclStatic.RedisBackendStatic;
}
interface Logger {
debug: (msg: string) => any;
}
interface Acl {
addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>;
removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>;
userRoles: (userId: Value, cb?: (err: Error, roles: string[]) => any) => Promise<string[]>;
roleUsers: (role: Value, cb?: (err: Error, users: Values) => any) => Promise<any>;
hasRole: (userId: Value, role: string, cb?: (err: Error, isInRole: boolean) => any) => Promise<boolean>;
addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise<void>;
removeRole: (role: string, cb?: Callback) => Promise<void>;
removeResource: (resource: string, cb?: Callback) => Promise<void>;
allow: {
(roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise<void>;
(aclSets: AclSet | AclSet[]): Promise<void>;
declare namespace AclStatic {
interface Logger {
debug: (msg: string) => any;
}
removeAllow: (role: string, resources: strings, permissions: strings, cb?: Callback) => Promise<void>;
removePermissions: (role: string, resources: strings, permissions: strings, cb?: Function) => Promise<void>;
allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise<void>;
isAllowed: (userId: Value, resources: strings, permissions: strings, cb?: AllowedCallback) => Promise<boolean>;
areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise<any>;
whatResources: {
(roles: strings, cb?: AnyCallback): Promise<any>;
(roles: strings, permissions: strings, cb?: AnyCallback): Promise<any>;
interface Acl {
addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>;
removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>;
userRoles: (userId: Value, cb?: (err: Error, roles: string[]) => any) => Promise<string[]>;
roleUsers: (role: Value, cb?: (err: Error, users: Values) => any) => Promise<any>;
hasRole: (
userId: Value,
role: string,
cb?: (err: Error, isInRole: boolean) => any
) => Promise<boolean>;
addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise<void>;
removeRole: (role: string, cb?: Callback) => Promise<void>;
removeResource: (resource: string, cb?: Callback) => Promise<void>;
allow: {
(roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise<void>;
(aclSets: AclSet | AclSet[]): Promise<void>;
};
removeAllow: (
role: string,
resources: strings,
permissions: strings,
cb?: Callback
) => Promise<void>;
removePermissions: (
role: string,
resources: strings,
permissions: strings,
cb?: Callback
) => Promise<void>;
allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise<void>;
isAllowed: (
userId: Value,
resources: strings,
permissions: strings,
cb?: AllowedCallback
) => Promise<boolean>;
areAnyRolesAllowed: (
roles: strings,
resource: strings,
permissions: strings,
cb?: AllowedCallback
) => Promise<any>;
whatResources: {
(roles: strings, cb?: AnyCallback): Promise<any>;
(roles: strings, permissions: strings, cb?: AnyCallback): Promise<any>;
};
permittedResources: (roles: strings, permissions: strings, cb?: Callback) => Promise<void>;
middleware: (
numPathComponents?: number,
userId?: Value | GetUserId,
actions?: strings
) => express.RequestHandler;
}
interface Option {
buckets?: BucketsOption;
}
interface BucketsOption {
meta?: string;
parents?: string;
permissions?: string;
resources?: string;
roles?: string;
users?: string;
}
interface AclSet {
roles: strings;
allows: AclAllow[];
}
interface AclAllow {
resources: strings;
permissions: strings;
}
interface MemoryBackend extends Backend<Action[]> {}
interface MemoryBackendStatic {
new (): MemoryBackend;
}
//
// For internal use
//
interface Backend<T> {
begin: () => T;
end: (transaction: T, cb?: Action) => void;
clean: (cb?: Action) => void;
get: (bucket: string, key: Value, cb?: Action) => void;
union: (bucket: string, keys: Value[], cb?: Action) => void;
add: (transaction: T, bucket: string, key: Value, values: Values) => void;
del: (transaction: T, bucket: string, keys: Value[]) => void;
remove: (transaction: T, bucket: string, key: Value, values: Values) => void;
endAsync: (transaction: T, cb?: (err: Error | null) => void) => Promise<void>;
getAsync: (
bucket: string,
key: Value,
cb?: (err: Error | null, value: any) => void
) => Promise<any>;
cleanAsync: (cb?: (error?: Error) => void) => Promise<void>;
unionAsync: (
bucket: string,
keys: Value[],
cb?: (error: Error | undefined, results: any[]) => void
) => Promise<any[]>;
}
interface Contract {
(args: IArguments): Contract | NoOp;
debug: boolean;
fulfilled: boolean;
args: any[];
checkedParams: string[];
params: (...types: string[]) => Contract | NoOp;
end: () => void;
}
interface NoOp {
params: (...types: string[]) => NoOp;
end: () => void;
}
// for redis backend
interface RedisBackend extends Backend<redis.RedisClient> {}
interface RedisBackendStatic {
new (redis: redis.RedisClient, prefix?: string): RedisBackend;
}
// for mongodb backend
interface MongodbBackend extends Backend<Callback> {}
interface MongodbBackendStatic {
new (db: mongo.Db, prefix?: string, useSingle?: boolean): MongodbBackend;
}
permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise<void>;
middleware: (numPathComponents?: number, userId?: Value | GetUserId, actions?: strings) => express.RequestHandler;
}
interface Option {
buckets?: BucketsOption;
}
interface BucketsOption {
meta?: string;
parents?: string;
permissions?: string;
resources?: string;
roles?: string;
users?: string;
}
interface AclSet {
roles: strings;
allows: AclAllow[];
}
interface AclAllow {
resources: strings;
permissions: strings;
}
interface MemoryBackend extends Backend<Action[]> { }
interface MemoryBackendStatic {
new (): MemoryBackend;
}
//
// For internal use
//
interface Backend<T> {
begin: () => T;
end: (transaction: T, cb?: Action) => void;
clean: (cb?: Action) => void;
get: (bucket: string, key: Value, cb?: Action) => void;
union: (bucket: string, keys: Value[], cb?: Action) => void;
add: (transaction: T, bucket: string, key: Value, values: Values) => void;
del: (transaction: T, bucket: string, keys: Value[]) => void;
remove: (transaction: T, bucket: string, key: Value, values: Values) => void;
endAsync: Function; //TODO: Give more specific function signature
getAsync: Function;
cleanAsync: Function;
unionAsync: Function;
}
interface Contract {
(args: IArguments): Contract | NoOp;
debug: boolean;
fulfilled: boolean;
args: any[];
checkedParams: string[];
params: (...types: string[]) => Contract | NoOp;
end: () => void;
}
interface NoOp {
params: (...types: string[]) => NoOp;
end: () => void;
}
// for redis backend
import redis = require('redis');
interface AclStatic {
redisBackend: RedisBackendStatic;
}
interface RedisBackend extends Backend<redis.RedisClient> { }
interface RedisBackendStatic {
new (redis: redis.RedisClient, prefix: string): RedisBackend;
new (redis: redis.RedisClient): RedisBackend;
}
// for mongodb backend
import mongo = require('mongodb');
interface AclStatic {
mongodbBackend: MongodbBackendStatic;
}
interface MongodbBackend extends Backend<Callback> { }
interface MongodbBackendStatic {
new (db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend;
new (db: mongo.Db, prefix: string): MongodbBackend;
new (db: mongo.Db): MongodbBackend;
}
declare var _: AclStatic;
export = _;

View File

@@ -2,15 +2,15 @@
// https://github.com/OptimalBits/node_acl/blob/master/Readme.md
import Acl = require('acl');
var report = <T>(err: Error, value: T) => {
if (err) {
console.error(err);
}
console.info(value);
const report = (err: Error, value: any) => {
if (err) {
console.error(err);
}
console.info(value);
};
// Using the memory backend
var acl = new Acl(new Acl.memoryBackend());
const acl: Acl.Acl = new Acl(new Acl.memoryBackend());
// middleware with no optional parameters
acl.middleware();
@@ -18,11 +18,11 @@ acl.middleware();
acl.middleware(1);
acl.middleware(1, () => {
return "joed";
return 'joed';
});
acl.middleware(1, () => {
return 2;
return 2;
});
acl.middleware(1, 'joed');
@@ -33,36 +33,36 @@ acl.middleware(3, 'joed', 'post');
acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);
acl.allow('member', 'blogs', ['edit', 'view', 'delete']);
acl.addUserRoles('joed', 'guest');
acl.addRoleParents('baz', ['foo','bar']);
acl.addRoleParents('baz', ['foo', 'bar']);
acl.allow('foo', ['blogs','forums','news'], ['view', 'delete']);
acl.allow('foo', ['blogs', 'forums', 'news'], ['view', 'delete']);
acl.allow('admin', ['blogs','forums'], '*');
acl.allow('admin', ['blogs', 'forums'], '*');
acl.allow([
{
roles:['guest','special-member'],
allows:[
{resources:'blogs', permissions:'get'},
{resources:['forums','news'], permissions:['get','put','delete']}
]
roles: ['guest', 'special-member'],
allows: [
{ resources: 'blogs', permissions: 'get' },
{ resources: ['forums', 'news'], permissions: ['get', 'put', 'delete'] },
],
},
{
roles:['gold','silver'],
allows:[
{resources:'cash', permissions:['sell','exchange']},
{resources:['account','deposit'], permissions:['put','delete']}
]
}
roles: ['gold', 'silver'],
allows: [
{ resources: 'cash', permissions: ['sell', 'exchange'] },
{ resources: ['account', 'deposit'], permissions: ['put', 'delete'] },
],
},
]);
acl.isAllowed('joed', 'blogs', 'view', (err, res) => {
if (res) {
console.log("User joed is allowed to view blogs");
console.log('User joed is allowed to view blogs');
}
});
@@ -78,15 +78,14 @@ acl.whatResources('foo', 'view', (err, res) => {
}
});
acl.isAllowed('jsmith', 'blogs', ['edit','view','delete'])
.then((result) => {
console.dir('jsmith is allowed blogs ' + result);
acl.addUserRoles('jsmith', 'member');
}).then(() =>
acl.isAllowed('jsmith', 'blogs', ['edit','view','delete'])
).then((result) =>
console.dir('jsmith is allowed blogs ' + result)
).then(() => {
acl.allowedPermissions('james', ['blogs','forums'], report);
acl.allowedPermissions('jsmith', ['blogs','forums'], report);
});
acl.isAllowed('jsmith', 'blogs', ['edit', 'view', 'delete'])
.then(result => {
console.dir('jsmith is allowed blogs ' + result);
acl.addUserRoles('jsmith', 'member');
})
.then(() => acl.isAllowed('jsmith', 'blogs', ['edit', 'view', 'delete']))
.then(result => console.dir('jsmith is allowed blogs ' + result))
.then(() => {
acl.allowedPermissions('james', ['blogs', 'forums'], report);
acl.allowedPermissions('jsmith', ['blogs', 'forums'], report);
});

View File

@@ -5,10 +5,10 @@ import mongodb = require('mongodb');
declare var db: mongodb.Db;
// Using the mongo db backend
var acl = new Acl(new Acl.mongodbBackend(db, 'acl_', true));
const acl = new Acl(new Acl.mongodbBackend(db, 'acl_', true));
// guest is allowed to view blogs
acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);
acl.allow('member', 'blogs', ['edit', 'view', 'delete']);

View File

@@ -5,10 +5,10 @@ import redis = require('redis');
declare var client: redis.RedisClient;
// Using the redis backend
var acl = new Acl(new Acl.redisBackend(client, 'acl_'));
const acl = new Acl(new Acl.redisBackend(client, 'acl_'));
// guest is allowed to view blogs
acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);
acl.allow('member', 'blogs', ['edit', 'view', 'delete']);

View File

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

View File

@@ -1,5 +1,5 @@
// Type definitions for Acorn 4.0
// Project: https://github.com/marijnh/acorn
// Project: https://github.com/acornjs/acorn
// Definitions by: RReverser <https://github.com/RReverser>, e-cloud <https://github.com/e-cloud>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -246,9 +246,7 @@ declare namespace acorn {
let LooseParser: ILooseParserClass | undefined;
let pluginsLoose: PluginsObject | undefined;
interface ILooseParserClass {
new (input: string, options?: Options): ILooseParser;
}
type ILooseParserClass = new (input: string, options?: Options) => ILooseParser;
interface ILooseParser {}

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

@@ -8,6 +8,7 @@
"callable-types": false,
"comment-format": false,
"dt-header": false,
"npm-naming": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,

View File

@@ -0,0 +1,17 @@
import activeWin = require('active-win');
// $ExpectType Promise<Result>
activeWin();
// $ExpectType Result
activeWin.sync();
let win = {
title: 'Unicorns - Google Search',
id: 5762,
owner: {
name: 'Google Chrome',
processId: 310,
},
};
win = activeWin.sync();

30
types/active-win/index.d.ts vendored Normal file
View File

@@ -0,0 +1,30 @@
// Type definitions for active-win 4.0
// Project: https://github.com/sindresorhus/active-win#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = activeWin;
declare function activeWin(): Promise<activeWin.Result>;
declare namespace activeWin {
function sync(): Result;
interface Result {
title: string;
id: number;
bounds?: {
x: number;
y: number;
width: number;
height: number;
};
owner: {
name: string;
processId: number;
bundleId?: number;
path?: string;
};
memoryUsage?: number;
}
}

View File

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

View File

@@ -0,0 +1,28 @@
import * as ActiveStorage from 'activestorage';
ActiveStorage.start();
const delegate: ActiveStorage.DirectUploadDelegate = {
directUploadWillCreateBlobWithXHR(xhr) {
console.log(xhr.status);
},
directUploadWillStoreFileWithXHR(xhr) {
console.log(xhr.status);
},
};
const d = new ActiveStorage.DirectUpload(
new File([], 'blank.txt'),
'/rails/active_storage/direct_uploads',
delegate
);
d.create((error, blob) => {
if (error) {
console.log(error.message);
} else {
const { byte_size, checksum, content_type, filename, signed_id } = blob;
console.log({ byte_size, checksum, content_type, filename, signed_id });
}
});

33
types/activestorage/index.d.ts vendored Normal file
View File

@@ -0,0 +1,33 @@
// Type definitions for ActiveStorage 5.2
// Project: https://github.com/rails/rails/tree/master/activestorage/app/javascript, http://rubyonrails.org
// Definitions by: Cameron Bothner <https://github.com/cbothner>
// Definitions: https://github.com/cbothner/DefinitelyTyped
// TypeScript Version: 2.1
export as namespace ActiveStorage
export function start(): void;
export class DirectUpload {
id: number;
file: File;
url: string;
constructor(file: File, url: string, delegate: DirectUploadDelegate)
create(callback: (error: Error, blob: Blob) => void): void;
}
export interface DirectUploadDelegate {
directUploadWillCreateBlobWithXHR?: (xhr: XMLHttpRequest) => void;
directUploadWillStoreFileWithXHR?: (xhr: XMLHttpRequest) => void;
}
export interface Blob {
byte_size: number;
checksum: string;
content_type: string;
filename: string;
signed_id: string;
}

View File

@@ -0,0 +1,16 @@
{
"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", "activestorage-tests.ts"]
}

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft Access 14.0 Object Library - Access 14.0
// Type definitions for non-npm package Microsoft Access 14.0 Object Library - Access 14.0
// Project: https://msdn.microsoft.com/en-us/library/dn142571.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft ActiveX Data Objects 6.0 Library - ADODB 6.1
// Type definitions for non-npm package Microsoft ActiveX Data Objects 6.0 Library - ADODB 6.1
// Project: https://msdn.microsoft.com/en-us/library/jj249010.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft ADO Extensions 6.0 for DDL and Security - ADOX 6.0
// Type definitions for non-npm package Microsoft ADO Extensions 6.0 for DDL and Security - ADOX 6.0
// Project: https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/adox-object-model
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft Office 16.0 Access Database Engine Object Library - DAO 16.0
// Type definitions for non-npm package Microsoft Office 16.0 Access Database Engine Object Library - DAO 16.0
// Project: https://msdn.microsoft.com/en-us/library/dn124645.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for DiskQuotaTypeLibrary 1.0
// Type definitions for non-npm package DiskQuotaTypeLibrary 1.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773938(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft Excel 14.0 Object Library - Excel 14.0
// Type definitions for non-npm package Microsoft Excel 14.0 Object Library - Excel 14.0
// Project: https://msdn.microsoft.com/en-us/library/fp179694.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft Fax Service Extended COM Type Library - FAXCOMEXLib 1.0
// Type definitions for non-npm package Microsoft Fax Service Extended COM Type Library - FAXCOMEXLib 1.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684513(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft InfoPath 3.0 Type Library - InfoPath 3.0
// Type definitions for non-npm package Microsoft InfoPath 3.0 Type Library - InfoPath 3.0
// Project: https://msdn.microsoft.com/en-us/library/jj602751.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Javascript Automation interop 0.0
// Type definitions for non-npm package Javascript Automation interop 0.0
// Project: https://msdn.microsoft.com/en-us/library/ff521046(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Windows Script Host Runtime Object Model 0.0
// Type definitions for non-npm package Windows Script Host Runtime Object Model 0.0
// Project: https://msdn.microsoft.com/en-us/library/9bbdkx3k.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for LibreOffice 5.3
// Type definitions for non-npm package LibreOffice 5.3
// Project: https://api.libreoffice.org/
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft Forms 2.0 Object Library - MSForms 2.0
// Type definitions for non-npm package Microsoft Forms 2.0 Object Library - MSForms 2.0
// Project: https://msdn.microsoft.com/VBA/Language-Reference-VBA/articles/reference-microsoft-forms
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft HTML Object Library - MSHTML 4.0
// Type definitions for non-npm package Microsoft HTML Object Library - MSHTML 4.0
// Project: https://msdn.microsoft.com/en-us/library/aa741317(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft XML, v6.0 - MSXML2 6.0
// Type definitions for non-npm package Microsoft XML, v6.0 - MSXML2 6.0
// Project: https://msdn.microsoft.com/en-us/library/ms763742.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft Office 16.0 Object Library - Office 16.0
// Type definitions for non-npm package Microsoft Office 16.0 Object Library - Office 16.0
// Project: https://msdn.microsoft.com/VBA/Office-Shared-VBA/articles/office-vba-object-library-reference
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft Outlook 14.0 Object Library - Outlook 14.0
// Type definitions for non-npm package Microsoft Outlook 14.0 Object Library - Outlook 14.0
// Project: https://msdn.microsoft.com/en-us/vba/vba-outlook
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft PowerPoint 14.0 Object Library - PowerPoint 14.0
// Type definitions for non-npm package Microsoft PowerPoint 14.0 Object Library - PowerPoint 14.0
// Project: https://msdn.microsoft.com/en-us/library/fp161225.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft Scripting Runtime 1.0
// Type definitions for non-npm package Microsoft Scripting Runtime 1.0
// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7(v=vs.84).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft Internet Controls - SHDocVw 1.1
// Type definitions for non-npm package Microsoft Internet Controls - SHDocVw 1.1
// Project: https://msdn.microsoft.com/en-us/library/aa752040(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft Shell Controls And Automation - Shell32 1.0
// Type definitions for non-npm package Microsoft Shell Controls And Automation - Shell32 1.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773938(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for OLE Automation - stdole 2.0
// Type definitions for non-npm package OLE Automation - stdole 2.0
// Project: https://msdn.microsoft.com/en-us/library/hh272953.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft Visual Basic for Applications Extensibility 5.3 - VBIDE 14.0
// Type definitions for non-npm package Microsoft Visual Basic for Applications Extensibility 5.3 - VBIDE 14.0
// Project: https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/collections-visual-basic-add-in-model
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Windows Image Acquisition 2.0
// Type definitions for non-npm package Windows Image Acquisition 2.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms630368(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,4 +1,4 @@
// Type definitions for Microsoft Word 14.0 Object Library - Word 14.0
// Type definitions for non-npm package Microsoft Word 14.0 Object Library - Word 14.0
// Project: https://msdn.microsoft.com/en-us/library/fp179696.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

View File

@@ -1,3 +1,3 @@
import addZero from "add-zero";
import addZero = require("add-zero");
addZero(5, 2);

View File

@@ -3,4 +3,5 @@
// Definitions by: Giles Roadnight <https://github.com/Roaders>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export default function addZero(value: string | number, digits?: number): string;
export = addZero;
declare function addZero(value: string | number, digits?: number): string;

View File

@@ -8,6 +8,7 @@
"callable-types": false,
"comment-format": false,
"dt-header": false,
"npm-naming": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,

View File

@@ -0,0 +1,40 @@
/*
| Copyright 2018 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
import * as adlib from "adlib";
const transform1: adlib.TransformFunction =
(key: string, value: any, settings: any, param?: any): any => {
return null;
};
const transformsList: adlib.TransformsList = {
firstXform: transform1
};
const template = {
value: '{{ instance.color }}'
};
const settings = {
instance: {
color: 'red'
}
};
const interpolated = adlib.adlib(template, settings, transformsList);
const list: string[] = adlib.listDependencies(template);

75
types/adlib/index.d.ts vendored Normal file
View File

@@ -0,0 +1,75 @@
// Type definitions for adlib 3.0
// Project: https://github.com/Esri/adlib, https://arcgis.github.io/ember-arcgis-adlib-service
// Definitions by: Esri <https://github.com/Esri>
// Mike Tschudi <https://github.com/MikeTschudi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/*
| Copyright 2018 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
/**
* Transform function to apply to interpolated value.
*
* @param key Path within a handlebar-style expression to attempt to replace; e.g., `s.animal.type` in
* https://github.com/Esri/adlib#transforms
* @param value Value to replace expression with
* @param settings Hash providing values to insert into template; see https://github.com/Esri/adlib#general-pattern
* @param param Parameter for transform function; e.g., the `optional` transform accepts a count of levels
* to delete if the value is not found (default is 0--just the current level);
* see https://github.com/Esri/adlib#optional-transform
*/
export interface TransformFunction {
(
key: string,
value: any,
settings: any,
param?: any
): any;
}
/**
* Set of transformation functions keyed by the transform function's name.
*/
export interface TransformsList {
[ transformFnName: string ]: TransformFunction;
}
/**
* A JavaScript library for interpolating property values in JSON Objects.
*
* @param template A template that possibly containing handlebar-style property values to replace;
* see https://github.com/Esri/adlib#general-pattern
* @param settings Hash providing values to insert into template; see https://github.com/Esri/adlib#general-pattern
* @param transforms Set of transformation functions
* @return Copy of template with replacements performed
*/
export function adlib(
template: any,
settings: any,
transforms?: TransformsList
): any;
/**
* Reads a template and spits out unique handlebar-style property values.
*
* @param template A template that possibly containing handlebar-style property values to replace;
* see https://github.com/Esri/adlib#general-pattern
* @return List of unique property values in template
*/
export function listDependencies(
template: any
): string [];

23
types/adlib/tsconfig.json Normal file
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",
"adlib-tests.ts"
]
}

View File

@@ -1,62 +1,69 @@
import AdmZip = require("adm-zip");
import AdmZip = require('adm-zip');
// reading archives
var zip = new AdmZip("./my_file.zip");
var zipEntries: AdmZip.IZipEntry[] = zip.getEntries(); // an array of ZipEntry records
const zip = new AdmZip('./my_file.zip');
const zipEntries: AdmZip.IZipEntry[] = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function (zipEntry) {
zipEntries.forEach(zipEntry => {
console.log(zipEntry.toString()); // outputs zip entries information
if (zipEntry.entryName == "my_file.txt") {
if (zipEntry.entryName === 'my_file.txt') {
console.log(zipEntry.getData().toString('utf8'));
}
});
// outputs the content of some_folder/my_file.txt
console.log(zip.readAsText("some_folder/my_file.txt"));
console.log(zip.readAsText('some_folder/my_file.txt'));
// extracts the specified file to the specified location
zip.extractEntryTo(/*entry name*/"some_folder/my_file.txt", /*target path*/"/home/me/tempfolder", /*overwrite*/true)
zip.extractEntryTo(
/*entry name*/ 'some_folder/my_file.txt',
/*target path*/ '/home/me/tempfolder',
/*overwrite*/ true
);
// extracts everything
zip.extractAllTo(/*target path*/"/home/me/zipcontent/", /*overwrite*/true);
zip.extractAllTo(/*target path*/ '/home/me/zipcontent/', /*overwrite*/ true);
// extracts everything and calls callback -> async extracction
zip.extractAllToAsync(/*target path*/"/home/me/zipcontent/", /*overwrite*/true, (error: Error)=> {});
zip.extractAllToAsync(
/*target path*/ '/home/me/zipcontent/',
/*overwrite*/ true,
(error: Error) => {}
);
// creating archives
var zip = new AdmZip();
new AdmZip();
// add file directly
zip.addFile("test.txt", new Buffer("inner content of the file"), "entry comment goes here");
zip.addFile('test.txt', new Buffer('inner content of the file'), 'entry comment goes here');
// add local file
zip.addLocalFile("/home/me/some_picture.png");
zip.addLocalFile('/home/me/some_picture.png');
// get everything as a buffer
var willSendthis = zip.toBuffer();
const willSendthis = zip.toBuffer();
// or write everything to disk
zip.writeZip(/*target file name*/"/home/me/files.zip");
zip.writeZip(/*target file name*/ '/home/me/files.zip');
function processZipEntry(zipEntry: AdmZip.IZipEntry) {
console.log('comment', zipEntry.comment);
}
//tests taken from examples at https://github.com/cthackers/adm-zip/wiki/ADM-ZIP
import Zip = require("adm-zip");
// tests taken from examples at https://github.com/cthackers/adm-zip/wiki/ADM-ZIP
import Zip = require('adm-zip');
// loads and parses existing zip file local_file.zip
var zip = new Zip("local_file.zip");
new Zip('local_file.zip');
// creates new in memory zip
zip = new Zip();
new Zip();
// loads and parses existing zip file local_file.zip
zip = new Zip("local_file.zip");
new Zip('local_file.zip');
// get all entries and iterate them
zip.getEntries().forEach((entry) => {
var entryName = entry.entryName;
var decompressedData = zip.readFile(entry); // decompressed buffer of the entry
console.log(zip.readAsText(entry)); // outputs the decompressed content of the entry
zip.getEntries().forEach(entry => {
const entryName = entry.entryName;
const decompressedData = zip.readFile(entry); // decompressed buffer of the entry
console.log(zip.readAsText(entry)); // outputs the decompressed content of the entry
});
// will extract the file myfile.txt from the archive to /home/user/folder/subfolder/myfile.txt
zip.extractEntryTo("folder/subfolder/myfile.txt", "/home/user/", true, true);
zip.extractEntryTo('folder/subfolder/myfile.txt', '/home/user/', true, true);
// will extract the file myfile.txt from the archive to /home/user/myfile.txt
zip.extractEntryTo("folder/subfolder/myfile.txt", "/home/user/", false, true);
zip.extractEntryTo('folder/subfolder/myfile.txt', '/home/user/', false, true);
function isAdmZipEntry(obj: any): obj is AdmZip.IZipEntry {
return obj !== null && typeof obj === "object" && typeof obj['entryName'] === 'string';
return obj !== null && typeof obj === 'object' && typeof obj['entryName'] === 'string';
}

View File

@@ -1,90 +1,56 @@
// Type definitions for adm-zip v0.4.4
// Type definitions for adm-zip 0.4
// Project: https://github.com/cthackers/adm-zip
// Definitions by: John Vilk <https://github.com/jvilk>, Abner Oliveira <https://github.com/abner>
// Definitions by: John Vilk <https://github.com/jvilk>
// Abner Oliveira <https://github.com/abner>
// BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
declare class AdmZip {
/**
* Create a new, empty archive.
* @param fileNameOrRawData If provided, reads an existing archive. Otherwise creates a new, empty archive.
*/
constructor();
constructor(fileNameOrRawData?: string | Buffer);
/**
* Read an existing archive.
* Extracts the given entry from the archive and returns the content.
* @param entry The full path of the entry or a `IZipEntry` object.
* @return `Buffer` or `null` in case of error.
*/
constructor(fileName: string);
constructor(rawData: Buffer);
readFile(entry: string | AdmZip.IZipEntry): Buffer | null;
/**
* Extracts the given entry from the archive and returns the content as a
* Buffer object.
* @param entry String with the full path of the entry
* @return Buffer or Null in case of error
* Asynchronous `readFile`.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param callback Called with a `Buffer` or `null` in case of error.
*/
readFile(entry: string): Buffer;
/**
* Extracts the given entry from the archive and returns the content as a
* Buffer object.
* @param entry ZipEntry object
* @return Buffer or Null in case of error
*/
readFile(entry: AdmZip.IZipEntry): Buffer;
/**
* Asynchronous readFile
* @param entry String with the full path of the entry
* @param callback Called with a Buffer or Null in case of error
*/
readFileAsync(entry: string, callback: (data: Buffer, err: string) => any): void;
/**
* Asynchronous readFile
* @param entry ZipEntry object
* @param callback Called with a Buffer or Null in case of error
* @return Buffer or Null in case of error
*/
readFileAsync(entry: AdmZip.IZipEntry, callback: (data: Buffer, err: string) => any): void;
readFileAsync(
entry: string | AdmZip.IZipEntry,
callback: (data: Buffer | null, err: string) => any
): void;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding
* @param entry String with the full path of the entry
* @param encoding Optional. If no encoding is specified utf8 is used
* @return String
* plain text in the given encoding.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param encoding If no encoding is specified `"utf8"` is used.
*/
readAsText(fileName: string, encoding?: string): string;
readAsText(fileName: string | AdmZip.IZipEntry, encoding?: string): string;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding
* @param entry ZipEntry object
* @param encoding Optional. If no encoding is specified utf8 is used
* @return String
*/
readAsText(fileName: AdmZip.IZipEntry, encoding?: string): string;
/**
* Asynchronous readAsText
* @param entry String with the full path of the entry
* Asynchronous `readAsText`.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param callback Called with the resulting string.
* @param encoding Optional. If no encoding is specified utf8 is used
* @param encoding If no encoding is specified `"utf8"` is used.
*/
readAsTextAsync(fileName: string, callback: (data: string) => any, encoding?: string): void;
/**
* Asynchronous readAsText
* @param entry ZipEntry object
* @param callback Called with the resulting string.
* @param encoding Optional. If no encoding is specified utf8 is used
*/
readAsTextAsync(fileName: AdmZip.IZipEntry, callback: (data: string) => any, encoding?: string): void;
readAsTextAsync(
fileName: string | AdmZip.IZipEntry,
callback: (data: string) => any,
encoding?: string
): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory
* @param entry String with the full path of the entry
* and files if the given entry is a directory.
* @param entry The full path of the entry or a `IZipEntry` object.
*/
deleteFile(entry: string): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory
* @param entry A ZipEntry object.
*/
deleteFile(entry: AdmZip.IZipEntry): void;
deleteFile(entry: string | AdmZip.IZipEntry): void;
/**
* Adds a comment to the zip. The zip must be rewritten after
* adding the comment.
@@ -92,72 +58,55 @@ declare class AdmZip {
*/
addZipComment(comment: string): void;
/**
* Returns the zip comment
* @return The zip comment.
*/
getZipComment(): string;
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after
* Adds a comment to a specified file or `IZipEntry`. The zip must be rewritten after
* adding the comment.
* The comment cannot exceed 65535 characters in length.
* @param entry String with the full path of the entry
* @param entry The full path of the entry or a `IZipEntry` object.
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: string, comment: string): void;
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after
* adding the comment.
* The comment cannot exceed 65535 characters in length.
* @param entry ZipEntry object.
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: AdmZip.IZipEntry, comment: string): void;
addZipEntryComment(entry: string | AdmZip.IZipEntry, comment: string): void;
/**
* Returns the comment of the specified entry.
* @param entry String with the full path of the entry.
* @return String The comment of the specified entry.
* @param entry The full path of the entry or a `IZipEntry` object.
* @return The comment of the specified entry.
*/
getZipEntryComment(entry: string): string;
/**
* Returns the comment of the specified entry
* @param entry ZipEntry object.
* @return String The comment of the specified entry.
*/
getZipEntryComment(entry: AdmZip.IZipEntry): string;
getZipEntryComment(entry: string | AdmZip.IZipEntry): string;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content
* @param entry String with the full path of the entry.
* must be rewritten after updating the content.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param content The entry's new contents.
*/
updateFile(entry: string, content: Buffer): void;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content
* @param entry ZipEntry object.
* @param content The entry's new contents.
*/
updateFile(entry: AdmZip.IZipEntry, content: Buffer): void;
updateFile(entry: string | AdmZip.IZipEntry, content: Buffer): void;
/**
* Adds a file from the disk to the archive.
* @param localPath Path to a file on disk.
* @param zipPath Path to a directory in the archive. Defaults to the empty
* string.
* @param zipName Name for the file.
*/
addLocalFile(localPath: string, zipPath?: string): void;
addLocalFile(localPath: string, zipPath?: string, zipName?: string): void;
/**
* Adds a local directory and all its nested files and directories to the
* archive.
* @param localPath Path to a folder on disk.
* @param zipPath Path to a folder in the archive. Defaults to an empty
* string.
* @param zipPath Path to a folder in the archive. Default: `""`.
* @param filter RegExp or Function if files match will be included.
*/
addLocalFolder(localPath: string, zipPath?: string): void;
addLocalFolder(
localPath: string,
zipPath?: string,
filter?: RegExp | ((filename: string) => boolean)
): void;
/**
* Allows you to create a entry (file or directory) in the zip file.
* If you want to create a directory the entryName must end in / and a null
* If you want to create a directory the `entryName` must end in `"/"` and a `null`
* buffer should be provided.
* @param entryName Entry path
* @param entryName Entry path.
* @param content Content to add to the entry; must be a 0-length buffer
* for a directory.
* @param comment Comment to add to the entry.
@@ -165,89 +114,81 @@ declare class AdmZip {
*/
addFile(entryName: string, data: Buffer, comment?: string, attr?: number): void;
/**
* Returns an array of ZipEntry objects representing the files and folders
* inside the archive
* Returns an array of `IZipEntry` objects representing the files and folders
* inside the archive.
*/
getEntries(): AdmZip.IZipEntry[];
/**
* Returns a ZipEntry object representing the file or folder specified by
* ``name``.
* Returns a `IZipEntry` object representing the file or folder specified by `name`.
* @param name Name of the file or folder to retrieve.
* @return ZipEntry The entry corresponding to the name.
* @return The entry corresponding to the `name`.
*/
getEntry(name: string): AdmZip.IZipEntry;
/**
* Extracts the given entry to the given targetPath.
* Extracts the given entry to the given `targetPath`.
* If the entry is a directory inside the archive, the entire directory and
* its subdirectories will be extracted.
* @param entry String with the full path of the entry
* @param targetPath Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is
* inside a folder, the entry folder will be created in targetPath as
* well. Default is TRUE
* @param entry The full path of the entry or a `IZipEntry` object.
* @param targetPath Target folder where to write the file.
* @param maintainEntryPath If maintainEntryPath is `true` and the entry is
* inside a folder, the entry folder will be created in `targetPath` as
* well. Default: `true`.
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
*
* @return Boolean
* will be overwriten if this is `true`. Default: `false`.
*/
extractEntryTo(entryPath: string, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean;
extractEntryTo(
entryPath: string | AdmZip.IZipEntry,
targetPath: string,
maintainEntryPath?: boolean,
overwrite?: boolean
): boolean;
/**
* Extracts the given entry to the given targetPath.
* If the entry is a directory inside the archive, the entire directory and
* its subdirectories will be extracted.
* @param entry ZipEntry object
* @param targetPath Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is
* inside a folder, the entry folder will be created in targetPath as
* well. Default is TRUE
* Extracts the entire archive to the given location.
* @param targetPath Target location.
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
* @return Boolean
*/
extractEntryTo(entryPath: AdmZip.IZipEntry, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean;
/**
* Extracts the entire archive to the given location
* @param targetPath Target location
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
* will be overwriten if this is `true`. Default: `false`.
*/
extractAllTo(targetPath: string, overwrite?: boolean): void;
/**
* Extracts the entire archive to the given location
* @param targetPath Target location
* Extracts the entire archive to the given location.
* @param targetPath Target location.
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
* @param callback The callback function will be called afeter extraction
* will be overwriten if this is `true`. Default: `false`.
* @param callback The callback function will be called after extraction.
*/
extractAllToAsync(targetPath: string, overwrite: boolean, callback: (error: Error) => void): void;
extractAllToAsync(
targetPath: string,
overwrite?: boolean,
callback?: (error: Error) => void
): void;
/**
* Writes the newly created zip file to disk at the specified location or
* if a zip was opened and no ``targetFileName`` is provided, it will
* overwrite the opened zip
* @param targetFileName
* if a zip was opened and no `targetFileName` is provided, it will
* overwrite the opened zip.
*/
writeZip(targetPath?: string): void;
writeZip(targetFileName?: string, callback?: (error: Error | null) => void): void;
/**
* Returns the content of the entire zip file as a Buffer object
* @return Buffer
* Returns the content of the entire zip file.
*/
toBuffer(): Buffer;
}
declare namespace AdmZip {
/**
* The ZipEntry is more than a structure representing the entry inside the
* The `IZipEntry` is more than a structure representing the entry inside the
* zip file. Beside the normal attributes and headers a entry can have, the
* class contains a reference to the part of the file where the compressed
* data resides and decompresses it when requested. It also compresses the
* data and creates the headers required to write in the zip file.
*/
// disable warning about the I-prefix in interface name to prevent breaking stuff for users without a major bump
// tslint:disable-next-line:interface-name
interface IZipEntry {
/**
* Represents the full name and path of the file
*/
entryName: string;
rawEntryName: Buffer;
readonly rawEntryName: Buffer;
/**
* Extra data associated with this entry.
*/
@@ -256,15 +197,16 @@ declare namespace AdmZip {
* Entry comment.
*/
comment: string;
name: string;
readonly name: string;
/**
* Read-Only property that indicates the type of the entry.
*/
isDirectory: boolean;
readonly isDirectory: boolean;
/**
* Get the header associated with this ZipEntry.
*/
header: Buffer;
attr: number;
/**
* Retrieve the compressed data for this entry. Note that this may trigger
* compression if any properties were modified.
@@ -278,11 +220,7 @@ declare namespace AdmZip {
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: string): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: Buffer): void;
setData(value: string | Buffer): void;
/**
* Get the decompressed data associated with this entry.
*/

View File

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

View File

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

View File

@@ -30,7 +30,7 @@ declare namespace adone.collection {
/**
* Ends the stream
*/
end(chunk?: Buffer): void;
end(chunk?: Buffer | string): void;
end(chunk?: () => void): void;
/**

View File

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

View File

@@ -2,7 +2,7 @@
// Project: https://github.com/ciferox/adone
// Definitions by: am <https://github.com/s0m3on3>, Maximus <https://github.com/maxveres>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
/// <reference path="./adone.d.ts" />
/// <reference path="./glosses/app.d.ts" />

View File

@@ -223,7 +223,7 @@ namespace adoneTests.system.process {
});
ret.on("message", () => {});
ret.stdout.pipe(adone.fs.createWriteStream(__filename));
ret.stdout!.pipe(adone.fs.createWriteStream(__filename));
}
}
@@ -811,7 +811,7 @@ namespace adoneTests.system.process {
});
ret.on("message", () => {});
ret.stdout.pipe(adone.fs.createWriteStream(__filename));
ret.stdout!.pipe(adone.fs.createWriteStream(__filename));
}
}

View File

@@ -13,6 +13,7 @@
"no-unnecessary-qualifier": false,
"unified-signatures": false,
"space-before-function-paren": false,
"await-promise": false
"await-promise": false,
"no-restricted-globals": false
}
}
}

View File

@@ -0,0 +1,10 @@
import * as aesjs from 'aes-js';
const key = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const data: Uint8Array = aesjs.utils.utf8.toBytes('hello world');
const ecb = new aesjs.ModeOfOperation.ecb(key);
ecb.decrypt(ecb.encrypt(data));
const hex: string = aesjs.utils.hex.fromBytes(data);

134
types/aes-js/index.d.ts vendored Normal file
View File

@@ -0,0 +1,134 @@
// Type definitions for aes-js 3.1
// Project: https://github.com/ricmoo/aes-js
// Definitions by: Federico Bond <https://github.com/federicobond>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export type ByteSource = ArrayBuffer | Uint8Array | number[];
export class AES {
/**
* Create a new AES block cipher.
* @param key The cipher key.
*/
constructor(key: ByteSource)
encrypt(v: ByteSource): ByteSource;
}
/**
* Create a new Counter state for CTR cipher mode.
* @param initialValue The Counter initial value.
*/
export class Counter {
constructor(initialValue: number)
setValue(value: number): void;
setBytes(bytes: ByteSource): void;
increment(): void;
}
export namespace ModeOfOperation {
class ModeOfOperationECB {
/**
* Create a new ECB stream cipher.
* @param key The cipher key.
*/
constructor(key: ByteSource)
encrypt(v: ByteSource): Uint8Array;
decrypt(v: ByteSource): Uint8Array;
}
class ModeOfOperationCBC {
/**
* Create a new CBC stream cipher.
* @param key The cipher key.
* @param iv The cipher initialization vector.
*/
constructor(key: ByteSource, iv: ByteSource);
encrypt(v: ByteSource): Uint8Array;
decrypt(v: ByteSource): Uint8Array;
}
class ModeOfOperationCFB {
/**
* Create a new CFB stream cipher.
* @param key The cipher key.
* @param iv The cipher initialization vector.
* @param segmentSize The cipher segment size.
*/
constructor(key: ByteSource, iv: ByteSource, segmentSize: number);
encrypt(v: ByteSource): Uint8Array;
decrypt(v: ByteSource): Uint8Array;
}
class ModeOfOperationOFB {
/**
* Create a new OFB stream cipher.
* @param key The cipher key.
* @param iv The cipher initialization vector.
*/
constructor(key: ByteSource, iv: ByteSource);
encrypt(v: ByteSource): Uint8Array;
decrypt(v: ByteSource): Uint8Array;
}
class ModeOfOperationCTR {
/**
* Create a new CTR stream cipher.
* @param key The cipher key.
* @param counter The cipher counter state.
*/
constructor(key: ByteSource, counter?: Counter)
encrypt(v: ByteSource): Uint8Array;
decrypt(v: ByteSource): Uint8Array;
}
const ecb: typeof ModeOfOperationECB;
const cbc: typeof ModeOfOperationCBC;
const cfb: typeof ModeOfOperationCFB;
const ofb: typeof ModeOfOperationOFB;
const ctr: typeof ModeOfOperationCTR;
}
export namespace utils {
namespace utf8 {
/**
* Convert a UTF8 encoded string to a Uint8Array.
* @param data The input string.
*/
function toBytes(data: string): Uint8Array;
/**
* Convert an array-like object containing UTF8 data to a string.
* @param data The input data.
*/
function fromBytes(data: ByteSource): string;
}
namespace hex {
/**
* Convert a hexadecimal string to a Uint8Array.
* @param data The input string.
*/
function toBytes(data: string): Uint8Array;
/**
* Convert an array-like object to a hexadecimal string.
* @param data The input data.
*/
function fromBytes(data: ByteSource): string;
}
}
export namespace padding {
namespace pkcs7 {
/**
* Add standard PKCS7 padding to an array.
* @param data The input data.
*/
function pad(data: ByteSource): Uint8Array;
/**
* Remove standard PKCS7 padding from an array.
* @param data The input data.
*/
function strip(data: ByteSource): Uint8Array;
}
}

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",
"aes-js-tests.ts"
]
}

View File

@@ -1,119 +0,0 @@
// Global
const threeCamera = new AFRAME.THREE.Camera();
AFRAME.TWEEN.Easing;
// Entity
const entity = document.createElement('a-entity');
entity.emit('rotate');
entity.emit('collide', { target: entity });
entity.emit('sink', null, false);
const position = entity.getAttribute('position');
position.x;
position.y;
position.z;
entity.setAttribute('material', 'color', 'red');
entity.components['geometry'].data;
type MyEntity = AFrame.Entity<{
camera: THREE.Camera;
material: THREE.Material;
sound: { pause(): void };
}>;
const camera = (document.querySelector('a-entity[camera]') as MyEntity).components.camera;
const material = (document.querySelector('a-entity[material]') as MyEntity).components.material;
(document.querySelector('a-entity[sound]') as MyEntity).components.sound.pause();
entity.getDOMAttribute('geometry').primitive;
entity.setAttribute('light', {
type: 'spot',
distance: 30,
intensity: 2.0
});
entity.addEventListener('child-detached', (event) => {
event.detail;
});
// Components
interface TestComponent extends AFrame.Component {
multiply: (f: number) => number;
data: {
myProperty: any[],
string: string,
num: number
};
system: TestSystem;
}
const Component = AFRAME.registerComponent<TestComponent>('test-component', {
schema: {
myProperty: {
default: [],
parse() { return [true]; },
},
string: { type: 'string' },
num: 0
},
init() {
this.data.num = 0;
},
update() {},
tick() {},
remove() {},
pause() {},
play() {},
multiply(this: TestComponent, f: number) {
// Reference to system because both were registered with the same name.
return f * this.data.num * this.system.data.counter;
}
});
// Scene
const scene = document.querySelector('a-scene');
scene.hasLoaded;
// System
interface TestSystem extends AFrame.System {
data: {
counter: number;
};
}
const testSystem: AFrame.SystemDefinition<TestSystem> = {
schema: {
counter: 0
},
init() {
this.data.counter = 1;
}
};
AFRAME.registerSystem('test-component', testSystem);
// Register Custom Geometry
interface TestGeometry extends AFrame.Geometry {
schema: AFrame.MultiPropertySchema<{
groupIndex: number;
}>;
}
AFRAME.registerGeometry<TestGeometry>('a-test-geometry', {
schema: {
groupIndex: { default: 0 }
},
init(data) {
this.geometry = new THREE.Geometry();
const temp = data.groupIndex;
temp;
}
});

View File

@@ -1,345 +1,492 @@
// Type definitions for AFRAME 0.7
// Type definitions for AFRAME 0.8
// Project: https://aframe.io/
// Definitions by: Paul Shannon <https://github.com/devpaul>
// Roberto Ritger <https://github.com/bertoritger>
// Trygve Wastvedt <https://github.com/twastvedt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 2.8
/**
* Extended tests available at https://github.com/devpaul/aframe-typings.git
* Extended tests and examples available at https://github.com/devpaul/aframe-experiments.git
*/
/// <reference types="three" />
/// <reference types="tween.js" />
// Globals
declare var AFRAME: AFrame.AFrameGlobal;
declare var hasNativeWebVRImplementation: boolean;
import * as three from 'three';
import * as tween from '@tweenjs/tween.js';
interface Document {
createElement(tagName: string): AFrame.Entity;
querySelector(selectors: 'a-scene'): AFrame.Scene;
querySelector(selectors: string): AFrame.Entity<any>;
querySelectorAll(selectors: string): NodeListOf<AFrame.Entity<any> | Element>;
export type ThreeLib = typeof three;
export type TweenLib = typeof tween;
export interface ObjectMap<T = any> {
[key: string]: T;
}
// Interfaces
declare namespace AFrame {
interface ObjectMap<T = any> {
[ key: string ]: T;
}
export interface Animation {
attribute: string;
begin: string | number;
delay: number;
direction: 'alternate' | 'alternateReverse' | 'normal' | 'reverse';
dur: number;
easing(): void;
end: string;
fill: 'backwards' | 'both' | 'forwards' | 'none';
from: any; // TODO type
repeat: number | 'indefinite';
to: number;
}
interface AFrameGlobal {
AEntity: Entity;
ANode: ANode;
AScene: Scene;
components: { [ key: string ]: ComponentDescriptor };
geometries: { [ key: string ]: GeometryDescriptor };
primitives: { [ key: string ]: Entity };
registerComponent<T extends Component>(name: string, component: ComponentDefinition<T>): ComponentConstructor<T>;
registerElement(name: string, element: ANode): void;
registerGeometry<T extends Geometry>(name: string, geometry: GeometryDefinition<T>): GeometryConstructor<T>;
registerPrimitive(name: string, primitive: PrimitiveDefinition): void;
registerShader<T extends Shader>(name: string, shader: T): ShaderConstructor<T>;
registerSystem<T extends System>(name: string, definition: SystemDefinition<T>): SystemConstructor<T>;
schema: SchemaUtils;
shaders: { [ key: string ]: ShaderDescriptor };
systems: { [key: string]: SystemConstructor };
THREE: typeof THREE;
TWEEN: typeof TWEEN;
utils: Utils;
version: string;
}
export interface ANode extends HTMLElement {
// Only public APIs added. Many methods intentionally left out.
// createdCallback
// attachedCallback
// attributeChangedCallback
closestScene(): Scene;
closest(selector: string): ANode;
// detachedCallback
hasLoaded: boolean;
load(cb?: () => void, childFilter?: (el: Element) => boolean): void;
// updateMixins
registerMixin(id: string): void;
setAttribute(type: string, newValue: any): void;
unregisterMixin(id: string): void;
removeMixinListener(id: string): void;
attachMixinListener(mixin: HTMLElement): void;
emit(name: string, detail?: any, bubbles?: boolean): void;
emitter(name: string, detail?: any, bubbles?: boolean): () => void;
}
interface Animation {
attribute: string;
begin: string | number;
delay: number;
direction: 'alternate' | 'alternateReverse' | 'normal' | 'reverse';
dur: number;
easing(): void;
end: string;
fill: 'backwards' | 'both' | 'forwards' | 'none';
from: any; // TODO type
repeat: number | 'indefinite';
to: number;
}
export interface Behavior {
tick(): void;
}
interface ANode extends HTMLElement {
// Only public APIs added. Many methods intentionally left out.
// createdCallback
// attachedCallback
// attributeChangedCallback
closestScene(): Scene;
closest(selector: string): ANode;
// detachedCallback
hasLoaded: boolean;
load(cb?: () => void, childFilter?: (el: Element) => boolean): void;
// updateMixins
registerMixin(id: string): void;
setAttribute(type: string, newValue: any): void;
unregisterMixin(id: string): void;
removeMixinListener(id: string): void;
attachMixinListener(mixin: HTMLElement): void;
emit(name: string, detail?: any, bubbles?: boolean): void;
emitter(name: string, detail?: any, bubbles?: boolean): () => void;
}
export interface Component<T extends object = any, S extends System = System> {
attrName?: string;
data: T;
dependencies?: string[];
el: Entity;
id: string;
multiple?: boolean;
name: string;
schema: Schema<T>;
system: S | undefined;
interface Behavior {
tick(): void;
}
init(data?: T): void;
pause(): void;
play(): void;
remove(): void;
tick?(time: number, timeDelta: number): void;
update(oldData: T): void;
updateSchema?(): void;
interface Component<T extends { [key: string]: any } = any, S extends System = System> {
attrName?: string;
data: T;
dependencies?: string[];
el: Entity;
id: string;
multiple?: boolean;
extendSchema(update: Schema): void;
flushToDOM(): void;
}
export interface ComponentConstructor<T extends object> {
new (el: Entity, attrValue: string, id: string): T & Component;
prototype: T & {
name: string;
schema: Schema<T>;
system: S | undefined;
init(this: this, data?: T): void;
pause(this: this): void;
play(this: this): void;
remove(this: this): void;
tick?(this: this, time: number, timeDelta: number): void;
update(this: this, oldData: T): void;
updateSchema?(this: this): void;
extendSchema(this: this, update: Schema): void;
flushToDOM(this: this): void;
}
interface ComponentConstructor<T extends Component> {
new (el: Entity, attrValue: string, id: string): T;
}
type ComponentDefinition<T extends Component = Component> = Partial<T>;
interface ComponentDescriptor<T extends Component = Component> {
Component: ComponentConstructor<T>;
dependencies: string[] | undefined;
multiple: boolean | undefined;
// internal APIs2
// parse
// parseAttrValueForCache
// schema
// stringify
// type
}
interface Coordinate {
x: number;
y: number;
z: number;
}
interface DefaultComponents {
position: Component<Coordinate>;
rotation: Component<Coordinate>;
scale: Component<Coordinate>;
}
interface Entity<C = ObjectMap<Component>> extends ANode {
components: C & DefaultComponents;
isPlaying: boolean;
object3D: THREE.Object3D;
object3DMap: ObjectMap<THREE.Object3D>;
sceneEl?: Scene;
addState(name: string): void;
flushToDOM(recursive?: boolean): void;
/**
* @deprecated since 0.4.0
*/
getComputedAttribute(attr: string): Component;
getDOMAttribute(attr: string): any;
getObject3D(type: string): THREE.Object3D;
getOrCreateObject3D(type: string, construct: any): THREE.Object3D;
is(stateName: string): boolean;
pause(): void;
system: System;
play(): void;
setObject3D(type: string, obj: THREE.Object3D): void;
removeAttribute(attr: string, property?: string): void;
removeObject3D(type: string): void;
removeState(stateName: string): void;
// getAttribute specific usages
getAttribute(type: string): any;
getAttribute(type: 'position' | 'rotation' | 'scale'): Coordinate;
// setAttribute specific usages
setAttribute(attr: string, value: any): void;
setAttribute(attr: string, property: string, componentAttrValue?: any): void;
setAttribute(type: 'position' | 'rotation' | 'scale', value: Coordinate): void;
// addEventListener specific usages
addEventListener<K extends keyof EntityEventMap>(type: K, listener: (event: Event & EntityEventMap[K]) => void, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
type DetailEvent<D> = Event & {
detail: D;
target: EventTarget & Entity;
pause(): void;
};
}
interface EntityEventMap {
'child-attached': DetailEvent<{ el: Element | Entity }>;
'child-detached': DetailEvent<{ el: Element | Entity }>;
'componentchanged': DetailEvent<{
name: string,
id: string
}>;
'componentremoved': DetailEvent<{
name: string,
id: string,
newData: any,
oldData: any
}>;
'loaded': EventListener;
'pause': EventListener;
'play': EventListener;
'stateadded': DetailEvent<{ state: string }>;
'stateremoved': DetailEvent<{ state: string }>;
'schemachanged': DetailEvent<{ componentName: string }>;
}
export interface ComponentDescriptor<T extends Component = Component> {
Component: ComponentConstructor<T>;
dependencies: string[] | undefined;
multiple: boolean | undefined;
interface Geometry {
// internal APIs2
// parse
// parseAttrValueForCache
// schema
// stringify
// type
}
export interface Coordinate {
x: number;
y: number;
z: number;
}
export interface DefaultComponents {
position: Component<Coordinate>;
rotation: Component<Coordinate>;
scale: Component<Coordinate>;
}
export interface Entity<C = ObjectMap<Component>> extends ANode {
components: C & DefaultComponents;
isPlaying: boolean;
object3D: THREE.Object3D;
object3DMap: ObjectMap<THREE.Object3D>;
sceneEl?: Scene;
addState(name: string): void;
flushToDOM(recursive?: boolean): void;
/**
* @deprecated since 0.4.0
*/
getComputedAttribute(attr: string): Component;
getDOMAttribute(attr: string): any;
getObject3D(type: string): THREE.Object3D;
getOrCreateObject3D(type: string, construct: any): THREE.Object3D;
is(stateName: string): boolean;
pause(): void;
play(): void;
setObject3D(type: string, obj: THREE.Object3D): void;
removeAttribute(attr: string, property?: string): void;
removeObject3D(type: string): void;
removeState(stateName: string): void;
// getAttribute specific usages
getAttribute(type: string): any;
getAttribute(type: 'position' | 'rotation' | 'scale'): Coordinate;
// setAttribute specific usages
setAttribute(attr: string, value: any): void;
setAttribute(attr: string, property: string, componentAttrValue?: any): void;
setAttribute(type: 'position' | 'rotation' | 'scale', value: Coordinate): void;
// addEventListener specific usages
addEventListener<K extends keyof EntityEventMap>(
type: K,
listener: (event: Event & EntityEventMap[K]) => void,
useCapture?: boolean
): void;
addEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
useCapture?: boolean
): void;
}
export type DetailEvent<D> = Event & {
detail: D;
target: EventTarget & Entity;
};
export interface EntityEventMap {
'child-attached': DetailEvent<{ el: Element | Entity }>;
'child-detached': DetailEvent<{ el: Element | Entity }>;
componentchanged: DetailEvent<{
name: string;
geometry: THREE.Geometry;
schema: Schema<any>;
id: string;
}>;
componentremoved: DetailEvent<{
name: string;
id: string;
newData: any;
oldData: any;
}>;
loaded: EventListener;
pause: EventListener;
play: EventListener;
stateadded: DetailEvent<{ state: string }>;
stateremoved: DetailEvent<{ state: string }>;
schemachanged: DetailEvent<{ componentName: string }>;
}
init(this: this, data: { [P in keyof this['schema']]: any }): void;
// Would like the above to be:
// init?(this: this, data?: { [P in keyof T['schema']]: T['schema'][P]['default'] } ): void;
// I think this is prevented by the following issue: https://github.com/Microsoft/TypeScript/issues/21760.
}
export interface Geometry<T = any> {
data: T;
name: string;
geometry: THREE.Geometry;
schema: Schema<any>;
interface GeometryConstructor<T extends Geometry> {
new (): T;
}
init(data: any): void;
}
type GeometryDefinition<T extends Geometry = Geometry> = Partial<T>;
export interface GeometryConstructor<T extends object = object> {
new (): T & Geometry;
}
interface GeometryDescriptor<T extends Geometry = Geometry> {
Geometry: GeometryConstructor<T>;
schema: Schema;
}
export interface GeometryDescriptor<T extends Geometry = Geometry> {
Geometry: GeometryConstructor<T>;
schema: Schema;
}
type MultiPropertySchema<T extends { [key: string ]: any }> = {
[P in keyof T]: SinglePropertySchema<T[P]> | T[P];
export type MultiPropertySchema<T extends object> = {
[P in keyof T]: SinglePropertySchema<T[P]> | T[P]
};
export type PropertyTypes =
| 'array'
| 'asset'
| 'audio'
| 'boolean'
| 'color'
| 'int'
| 'map'
| 'model'
| 'number'
| 'selector'
| 'selectorAll'
| 'string'
| 'vec2'
| 'vec3'
| 'vec4';
export type SceneEvents = 'enter-vr' | 'exit-vr' | 'loaded' | 'renderstart';
export interface Scene extends Entity {
behaviors: Behavior[];
camera: THREE.Camera;
canvas: HTMLCanvasElement;
effect: THREE.VREffect;
isMobile: boolean;
object3D: THREE.Scene;
renderer: THREE.WebGLRenderer;
renderStarted: boolean;
systems: ObjectMap<System>;
time: number;
enterVR(): Promise<void> | void;
exitVR(): Promise<void> | void;
reload(): void;
addEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
useCapture?: boolean
): void;
addEventListener(type: SceneEvents, listener: EventListener, useCapture?: boolean): void;
}
export type Schema<T extends object = object> = SinglePropertySchema<T> | MultiPropertySchema<T>;
export interface SchemaUtils {
isSingleProperty(schema: Schema): boolean;
process(schema: Schema): boolean;
}
export interface Shader {
name: string;
data: object;
schema: Schema<this['data']>;
material: THREE.Material;
vertexShader: string;
fragmentShader: string;
init(data?: this['data']): void;
tick?(time: number, timeDelta: number): void;
update(oldData: this['data']): void;
}
export interface ShaderConstructor<T extends object> {
new (): T;
}
export interface ShaderDescriptor<T extends Shader = Shader> {
Shader: ShaderConstructor<T>;
schema: Schema;
}
export interface SinglePropertySchema<T> {
type?: PropertyTypes;
default?: T;
parse?(value: string): T;
stringify?(value: T): string;
}
export interface System<T extends object = any> {
data: T;
schema: Schema<T>;
init(): void;
pause(): void;
play(): void;
tick?(t: number, dt: number): void;
}
export interface SystemConstructor<T extends object = object> {
new (scene: Scene): T & System;
}
export interface Utils {
coordinates: {
isCoordinate(value: string): boolean;
parse(value: string): Coordinate;
stringify(coord: Coordinate): string;
};
entity: {
getComponentProperty(entity: Entity, componentName: string, delimiter?: string): any;
setComponentProperty(
entity: Entity,
componentName: string,
value: any,
delimiter?: string
): void;
};
device: {
isWebXRAvailable: boolean;
getVRDisplay(): VRDisplay[];
checkHeadsetConnected(): boolean;
checkHasPositionalTracking(): boolean;
isMobile(): boolean;
isTablet(): boolean;
isIOS(): boolean;
isGearVR(): boolean;
isOculusGo(): boolean;
isR7(): boolean;
isLandscape(): boolean;
isBrowserEnvironment(): boolean;
isNodeEnvironment(): boolean;
PolyfillControls(object3D: THREE.Object3D): void;
};
styleParser: {
parse(value: string): object;
stringify(data: object): string;
};
deepEqual(a: any, b: any): boolean;
diff(a: object, b: object): object;
extend(target: object, ...source: object[]): object;
extendDeep(target: object, ...source: object[]): object;
interface PrimitiveDefinition {
defaultComponents?: any; // TODO cleanup type
deprecated?: boolean;
mappings?: any; // TODO cleanup type
transforms?: any; // TODO cleanup type
}
throttle(
tickFunction: () => void,
minimumInterval: number,
optionalContext?: {}
): (t: number, dt: number) => void;
throttleTick(
tickFunction: (t: number, dt: number) => void,
minimumInterval: number,
optionalContext?: {}
): (t: number, dt: number) => void;
}
type PropertyTypes = 'array' | 'asset' | 'audio' | 'boolean' | 'color' |
'int' | 'map' | 'model' | 'number' | 'selector' | 'selectorAll' |
'string' | 'vec2' | 'vec3' | 'vec4';
// Definitions
// used as mixins to register functions to create classes (newable functions) in A-Frame
export type ComponentDefinition<T extends object = object> = T & Partial<Component> & ThisType<T & Component>;
export type GeometryDefinition<T extends object = object, U = any> = T & Partial<Geometry<U>>;
export type NodeDefinition<T extends object = object> = T & Partial<ANode>;
export interface PrimitiveDefinition {
defaultComponents?: any; // TODO cleanup type
deprecated?: boolean;
mappings?: any; // TODO cleanup type
transforms?: any; // TODO cleanup type
}
export interface MinimalShaderDefinition {
schema: Shader['schema'];
}
export type ShaderDefinition<T extends object = MinimalShaderDefinition & object> = T &
Partial<Shader>;
export type SystemDefinition<T extends object = object> = T & Partial<System>;
type SceneEvents = 'enter-vr' | 'exit-vr' | 'loaded' | 'renderstart';
// root export
export interface AFrame {
AComponent: Component;
AEntity: Entity;
ANode: ANode;
AScene: Scene;
interface Scene extends Entity {
behaviors: Behavior[];
camera: THREE.Camera;
canvas: HTMLCanvasElement;
effect: THREE.VREffect;
isMobile: boolean;
object3D: THREE.Scene;
renderer: THREE.WebGLRenderer;
renderStarted: boolean;
systems: ObjectMap<System>;
time: number;
enterVR(): Promise<void> | void;
exitVR(): Promise<void> | void;
reload(): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
addEventListener(type: SceneEvents, listener: EventListener, useCapture?: boolean): void;
}
type Schema<T = { [key: string]: any }> = SinglePropertySchema<T> | MultiPropertySchema<T>;
interface SchemaUtils {
isSingleProperty(schema: Schema): boolean;
process(schema: Schema): boolean;
}
interface Shader {
name: string;
data: { [key: string]: any };
schema: Schema<this['data']>;
material: THREE.Material;
vertexShader: string;
fragmentShader: string;
init(this: this, data?: this['data']): void;
tick?(this: this, time: number, timeDelta: number): void;
update(this: this, oldData: this['data']): void;
}
interface ShaderConstructor<T extends Shader> {
new (): T;
}
type ShaderDefinition<T extends Shader = Shader> = Partial<T>;
interface ShaderDescriptor<T extends Shader = Shader> {
Shader: ShaderConstructor<T>;
schema: Schema;
}
interface SinglePropertySchema<T> {
type?: PropertyTypes;
'default'?: T;
parse?(value: string): T;
stringify?(value: T): string;
}
interface System {
data: { [key: string]: any };
schema: Schema<this['data']>;
init(this: this): void;
pause(this: this): void;
play(this: this): void;
tick?(this: this, t: number, dt: number): void;
}
interface SystemConstructor<T extends System = System> {
new (scene: Scene): T;
}
type SystemDefinition<T extends System = System> = Partial<T>;
interface Utils {
coordinates: {
isCoordinate(value: string): boolean;
parse(value: string): Coordinate;
stringify(coord: Coordinate): string;
components: ObjectMap<ComponentDescriptor>;
geometries: ObjectMap<GeometryDescriptor>;
primitives: {
getMeshMixin(): {
defaultComponents: { material: object };
mappings: { [key: string]: any }; // TODO improve any type
};
entity: {
getComponentProperty(entity: Entity, componentName: string, delimiter?: string): any;
setComponentProperty(entity: Entity, componentName: string, value: any, delimiter?: string): void;
};
styleParser: {
parse(value: string): object;
stringify(data: object): string;
};
deepEqual(a: any, b: any): boolean;
diff(a: object, b: object): object;
extend(target: object, ... source: object[]): object;
extendDeep(target: object, ... source: object[]): object;
primitives: ObjectMap<Entity>;
};
scenes: Scene[];
schema: SchemaUtils;
shaders: ObjectMap<ShaderDescriptor>;
systems: ObjectMap<SystemConstructor>;
THREE: ThreeLib;
TWEEN: TweenLib;
utils: Utils;
version: string;
throttle(tickFunction: () => void, minimumInterval: number, optionalContext?: {}): (t: number, dt: number) => void;
throttleTick(tickFunction: (t: number, dt: number) => void, minimumInterval: number, optionalContext?: {}): (t: number, dt: number) => void;
registerComponent<T extends object>(
name: string,
component: ComponentDefinition<T>
): ComponentConstructor<T>;
registerElement(name: string, element: object): void;
registerGeometry<T extends object>(
name: string,
geometry: GeometryDefinition<T>
): GeometryConstructor<T>;
registerPrimitive(name: string, primitive: PrimitiveDefinition): void;
registerShader<T extends MinimalShaderDefinition & object>(
name: string,
shader: ShaderDefinition<T>
): ShaderConstructor<T>;
registerSystem<T extends object>(
name: string,
definition: SystemDefinition<T>
): SystemConstructor<T>;
}
// module.exports
export const AComponent: AFrame['AComponent'];
export const AEntity: AFrame['AEntity'];
export const ANode: AFrame['ANode'];
export const AScene: AFrame['AScene'];
export const components: AFrame['components'];
export const geometries: AFrame['geometries'];
export const primitives: AFrame['primitives'];
export const scenes: AFrame['scenes'];
export const schema: AFrame['schema'];
export const shaders: AFrame['shaders'];
export const systems: AFrame['systems'];
export const THREE: AFrame['THREE'];
export const TWEEN: AFrame['TWEEN'];
export const utils: AFrame['utils'];
export const version: AFrame['version'];
export const registerComponent: AFrame['registerComponent'];
export const registerElement: AFrame['registerElement'];
export const registerGeometry: AFrame['registerGeometry'];
export const registerPrimitive: AFrame['registerPrimitive'];
export const registerShader: AFrame['registerShader'];
export const registerSystem: AFrame['registerSystem'];
// global exports
declare global {
var hasNativeWebVRImplementation: boolean;
namespace AFRAME {
const AComponent: AFrame['AComponent'];
const AEntity: AFrame['AEntity'];
const ANode: AFrame['ANode'];
const AScene: AFrame['AScene'];
const components: AFrame['components'];
const geometries: AFrame['geometries'];
const primitives: AFrame['primitives'];
const scenes: AFrame['scenes'];
const schema: AFrame['schema'];
const shaders: AFrame['shaders'];
const systems: AFrame['systems'];
const THREE: AFrame['THREE'];
const TWEEN: AFrame['TWEEN'];
const utils: AFrame['utils'];
const version: string;
const registerComponent: AFrame['registerComponent'];
const registerElement: AFrame['registerElement'];
const registerGeometry: AFrame['registerGeometry'];
const registerPrimitive: AFrame['registerPrimitive'];
const registerShader: AFrame['registerShader'];
const registerSystem: AFrame['registerSystem'];
}
/**
* Custom elements augment document methods to return custom HTML
*/
interface Document {
createElement(tagName: string): Entity;
querySelector(selectors: 'a-scene'): Scene;
querySelector(selectors: string): Entity<any>;
querySelectorAll(selectors: string): NodeListOf<Entity<any> | Element>;
}
interface HTMLCollection extends HTMLCollectionBase {
/**
* Retrieves a select object or an object from an options collection.
*/
namedItem(name: string): Element | Entity | null;
item(index: number): Element | Entity;
[index: number]: Element | Entity;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,121 @@
import {
Component,
Entity,
MultiPropertySchema,
System,
SystemDefinition,
THREE,
Geometry,
registerComponent
} from 'aframe';
// Global
const threeCamera = new AFRAME.THREE.Camera();
AFRAME.TWEEN.Easing;
// Entity
const entity = document.createElement('a-entity');
entity.emit('rotate');
entity.emit('collide', { target: entity });
entity.emit('sink', null, false);
const position = entity.getAttribute('position');
position.x;
position.y;
position.z;
entity.setAttribute('material', 'color', 'red');
entity.components['geometry'].data;
type MyEntity = Entity<{
camera: THREE.Camera;
material: THREE.Material;
sound: { pause(): void };
}>;
const camera = (document.querySelector('a-entity[camera]') as MyEntity).components.camera;
const material = (document.querySelector('a-entity[material]') as MyEntity).components.material;
(document.querySelector('a-entity[sound]') as MyEntity).components.sound.pause();
entity.getDOMAttribute('geometry').primitive;
entity.setAttribute('light', {
type: 'spot',
distance: 30,
intensity: 2.0
});
entity.addEventListener('child-detached', event => {
event.detail;
});
// Components
// interface TestComponent extends Component {
// multiply: (f: number) => number;
//
// data: {
// myProperty: any[],
// string: string,
// num: number
// };
//
// system: TestSystem;
// }
const Component = registerComponent('test-component', {
schema: {
myProperty: {
default: [],
parse() {
return [true];
}
},
string: { type: 'string' },
num: 0
},
init() {
this.data.num = 0;
this.el.setAttribute('custom-attribute', 'custom-value');
},
update() {},
tick() {},
remove() {},
pause() {},
play() {},
multiply(f: number) {
// Reference to system because both were registered with the same name.
return f * this.data.num * this.system!.data.counter;
}
});
// Scene
const scene = document.querySelector('a-scene');
scene.hasLoaded;
// System
const testSystem: SystemDefinition = {
schema: {
counter: 0
},
init() {
this.data.counter = 1;
}
};
AFRAME.registerSystem('test-component', testSystem);
// Register Custom Geometry
AFRAME.registerGeometry('a-test-geometry', {
schema: {
groupIndex: { default: 0 }
},
init(data) {
this.geometry = new THREE.Geometry();
const temp = data.groupIndex;
temp;
}
});

View File

@@ -21,6 +21,7 @@
},
"files": [
"index.d.ts",
"aframe-tests.ts"
"test/aframe-tests.ts",
"test/aframe-io-tests.ts"
]
}
}

View File

@@ -1,10 +1,14 @@
import Agenda = require("agenda");
import { Db, Server } from "mongodb";
import { Db, Server, MongoClient } from "mongodb";
var mongoConnectionString = "mongodb://127.0.0.1/agenda";
(async () => {
var agenda = new Agenda({ db: { address: mongoConnectionString } });
var agenda = new Agenda({
mongo: (await MongoClient.connect(mongoConnectionString)).db(),
db: { collection: 'agenda-jobs' },
});
agenda.define<{ foo: Error }>('delete old users', (job, done) => {
done(job.attrs.data.foo)

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;
@@ -203,17 +203,7 @@ declare namespace Agenda {
/**
* Specifies that Agenda should be initialized using and existing MongoDB connection.
*/
mongo?: {
/**
* The MongoDB database connection to use.
*/
db: Db;
/**
* The name of the collection to use.
*/
collection?: string;
}
mongo?: Db;
/**
* Specifies that Agenda should connect to MongoDB.
@@ -221,8 +211,10 @@ declare namespace Agenda {
db?: {
/**
* The connection URL.
* Required when using `db` option to connect.
* Not required when an existing connection is passed as `mongo` property.
*/
address: string;
address?: string;
/**
* The name of the collection to use.
@@ -231,6 +223,7 @@ declare namespace Agenda {
/**
* Connection options to pass to MongoDB.
* Not required when an existing connection is passed as `mongo` property.
*/
options?: any;
}

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